babylon.max.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. * @hidden
  608. */
  609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  610. var _this = this;
  611. this._isReady = false;
  612. this._vertexSourceCodeOverride = vertexSourceCode;
  613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  614. this.onError = function (effect, error) {
  615. if (onError) {
  616. onError(error);
  617. }
  618. };
  619. this.onCompiled = function () {
  620. var scenes = _this.getEngine().scenes;
  621. for (var i = 0; i < scenes.length; i++) {
  622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  623. }
  624. if (onCompiled) {
  625. onCompiled(_this._program);
  626. }
  627. };
  628. this._fallbacks = null;
  629. this._prepareEffect();
  630. };
  631. /**
  632. * Gets the uniform locations of the the specified variable names
  633. * @param names THe names of the variables to lookup.
  634. * @returns Array of locations in the same order as variable names.
  635. */
  636. Effect.prototype.getSpecificUniformLocations = function (names) {
  637. var engine = this._engine;
  638. return engine.getUniforms(this._program, names);
  639. };
  640. /**
  641. * Prepares the effect
  642. * @hidden
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. BABYLON.Tools.Error("Error: " + this._compilationError);
  701. if (previousProgram) {
  702. this._program = previousProgram;
  703. this._isReady = true;
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. }
  709. if (fallbacks && fallbacks.isMoreFallbacks) {
  710. BABYLON.Tools.Error("Trying next fallback.");
  711. this.defines = fallbacks.reduce(this.defines, this);
  712. this._prepareEffect();
  713. }
  714. else { // Sorry we did everything we can
  715. if (this.onError) {
  716. this.onError(this, this._compilationError);
  717. }
  718. this.onErrorObservable.notifyObservers(this);
  719. this.onErrorObservable.clear();
  720. // Unbind mesh reference in fallbacks
  721. if (this._fallbacks) {
  722. this._fallbacks.unBindMesh();
  723. }
  724. }
  725. }
  726. };
  727. Object.defineProperty(Effect.prototype, "isSupported", {
  728. /**
  729. * Checks if the effect is supported. (Must be called after compilation)
  730. */
  731. get: function () {
  732. return this._compilationError === "";
  733. },
  734. enumerable: true,
  735. configurable: true
  736. });
  737. /**
  738. * Binds a texture to the engine to be used as output of the shader.
  739. * @param channel Name of the output variable.
  740. * @param texture Texture to bind.
  741. * @hidden
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  756. * @param channel Name of the sampler variable.
  757. * @param texture Texture to set.
  758. */
  759. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  760. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  761. };
  762. /**
  763. * Sets an array of textures on the engine to be used in the shader.
  764. * @param channel Name of the variable.
  765. * @param textures Textures to set.
  766. */
  767. Effect.prototype.setTextureArray = function (channel, textures) {
  768. if (this._samplers.indexOf(channel + "Ex") === -1) {
  769. var initialPos = this._samplers.indexOf(channel);
  770. for (var index = 1; index < textures.length; index++) {
  771. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  772. }
  773. }
  774. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  775. };
  776. /**
  777. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  778. * @param channel Name of the sampler variable.
  779. * @param postProcess Post process to get the input texture from.
  780. */
  781. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  782. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  783. };
  784. /**
  785. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  786. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  787. * @param channel Name of the sampler variable.
  788. * @param postProcess Post process to get the output texture from.
  789. */
  790. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  791. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  792. };
  793. /** @hidden */
  794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  795. var cache = this._valueCache[uniformName];
  796. var flag = matrix.updateFlag;
  797. if (cache !== undefined && cache === flag) {
  798. return false;
  799. }
  800. this._valueCache[uniformName] = flag;
  801. return true;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. return changed;
  821. };
  822. /** @hidden */
  823. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  824. var cache = this._valueCache[uniformName];
  825. if (!cache) {
  826. cache = [x, y, z];
  827. this._valueCache[uniformName] = cache;
  828. return true;
  829. }
  830. var changed = false;
  831. if (cache[0] !== x) {
  832. cache[0] = x;
  833. changed = true;
  834. }
  835. if (cache[1] !== y) {
  836. cache[1] = y;
  837. changed = true;
  838. }
  839. if (cache[2] !== z) {
  840. cache[2] = z;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /** @hidden */
  846. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  847. var cache = this._valueCache[uniformName];
  848. if (!cache) {
  849. cache = [x, y, z, w];
  850. this._valueCache[uniformName] = cache;
  851. return true;
  852. }
  853. var changed = false;
  854. if (cache[0] !== x) {
  855. cache[0] = x;
  856. changed = true;
  857. }
  858. if (cache[1] !== y) {
  859. cache[1] = y;
  860. changed = true;
  861. }
  862. if (cache[2] !== z) {
  863. cache[2] = z;
  864. changed = true;
  865. }
  866. if (cache[3] !== w) {
  867. cache[3] = w;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /**
  873. * Binds a buffer to a uniform.
  874. * @param buffer Buffer to bind.
  875. * @param name Name of the uniform variable to bind to.
  876. */
  877. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  878. var bufferName = this._uniformBuffersNames[name];
  879. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  880. return;
  881. }
  882. Effect._baseCache[bufferName] = buffer;
  883. this._engine.bindUniformBufferBase(buffer, bufferName);
  884. };
  885. /**
  886. * Binds block to a uniform.
  887. * @param blockName Name of the block to bind.
  888. * @param index Index to bind.
  889. */
  890. Effect.prototype.bindUniformBlock = function (blockName, index) {
  891. this._engine.bindUniformBlock(this._program, blockName, index);
  892. };
  893. /**
  894. * Sets an interger value on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param value Value to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setInt = function (uniformName, value) {
  900. var cache = this._valueCache[uniformName];
  901. if (cache !== undefined && cache === value)
  902. return this;
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value)
  1096. return this;
  1097. this._valueCache[uniformName] = value;
  1098. this._engine.setFloat(this.getUniform(uniformName), value);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a boolean on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param bool value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setBool = function (uniformName, bool) {
  1108. var cache = this._valueCache[uniformName];
  1109. if (cache !== undefined && cache === bool)
  1110. return this;
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. var KeyboardEventTypes = /** @class */ (function () {
  1269. function KeyboardEventTypes() {
  1270. }
  1271. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1272. get: function () {
  1273. return KeyboardEventTypes._KEYDOWN;
  1274. },
  1275. enumerable: true,
  1276. configurable: true
  1277. });
  1278. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1279. get: function () {
  1280. return KeyboardEventTypes._KEYUP;
  1281. },
  1282. enumerable: true,
  1283. configurable: true
  1284. });
  1285. KeyboardEventTypes._KEYDOWN = 0x01;
  1286. KeyboardEventTypes._KEYUP = 0x02;
  1287. return KeyboardEventTypes;
  1288. }());
  1289. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. function KeyboardInfo(type, event) {
  1292. this.type = type;
  1293. this.event = event;
  1294. }
  1295. return KeyboardInfo;
  1296. }());
  1297. BABYLON.KeyboardInfo = KeyboardInfo;
  1298. /**
  1299. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1300. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1301. */
  1302. var KeyboardInfoPre = /** @class */ (function (_super) {
  1303. __extends(KeyboardInfoPre, _super);
  1304. function KeyboardInfoPre(type, event) {
  1305. var _this = _super.call(this, type, event) || this;
  1306. _this.skipOnPointerObservable = false;
  1307. return _this;
  1308. }
  1309. return KeyboardInfoPre;
  1310. }(KeyboardInfo));
  1311. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1312. })(BABYLON || (BABYLON = {}));
  1313. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1314. var BABYLON;
  1315. (function (BABYLON) {
  1316. var PointerEventTypes = /** @class */ (function () {
  1317. function PointerEventTypes() {
  1318. }
  1319. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1320. get: function () {
  1321. return PointerEventTypes._POINTERDOWN;
  1322. },
  1323. enumerable: true,
  1324. configurable: true
  1325. });
  1326. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1327. get: function () {
  1328. return PointerEventTypes._POINTERUP;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1334. get: function () {
  1335. return PointerEventTypes._POINTERMOVE;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1341. get: function () {
  1342. return PointerEventTypes._POINTERWHEEL;
  1343. },
  1344. enumerable: true,
  1345. configurable: true
  1346. });
  1347. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1348. get: function () {
  1349. return PointerEventTypes._POINTERPICK;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1355. get: function () {
  1356. return PointerEventTypes._POINTERTAP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1362. get: function () {
  1363. return PointerEventTypes._POINTERDOUBLETAP;
  1364. },
  1365. enumerable: true,
  1366. configurable: true
  1367. });
  1368. PointerEventTypes._POINTERDOWN = 0x01;
  1369. PointerEventTypes._POINTERUP = 0x02;
  1370. PointerEventTypes._POINTERMOVE = 0x04;
  1371. PointerEventTypes._POINTERWHEEL = 0x08;
  1372. PointerEventTypes._POINTERPICK = 0x10;
  1373. PointerEventTypes._POINTERTAP = 0x20;
  1374. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1375. return PointerEventTypes;
  1376. }());
  1377. BABYLON.PointerEventTypes = PointerEventTypes;
  1378. var PointerInfoBase = /** @class */ (function () {
  1379. function PointerInfoBase(type, event) {
  1380. this.type = type;
  1381. this.event = event;
  1382. }
  1383. return PointerInfoBase;
  1384. }());
  1385. BABYLON.PointerInfoBase = PointerInfoBase;
  1386. /**
  1387. * This class is used to store pointer related info for the onPrePointerObservable event.
  1388. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1389. */
  1390. var PointerInfoPre = /** @class */ (function (_super) {
  1391. __extends(PointerInfoPre, _super);
  1392. function PointerInfoPre(type, event, localX, localY) {
  1393. var _this = _super.call(this, type, event) || this;
  1394. /**
  1395. * Ray from a pointer if availible (eg. 6dof controller)
  1396. */
  1397. _this.ray = null;
  1398. _this.skipOnPointerObservable = false;
  1399. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1400. return _this;
  1401. }
  1402. return PointerInfoPre;
  1403. }(PointerInfoBase));
  1404. BABYLON.PointerInfoPre = PointerInfoPre;
  1405. /**
  1406. * This type contains all the data related to a pointer event in Babylon.js.
  1407. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1408. */
  1409. var PointerInfo = /** @class */ (function (_super) {
  1410. __extends(PointerInfo, _super);
  1411. function PointerInfo(type, event, pickInfo) {
  1412. var _this = _super.call(this, type, event) || this;
  1413. _this.pickInfo = pickInfo;
  1414. return _this;
  1415. }
  1416. return PointerInfo;
  1417. }(PointerInfoBase));
  1418. BABYLON.PointerInfo = PointerInfo;
  1419. })(BABYLON || (BABYLON = {}));
  1420. //# sourceMappingURL=babylon.pointerEvents.js.map
  1421. var BABYLON;
  1422. (function (BABYLON) {
  1423. BABYLON.ToGammaSpace = 1 / 2.2;
  1424. BABYLON.ToLinearSpace = 2.2;
  1425. BABYLON.Epsilon = 0.001;
  1426. /**
  1427. * Class used to hold a RBG color
  1428. */
  1429. var Color3 = /** @class */ (function () {
  1430. /**
  1431. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1432. * @param r defines the red component (between 0 and 1, default is 0)
  1433. * @param g defines the green component (between 0 and 1, default is 0)
  1434. * @param b defines the blue component (between 0 and 1, default is 0)
  1435. */
  1436. function Color3(
  1437. /**
  1438. * Defines the red component (between 0 and 1, default is 0)
  1439. */
  1440. r,
  1441. /**
  1442. * Defines the green component (between 0 and 1, default is 0)
  1443. */
  1444. g,
  1445. /**
  1446. * Defines the blue component (between 0 and 1, default is 0)
  1447. */
  1448. b) {
  1449. if (r === void 0) { r = 0; }
  1450. if (g === void 0) { g = 0; }
  1451. if (b === void 0) { b = 0; }
  1452. this.r = r;
  1453. this.g = g;
  1454. this.b = b;
  1455. }
  1456. /**
  1457. * Creates a string with the Color3 current values
  1458. * @returns the string representation of the Color3 object
  1459. */
  1460. Color3.prototype.toString = function () {
  1461. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1462. };
  1463. /**
  1464. * Returns the string "Color3"
  1465. * @returns "Color3"
  1466. */
  1467. Color3.prototype.getClassName = function () {
  1468. return "Color3";
  1469. };
  1470. /**
  1471. * Compute the Color3 hash code
  1472. * @returns an unique number that can be used to hash Color3 objects
  1473. */
  1474. Color3.prototype.getHashCode = function () {
  1475. var hash = this.r || 0;
  1476. hash = (hash * 397) ^ (this.g || 0);
  1477. hash = (hash * 397) ^ (this.b || 0);
  1478. return hash;
  1479. };
  1480. // Operators
  1481. /**
  1482. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1483. * @param array defines the array where to store the r,g,b components
  1484. * @param index defines an optional index in the target array to define where to start storing values
  1485. * @returns the current Color3 object
  1486. */
  1487. Color3.prototype.toArray = function (array, index) {
  1488. if (index === undefined) {
  1489. index = 0;
  1490. }
  1491. array[index] = this.r;
  1492. array[index + 1] = this.g;
  1493. array[index + 2] = this.b;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1498. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1499. * @returns a new {BABYLON.Color4} object
  1500. */
  1501. Color3.prototype.toColor4 = function (alpha) {
  1502. if (alpha === void 0) { alpha = 1; }
  1503. return new Color4(this.r, this.g, this.b, alpha);
  1504. };
  1505. /**
  1506. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1507. * @returns the new array
  1508. */
  1509. Color3.prototype.asArray = function () {
  1510. var result = new Array();
  1511. this.toArray(result, 0);
  1512. return result;
  1513. };
  1514. /**
  1515. * Returns the luminance value
  1516. * @returns a float value
  1517. */
  1518. Color3.prototype.toLuminance = function () {
  1519. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1520. };
  1521. /**
  1522. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1523. * @param otherColor defines the second operand
  1524. * @returns the new Color3 object
  1525. */
  1526. Color3.prototype.multiply = function (otherColor) {
  1527. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1528. };
  1529. /**
  1530. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1531. * @param otherColor defines the second operand
  1532. * @param result defines the Color3 object where to store the result
  1533. * @returns the current Color3
  1534. */
  1535. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1536. result.r = this.r * otherColor.r;
  1537. result.g = this.g * otherColor.g;
  1538. result.b = this.b * otherColor.b;
  1539. return this;
  1540. };
  1541. /**
  1542. * Determines equality between Color3 objects
  1543. * @param otherColor defines the second operand
  1544. * @returns true if the rgb values are equal to the given ones
  1545. */
  1546. Color3.prototype.equals = function (otherColor) {
  1547. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1548. };
  1549. /**
  1550. * Determines equality between the current Color3 object and a set of r,b,g values
  1551. * @param r defines the red component to check
  1552. * @param g defines the green component to check
  1553. * @param b defines the blue component to check
  1554. * @returns true if the rgb values are equal to the given ones
  1555. */
  1556. Color3.prototype.equalsFloats = function (r, g, b) {
  1557. return this.r === r && this.g === g && this.b === b;
  1558. };
  1559. /**
  1560. * Multiplies in place each rgb value by scale
  1561. * @param scale defines the scaling factor
  1562. * @returns the updated Color3
  1563. */
  1564. Color3.prototype.scale = function (scale) {
  1565. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1566. };
  1567. /**
  1568. * Multiplies the rgb values by scale and stores the result into "result"
  1569. * @param scale defines the scaling factor
  1570. * @param result defines the Color3 object where to store the result
  1571. * @returns the unmodified current Color3
  1572. */
  1573. Color3.prototype.scaleToRef = function (scale, result) {
  1574. result.r = this.r * scale;
  1575. result.g = this.g * scale;
  1576. result.b = this.b * scale;
  1577. return this;
  1578. };
  1579. /**
  1580. * Scale the current Color3 values by a factor and add the result to a given Color3
  1581. * @param scale defines the scale factor
  1582. * @param result defines color to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1586. result.r += this.r * scale;
  1587. result.g += this.g * scale;
  1588. result.b += this.b * scale;
  1589. return this;
  1590. };
  1591. /**
  1592. * Clamps the rgb values by the min and max values and stores the result into "result"
  1593. * @param min defines minimum clamping value (default is 0)
  1594. * @param max defines maximum clamping value (default is 1)
  1595. * @param result defines color to store the result into
  1596. * @returns the original Color3
  1597. */
  1598. Color3.prototype.clampToRef = function (min, max, result) {
  1599. if (min === void 0) { min = 0; }
  1600. if (max === void 0) { max = 1; }
  1601. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1602. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1603. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1604. return this;
  1605. };
  1606. /**
  1607. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.add = function (otherColor) {
  1612. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.addToRef = function (otherColor, result) {
  1621. result.r = this.r + otherColor.r;
  1622. result.g = this.g + otherColor.g;
  1623. result.b = this.b + otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1628. * @param otherColor defines the second operand
  1629. * @returns the new Color3
  1630. */
  1631. Color3.prototype.subtract = function (otherColor) {
  1632. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1633. };
  1634. /**
  1635. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1636. * @param otherColor defines the second operand
  1637. * @param result defines Color3 object to store the result into
  1638. * @returns the unmodified current Color3
  1639. */
  1640. Color3.prototype.subtractToRef = function (otherColor, result) {
  1641. result.r = this.r - otherColor.r;
  1642. result.g = this.g - otherColor.g;
  1643. result.b = this.b - otherColor.b;
  1644. return this;
  1645. };
  1646. /**
  1647. * Copy the current object
  1648. * @returns a new Color3 copied the current one
  1649. */
  1650. Color3.prototype.clone = function () {
  1651. return new Color3(this.r, this.g, this.b);
  1652. };
  1653. /**
  1654. * Copies the rgb values from the source in the current Color3
  1655. * @param source defines the source Color3 object
  1656. * @returns the updated Color3 object
  1657. */
  1658. Color3.prototype.copyFrom = function (source) {
  1659. this.r = source.r;
  1660. this.g = source.g;
  1661. this.b = source.b;
  1662. return this;
  1663. };
  1664. /**
  1665. * Updates the Color3 rgb values from the given floats
  1666. * @param r defines the red component to read from
  1667. * @param g defines the green component to read from
  1668. * @param b defines the blue component to read from
  1669. * @returns the current Color3 object
  1670. */
  1671. Color3.prototype.copyFromFloats = function (r, g, b) {
  1672. this.r = r;
  1673. this.g = g;
  1674. this.b = b;
  1675. return this;
  1676. };
  1677. /**
  1678. * Updates the Color3 rgb values from the given floats
  1679. * @param r defines the red component to read from
  1680. * @param g defines the green component to read from
  1681. * @param b defines the blue component to read from
  1682. * @returns the current Color3 object
  1683. */
  1684. Color3.prototype.set = function (r, g, b) {
  1685. return this.copyFromFloats(r, g, b);
  1686. };
  1687. /**
  1688. * Compute the Color3 hexadecimal code as a string
  1689. * @returns a string containing the hexadecimal representation of the Color3 object
  1690. */
  1691. Color3.prototype.toHexString = function () {
  1692. var intR = (this.r * 255) | 0;
  1693. var intG = (this.g * 255) | 0;
  1694. var intB = (this.b * 255) | 0;
  1695. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to linear space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toLinearSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toLinearSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the linear space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1715. return this;
  1716. };
  1717. /**
  1718. * Computes a new Color3 converted from the current one to gamma space
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.prototype.toGammaSpace = function () {
  1722. var convertedColor = new Color3();
  1723. this.toGammaSpaceToRef(convertedColor);
  1724. return convertedColor;
  1725. };
  1726. /**
  1727. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1728. * @param convertedColor defines the Color3 object where to store the gamma space version
  1729. * @returns the unmodified Color3
  1730. */
  1731. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1732. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1733. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1734. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1735. return this;
  1736. };
  1737. // Statics
  1738. /**
  1739. * Creates a new Color3 from the string containing valid hexadecimal values
  1740. * @param hex defines a string containing valid hexadecimal values
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromHexString = function (hex) {
  1744. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1745. return new Color3(0, 0, 0);
  1746. }
  1747. var r = parseInt(hex.substring(1, 3), 16);
  1748. var g = parseInt(hex.substring(3, 5), 16);
  1749. var b = parseInt(hex.substring(5, 7), 16);
  1750. return Color3.FromInts(r, g, b);
  1751. };
  1752. /**
  1753. * Creates a new Vector3 from the starting index of the given array
  1754. * @param array defines the source array
  1755. * @param offset defines an offset in the source array
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromArray = function (array, offset) {
  1759. if (offset === void 0) { offset = 0; }
  1760. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1761. };
  1762. /**
  1763. * Creates a new Color3 from integer values (< 256)
  1764. * @param r defines the red component to read from (value between 0 and 255)
  1765. * @param g defines the green component to read from (value between 0 and 255)
  1766. * @param b defines the blue component to read from (value between 0 and 255)
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.FromInts = function (r, g, b) {
  1770. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1771. };
  1772. /**
  1773. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1774. * @param start defines the start Color3 value
  1775. * @param end defines the end Color3 value
  1776. * @param amount defines the gradient value between start and end
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Lerp = function (start, end, amount) {
  1780. var result = new Color3(0.0, 0.0, 0.0);
  1781. Color3.LerpToRef(start, end, amount, result);
  1782. return result;
  1783. };
  1784. /**
  1785. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1786. * @param left defines the start value
  1787. * @param right defines the end value
  1788. * @param amount defines the gradient factor
  1789. * @param result defines the Color3 object where to store the result
  1790. */
  1791. Color3.LerpToRef = function (left, right, amount, result) {
  1792. result.r = left.r + ((right.r - left.r) * amount);
  1793. result.g = left.g + ((right.g - left.g) * amount);
  1794. result.b = left.b + ((right.b - left.b) * amount);
  1795. };
  1796. /**
  1797. * Returns a Color3 value containing a red color
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Red = function () { return new Color3(1, 0, 0); };
  1801. /**
  1802. * Returns a Color3 value containing a green color
  1803. * @returns a new Color3 object
  1804. */
  1805. Color3.Green = function () { return new Color3(0, 1, 0); };
  1806. /**
  1807. * Returns a Color3 value containing a blue color
  1808. * @returns a new Color3 object
  1809. */
  1810. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1811. /**
  1812. * Returns a Color3 value containing a black color
  1813. * @returns a new Color3 object
  1814. */
  1815. Color3.Black = function () { return new Color3(0, 0, 0); };
  1816. /**
  1817. * Returns a Color3 value containing a white color
  1818. * @returns a new Color3 object
  1819. */
  1820. Color3.White = function () { return new Color3(1, 1, 1); };
  1821. /**
  1822. * Returns a Color3 value containing a purple color
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1826. /**
  1827. * Returns a Color3 value containing a magenta color
  1828. * @returns a new Color3 object
  1829. */
  1830. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1831. /**
  1832. * Returns a Color3 value containing a yellow color
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1836. /**
  1837. * Returns a Color3 value containing a gray color
  1838. * @returns a new Color3 object
  1839. */
  1840. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1841. /**
  1842. * Returns a Color3 value containing a teal color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1846. /**
  1847. * Returns a Color3 value containing a random color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1851. return Color3;
  1852. }());
  1853. BABYLON.Color3 = Color3;
  1854. /**
  1855. * Class used to hold a RBGA color
  1856. */
  1857. var Color4 = /** @class */ (function () {
  1858. /**
  1859. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1860. * @param r defines the red component (between 0 and 1, default is 0)
  1861. * @param g defines the green component (between 0 and 1, default is 0)
  1862. * @param b defines the blue component (between 0 and 1, default is 0)
  1863. * @param a defines the alpha component (between 0 and 1, default is 1)
  1864. */
  1865. function Color4(
  1866. /**
  1867. * Defines the red component (between 0 and 1, default is 0)
  1868. */
  1869. r,
  1870. /**
  1871. * Defines the green component (between 0 and 1, default is 0)
  1872. */
  1873. g,
  1874. /**
  1875. * Defines the blue component (between 0 and 1, default is 0)
  1876. */
  1877. b,
  1878. /**
  1879. * Defines the alpha component (between 0 and 1, default is 1)
  1880. */
  1881. a) {
  1882. if (r === void 0) { r = 0; }
  1883. if (g === void 0) { g = 0; }
  1884. if (b === void 0) { b = 0; }
  1885. if (a === void 0) { a = 1; }
  1886. this.r = r;
  1887. this.g = g;
  1888. this.b = b;
  1889. this.a = a;
  1890. }
  1891. // Operators
  1892. /**
  1893. * Adds in place the given Color4 values to the current Color4 object
  1894. * @param right defines the second operand
  1895. * @returns the current updated Color4 object
  1896. */
  1897. Color4.prototype.addInPlace = function (right) {
  1898. this.r += right.r;
  1899. this.g += right.g;
  1900. this.b += right.b;
  1901. this.a += right.a;
  1902. return this;
  1903. };
  1904. /**
  1905. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1906. * @returns the new array
  1907. */
  1908. Color4.prototype.asArray = function () {
  1909. var result = new Array();
  1910. this.toArray(result, 0);
  1911. return result;
  1912. };
  1913. /**
  1914. * Stores from the starting index in the given array the Color4 successive values
  1915. * @param array defines the array where to store the r,g,b components
  1916. * @param index defines an optional index in the target array to define where to start storing values
  1917. * @returns the current Color4 object
  1918. */
  1919. Color4.prototype.toArray = function (array, index) {
  1920. if (index === undefined) {
  1921. index = 0;
  1922. }
  1923. array[index] = this.r;
  1924. array[index + 1] = this.g;
  1925. array[index + 2] = this.b;
  1926. array[index + 3] = this.a;
  1927. return this;
  1928. };
  1929. /**
  1930. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1931. * @param right defines the second operand
  1932. * @returns a new Color4 object
  1933. */
  1934. Color4.prototype.add = function (right) {
  1935. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1936. };
  1937. /**
  1938. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1939. * @param right defines the second operand
  1940. * @returns a new Color4 object
  1941. */
  1942. Color4.prototype.subtract = function (right) {
  1943. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1944. };
  1945. /**
  1946. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1947. * @param right defines the second operand
  1948. * @param result defines the Color4 object where to store the result
  1949. * @returns the current Color4 object
  1950. */
  1951. Color4.prototype.subtractToRef = function (right, result) {
  1952. result.r = this.r - right.r;
  1953. result.g = this.g - right.g;
  1954. result.b = this.b - right.b;
  1955. result.a = this.a - right.a;
  1956. return this;
  1957. };
  1958. /**
  1959. * Creates a new Color4 with the current Color4 values multiplied by scale
  1960. * @param scale defines the scaling factor to apply
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.scale = function (scale) {
  1964. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1965. };
  1966. /**
  1967. * Multiplies the current Color4 values by scale and stores the result in "result"
  1968. * @param scale defines the scaling factor to apply
  1969. * @param result defines the Color4 object where to store the result
  1970. * @returns the current unmodified Color4
  1971. */
  1972. Color4.prototype.scaleToRef = function (scale, result) {
  1973. result.r = this.r * scale;
  1974. result.g = this.g * scale;
  1975. result.b = this.b * scale;
  1976. result.a = this.a * scale;
  1977. return this;
  1978. };
  1979. /**
  1980. * Scale the current Color4 values by a factor and add the result to a given Color4
  1981. * @param scale defines the scale factor
  1982. * @param result defines the Color4 object where to store the result
  1983. * @returns the unmodified current Color4
  1984. */
  1985. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1986. result.r += this.r * scale;
  1987. result.g += this.g * scale;
  1988. result.b += this.b * scale;
  1989. result.a += this.a * scale;
  1990. return this;
  1991. };
  1992. /**
  1993. * Clamps the rgb values by the min and max values and stores the result into "result"
  1994. * @param min defines minimum clamping value (default is 0)
  1995. * @param max defines maximum clamping value (default is 1)
  1996. * @param result defines color to store the result into.
  1997. * @returns the cuurent Color4
  1998. */
  1999. Color4.prototype.clampToRef = function (min, max, result) {
  2000. if (min === void 0) { min = 0; }
  2001. if (max === void 0) { max = 1; }
  2002. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2003. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2004. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2005. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2006. return this;
  2007. };
  2008. /**
  2009. * Multipy an Color4 value by another and return a new Color4 object
  2010. * @param color defines the Color4 value to multiply by
  2011. * @returns a new Color4 object
  2012. */
  2013. Color4.prototype.multiply = function (color) {
  2014. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2015. };
  2016. /**
  2017. * Multipy a Color4 value by another and push the result in a reference value
  2018. * @param color defines the Color4 value to multiply by
  2019. * @param result defines the Color4 to fill the result in
  2020. * @returns the result Color4
  2021. */
  2022. Color4.prototype.multiplyToRef = function (color, result) {
  2023. result.r = this.r * color.r;
  2024. result.g = this.g * color.g;
  2025. result.b = this.b * color.b;
  2026. result.a = this.a * color.a;
  2027. return result;
  2028. };
  2029. /**
  2030. * Creates a string with the Color4 current values
  2031. * @returns the string representation of the Color4 object
  2032. */
  2033. Color4.prototype.toString = function () {
  2034. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2035. };
  2036. /**
  2037. * Returns the string "Color4"
  2038. * @returns "Color4"
  2039. */
  2040. Color4.prototype.getClassName = function () {
  2041. return "Color4";
  2042. };
  2043. /**
  2044. * Compute the Color4 hash code
  2045. * @returns an unique number that can be used to hash Color4 objects
  2046. */
  2047. Color4.prototype.getHashCode = function () {
  2048. var hash = this.r || 0;
  2049. hash = (hash * 397) ^ (this.g || 0);
  2050. hash = (hash * 397) ^ (this.b || 0);
  2051. hash = (hash * 397) ^ (this.a || 0);
  2052. return hash;
  2053. };
  2054. /**
  2055. * Creates a new Color4 copied from the current one
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.clone = function () {
  2059. return new Color4(this.r, this.g, this.b, this.a);
  2060. };
  2061. /**
  2062. * Copies the given Color4 values into the current one
  2063. * @param source defines the source Color4 object
  2064. * @returns the current updated Color4 object
  2065. */
  2066. Color4.prototype.copyFrom = function (source) {
  2067. this.r = source.r;
  2068. this.g = source.g;
  2069. this.b = source.b;
  2070. this.a = source.a;
  2071. return this;
  2072. };
  2073. /**
  2074. * Copies the given float values into the current one
  2075. * @param r defines the red component to read from
  2076. * @param g defines the green component to read from
  2077. * @param b defines the blue component to read from
  2078. * @param a defines the alpha component to read from
  2079. * @returns the current updated Color4 object
  2080. */
  2081. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2082. this.r = r;
  2083. this.g = g;
  2084. this.b = b;
  2085. this.a = a;
  2086. return this;
  2087. };
  2088. /**
  2089. * Copies the given float values into the current one
  2090. * @param r defines the red component to read from
  2091. * @param g defines the green component to read from
  2092. * @param b defines the blue component to read from
  2093. * @param a defines the alpha component to read from
  2094. * @returns the current updated Color4 object
  2095. */
  2096. Color4.prototype.set = function (r, g, b, a) {
  2097. return this.copyFromFloats(r, g, b, a);
  2098. };
  2099. /**
  2100. * Compute the Color4 hexadecimal code as a string
  2101. * @returns a string containing the hexadecimal representation of the Color4 object
  2102. */
  2103. Color4.prototype.toHexString = function () {
  2104. var intR = (this.r * 255) | 0;
  2105. var intG = (this.g * 255) | 0;
  2106. var intB = (this.b * 255) | 0;
  2107. var intA = (this.a * 255) | 0;
  2108. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2109. };
  2110. /**
  2111. * Computes a new Color4 converted from the current one to linear space
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.prototype.toLinearSpace = function () {
  2115. var convertedColor = new Color4();
  2116. this.toLinearSpaceToRef(convertedColor);
  2117. return convertedColor;
  2118. };
  2119. /**
  2120. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2121. * @param convertedColor defines the Color4 object where to store the linear space version
  2122. * @returns the unmodified Color4
  2123. */
  2124. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2125. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2126. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2127. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2128. convertedColor.a = this.a;
  2129. return this;
  2130. };
  2131. /**
  2132. * Computes a new Color4 converted from the current one to gamma space
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.prototype.toGammaSpace = function () {
  2136. var convertedColor = new Color4();
  2137. this.toGammaSpaceToRef(convertedColor);
  2138. return convertedColor;
  2139. };
  2140. /**
  2141. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2142. * @param convertedColor defines the Color4 object where to store the gamma space version
  2143. * @returns the unmodified Color4
  2144. */
  2145. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2146. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2147. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2148. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2149. convertedColor.a = this.a;
  2150. return this;
  2151. };
  2152. // Statics
  2153. /**
  2154. * Creates a new Color4 from the string containing valid hexadecimal values
  2155. * @param hex defines a string containing valid hexadecimal values
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.FromHexString = function (hex) {
  2159. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2160. return new Color4(0.0, 0.0, 0.0, 0.0);
  2161. }
  2162. var r = parseInt(hex.substring(1, 3), 16);
  2163. var g = parseInt(hex.substring(3, 5), 16);
  2164. var b = parseInt(hex.substring(5, 7), 16);
  2165. var a = parseInt(hex.substring(7, 9), 16);
  2166. return Color4.FromInts(r, g, b, a);
  2167. };
  2168. /**
  2169. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2170. * @param left defines the start value
  2171. * @param right defines the end value
  2172. * @param amount defines the gradient factor
  2173. * @returns a new Color4 object
  2174. */
  2175. Color4.Lerp = function (left, right, amount) {
  2176. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2177. Color4.LerpToRef(left, right, amount, result);
  2178. return result;
  2179. };
  2180. /**
  2181. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2182. * @param left defines the start value
  2183. * @param right defines the end value
  2184. * @param amount defines the gradient factor
  2185. * @param result defines the Color4 object where to store data
  2186. */
  2187. Color4.LerpToRef = function (left, right, amount, result) {
  2188. result.r = left.r + (right.r - left.r) * amount;
  2189. result.g = left.g + (right.g - left.g) * amount;
  2190. result.b = left.b + (right.b - left.b) * amount;
  2191. result.a = left.a + (right.a - left.a) * amount;
  2192. };
  2193. /**
  2194. * Creates a new Color4 from a Color3 and an alpha value
  2195. * @param color3 defines the source Color3 to read from
  2196. * @param alpha defines the alpha component (1.0 by default)
  2197. * @returns a new Color4 object
  2198. */
  2199. Color4.FromColor3 = function (color3, alpha) {
  2200. if (alpha === void 0) { alpha = 1.0; }
  2201. return new Color4(color3.r, color3.g, color3.b, alpha);
  2202. };
  2203. /**
  2204. * Creates a new Color4 from the starting index element of the given array
  2205. * @param array defines the source array to read from
  2206. * @param offset defines the offset in the source array
  2207. * @returns a new Color4 object
  2208. */
  2209. Color4.FromArray = function (array, offset) {
  2210. if (offset === void 0) { offset = 0; }
  2211. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2212. };
  2213. /**
  2214. * Creates a new Color3 from integer values (< 256)
  2215. * @param r defines the red component to read from (value between 0 and 255)
  2216. * @param g defines the green component to read from (value between 0 and 255)
  2217. * @param b defines the blue component to read from (value between 0 and 255)
  2218. * @param a defines the alpha component to read from (value between 0 and 255)
  2219. * @returns a new Color3 object
  2220. */
  2221. Color4.FromInts = function (r, g, b, a) {
  2222. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2223. };
  2224. /**
  2225. * Check the content of a given array and convert it to an array containing RGBA data
  2226. * If the original array was already containing count * 4 values then it is returned directly
  2227. * @param colors defines the array to check
  2228. * @param count defines the number of RGBA data to expect
  2229. * @returns an array containing count * 4 values (RGBA)
  2230. */
  2231. Color4.CheckColors4 = function (colors, count) {
  2232. // Check if color3 was used
  2233. if (colors.length === count * 3) {
  2234. var colors4 = [];
  2235. for (var index = 0; index < colors.length; index += 3) {
  2236. var newIndex = (index / 3) * 4;
  2237. colors4[newIndex] = colors[index];
  2238. colors4[newIndex + 1] = colors[index + 1];
  2239. colors4[newIndex + 2] = colors[index + 2];
  2240. colors4[newIndex + 3] = 1.0;
  2241. }
  2242. return colors4;
  2243. }
  2244. return colors;
  2245. };
  2246. return Color4;
  2247. }());
  2248. BABYLON.Color4 = Color4;
  2249. /**
  2250. * Class representing a vector containing 2 coordinates
  2251. */
  2252. var Vector2 = /** @class */ (function () {
  2253. /**
  2254. * Creates a new Vector2 from the given x and y coordinates
  2255. * @param x defines the first coordinate
  2256. * @param y defines the second coordinate
  2257. */
  2258. function Vector2(
  2259. /** defines the first coordinate */
  2260. x,
  2261. /** defines the second coordinate */
  2262. y) {
  2263. if (x === void 0) { x = 0; }
  2264. if (y === void 0) { y = 0; }
  2265. this.x = x;
  2266. this.y = y;
  2267. }
  2268. /**
  2269. * Gets a string with the Vector2 coordinates
  2270. * @returns a string with the Vector2 coordinates
  2271. */
  2272. Vector2.prototype.toString = function () {
  2273. return "{X: " + this.x + " Y:" + this.y + "}";
  2274. };
  2275. /**
  2276. * Gets class name
  2277. * @returns the string "Vector2"
  2278. */
  2279. Vector2.prototype.getClassName = function () {
  2280. return "Vector2";
  2281. };
  2282. /**
  2283. * Gets current vector hash code
  2284. * @returns the Vector2 hash code as a number
  2285. */
  2286. Vector2.prototype.getHashCode = function () {
  2287. var hash = this.x || 0;
  2288. hash = (hash * 397) ^ (this.y || 0);
  2289. return hash;
  2290. };
  2291. // Operators
  2292. /**
  2293. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2294. * @param array defines the source array
  2295. * @param index defines the offset in source array
  2296. * @returns the current Vector2
  2297. */
  2298. Vector2.prototype.toArray = function (array, index) {
  2299. if (index === void 0) { index = 0; }
  2300. array[index] = this.x;
  2301. array[index + 1] = this.y;
  2302. return this;
  2303. };
  2304. /**
  2305. * Copy the current vector to an array
  2306. * @returns a new array with 2 elements: the Vector2 coordinates.
  2307. */
  2308. Vector2.prototype.asArray = function () {
  2309. var result = new Array();
  2310. this.toArray(result, 0);
  2311. return result;
  2312. };
  2313. /**
  2314. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2315. * @param source defines the source Vector2
  2316. * @returns the current updated Vector2
  2317. */
  2318. Vector2.prototype.copyFrom = function (source) {
  2319. this.x = source.x;
  2320. this.y = source.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Sets the Vector2 coordinates with the given floats
  2325. * @param x defines the first coordinate
  2326. * @param y defines the second coordinate
  2327. * @returns the current updated Vector2
  2328. */
  2329. Vector2.prototype.copyFromFloats = function (x, y) {
  2330. this.x = x;
  2331. this.y = y;
  2332. return this;
  2333. };
  2334. /**
  2335. * Sets the Vector2 coordinates with the given floats
  2336. * @param x defines the first coordinate
  2337. * @param y defines the second coordinate
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.set = function (x, y) {
  2341. return this.copyFromFloats(x, y);
  2342. };
  2343. /**
  2344. * Add another vector with the current one
  2345. * @param otherVector defines the other vector
  2346. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2347. */
  2348. Vector2.prototype.add = function (otherVector) {
  2349. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2350. };
  2351. /**
  2352. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @param result defines the target vector
  2355. * @returns the unmodified current Vector2
  2356. */
  2357. Vector2.prototype.addToRef = function (otherVector, result) {
  2358. result.x = this.x + otherVector.x;
  2359. result.y = this.y + otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2364. * @param otherVector defines the other vector
  2365. * @returns the current updated Vector2
  2366. */
  2367. Vector2.prototype.addInPlace = function (otherVector) {
  2368. this.x += otherVector.x;
  2369. this.y += otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns a new Vector2
  2376. */
  2377. Vector2.prototype.addVector3 = function (otherVector) {
  2378. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2379. };
  2380. /**
  2381. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2382. * @param otherVector defines the other vector
  2383. * @returns a new Vector2
  2384. */
  2385. Vector2.prototype.subtract = function (otherVector) {
  2386. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2387. };
  2388. /**
  2389. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2390. * @param otherVector defines the other vector
  2391. * @param result defines the target vector
  2392. * @returns the unmodified current Vector2
  2393. */
  2394. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2395. result.x = this.x - otherVector.x;
  2396. result.y = this.y - otherVector.y;
  2397. return this;
  2398. };
  2399. /**
  2400. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @returns the current updated Vector2
  2403. */
  2404. Vector2.prototype.subtractInPlace = function (otherVector) {
  2405. this.x -= otherVector.x;
  2406. this.y -= otherVector.y;
  2407. return this;
  2408. };
  2409. /**
  2410. * Multiplies in place the current Vector2 coordinates by the given ones
  2411. * @param otherVector defines the other vector
  2412. * @returns the current updated Vector2
  2413. */
  2414. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2415. this.x *= otherVector.x;
  2416. this.y *= otherVector.y;
  2417. return this;
  2418. };
  2419. /**
  2420. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2421. * @param otherVector defines the other vector
  2422. * @returns a new Vector2
  2423. */
  2424. Vector2.prototype.multiply = function (otherVector) {
  2425. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2426. };
  2427. /**
  2428. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2429. * @param otherVector defines the other vector
  2430. * @param result defines the target vector
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2434. result.x = this.x * otherVector.x;
  2435. result.y = this.y * otherVector.y;
  2436. return this;
  2437. };
  2438. /**
  2439. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2440. * @param x defines the first coordinate
  2441. * @param y defines the second coordinate
  2442. * @returns a new Vector2
  2443. */
  2444. Vector2.prototype.multiplyByFloats = function (x, y) {
  2445. return new Vector2(this.x * x, this.y * y);
  2446. };
  2447. /**
  2448. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2449. * @param otherVector defines the other vector
  2450. * @returns a new Vector2
  2451. */
  2452. Vector2.prototype.divide = function (otherVector) {
  2453. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2454. };
  2455. /**
  2456. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2457. * @param otherVector defines the other vector
  2458. * @param result defines the target vector
  2459. * @returns the unmodified current Vector2
  2460. */
  2461. Vector2.prototype.divideToRef = function (otherVector, result) {
  2462. result.x = this.x / otherVector.x;
  2463. result.y = this.y / otherVector.y;
  2464. return this;
  2465. };
  2466. /**
  2467. * Divides the current Vector2 coordinates by the given ones
  2468. * @param otherVector defines the other vector
  2469. * @returns the current updated Vector2
  2470. */
  2471. Vector2.prototype.divideInPlace = function (otherVector) {
  2472. return this.divideToRef(otherVector, this);
  2473. };
  2474. /**
  2475. * Gets a new Vector2 with current Vector2 negated coordinates
  2476. * @returns a new Vector2
  2477. */
  2478. Vector2.prototype.negate = function () {
  2479. return new Vector2(-this.x, -this.y);
  2480. };
  2481. /**
  2482. * Multiply the Vector2 coordinates by scale
  2483. * @param scale defines the scaling factor
  2484. * @returns the current updated Vector2
  2485. */
  2486. Vector2.prototype.scaleInPlace = function (scale) {
  2487. this.x *= scale;
  2488. this.y *= scale;
  2489. return this;
  2490. };
  2491. /**
  2492. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2493. * @param scale defines the scaling factor
  2494. * @returns a new Vector2
  2495. */
  2496. Vector2.prototype.scale = function (scale) {
  2497. var result = new Vector2(0, 0);
  2498. this.scaleToRef(scale, result);
  2499. return result;
  2500. };
  2501. /**
  2502. * Scale the current Vector2 values by a factor to a given Vector2
  2503. * @param scale defines the scale factor
  2504. * @param result defines the Vector2 object where to store the result
  2505. * @returns the unmodified current Vector2
  2506. */
  2507. Vector2.prototype.scaleToRef = function (scale, result) {
  2508. result.x = this.x * scale;
  2509. result.y = this.y * scale;
  2510. return this;
  2511. };
  2512. /**
  2513. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2514. * @param scale defines the scale factor
  2515. * @param result defines the Vector2 object where to store the result
  2516. * @returns the unmodified current Vector2
  2517. */
  2518. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2519. result.x += this.x * scale;
  2520. result.y += this.y * scale;
  2521. return this;
  2522. };
  2523. /**
  2524. * Gets a boolean if two vectors are equals
  2525. * @param otherVector defines the other vector
  2526. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2527. */
  2528. Vector2.prototype.equals = function (otherVector) {
  2529. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2530. };
  2531. /**
  2532. * Gets a boolean if two vectors are equals (using an epsilon value)
  2533. * @param otherVector defines the other vector
  2534. * @param epsilon defines the minimal distance to consider equality
  2535. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2536. */
  2537. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2538. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2539. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2540. };
  2541. /**
  2542. * Gets a new Vector2 from current Vector2 floored values
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.prototype.floor = function () {
  2546. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2547. };
  2548. /**
  2549. * Gets a new Vector2 from current Vector2 floored values
  2550. * @returns a new Vector2
  2551. */
  2552. Vector2.prototype.fract = function () {
  2553. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2554. };
  2555. // Properties
  2556. /**
  2557. * Gets the length of the vector
  2558. * @returns the vector length (float)
  2559. */
  2560. Vector2.prototype.length = function () {
  2561. return Math.sqrt(this.x * this.x + this.y * this.y);
  2562. };
  2563. /**
  2564. * Gets the vector squared length
  2565. * @returns the vector squared length (float)
  2566. */
  2567. Vector2.prototype.lengthSquared = function () {
  2568. return (this.x * this.x + this.y * this.y);
  2569. };
  2570. // Methods
  2571. /**
  2572. * Normalize the vector
  2573. * @returns the current updated Vector2
  2574. */
  2575. Vector2.prototype.normalize = function () {
  2576. var len = this.length();
  2577. if (len === 0)
  2578. return this;
  2579. var num = 1.0 / len;
  2580. this.x *= num;
  2581. this.y *= num;
  2582. return this;
  2583. };
  2584. /**
  2585. * Gets a new Vector2 copied from the Vector2
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.prototype.clone = function () {
  2589. return new Vector2(this.x, this.y);
  2590. };
  2591. // Statics
  2592. /**
  2593. * Gets a new Vector2(0, 0)
  2594. * @returns a new Vector2
  2595. */
  2596. Vector2.Zero = function () {
  2597. return new Vector2(0, 0);
  2598. };
  2599. /**
  2600. * Gets a new Vector2(1, 1)
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.One = function () {
  2604. return new Vector2(1, 1);
  2605. };
  2606. /**
  2607. * Gets a new Vector2 set from the given index element of the given array
  2608. * @param array defines the data source
  2609. * @param offset defines the offset in the data source
  2610. * @returns a new Vector2
  2611. */
  2612. Vector2.FromArray = function (array, offset) {
  2613. if (offset === void 0) { offset = 0; }
  2614. return new Vector2(array[offset], array[offset + 1]);
  2615. };
  2616. /**
  2617. * Sets "result" from the given index element of the given array
  2618. * @param array defines the data source
  2619. * @param offset defines the offset in the data source
  2620. * @param result defines the target vector
  2621. */
  2622. Vector2.FromArrayToRef = function (array, offset, result) {
  2623. result.x = array[offset];
  2624. result.y = array[offset + 1];
  2625. };
  2626. /**
  2627. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2628. * @param value1 defines 1st point of control
  2629. * @param value2 defines 2nd point of control
  2630. * @param value3 defines 3rd point of control
  2631. * @param value4 defines 4th point of control
  2632. * @param amount defines the interpolation factor
  2633. * @returns a new Vector2
  2634. */
  2635. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2636. var squared = amount * amount;
  2637. var cubed = amount * squared;
  2638. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2639. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2640. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2641. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2642. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2643. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2644. return new Vector2(x, y);
  2645. };
  2646. /**
  2647. * 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".
  2648. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2649. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2650. * @param value defines the value to clamp
  2651. * @param min defines the lower limit
  2652. * @param max defines the upper limit
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Clamp = function (value, min, max) {
  2656. var x = value.x;
  2657. x = (x > max.x) ? max.x : x;
  2658. x = (x < min.x) ? min.x : x;
  2659. var y = value.y;
  2660. y = (y > max.y) ? max.y : y;
  2661. y = (y < min.y) ? min.y : y;
  2662. return new Vector2(x, y);
  2663. };
  2664. /**
  2665. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2666. * @param value1 defines the 1st control point
  2667. * @param tangent1 defines the outgoing tangent
  2668. * @param value2 defines the 2nd control point
  2669. * @param tangent2 defines the incoming tangent
  2670. * @param amount defines the interpolation factor
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2674. var squared = amount * amount;
  2675. var cubed = amount * squared;
  2676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2678. var part3 = (cubed - (2.0 * squared)) + amount;
  2679. var part4 = cubed - squared;
  2680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2682. return new Vector2(x, y);
  2683. };
  2684. /**
  2685. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2686. * @param start defines the start vector
  2687. * @param end defines the end vector
  2688. * @param amount defines the interpolation factor
  2689. * @returns a new Vector2
  2690. */
  2691. Vector2.Lerp = function (start, end, amount) {
  2692. var x = start.x + ((end.x - start.x) * amount);
  2693. var y = start.y + ((end.y - start.y) * amount);
  2694. return new Vector2(x, y);
  2695. };
  2696. /**
  2697. * Gets the dot product of the vector "left" and the vector "right"
  2698. * @param left defines first vector
  2699. * @param right defines second vector
  2700. * @returns the dot product (float)
  2701. */
  2702. Vector2.Dot = function (left, right) {
  2703. return left.x * right.x + left.y * right.y;
  2704. };
  2705. /**
  2706. * Returns a new Vector2 equal to the normalized given vector
  2707. * @param vector defines the vector to normalize
  2708. * @returns a new Vector2
  2709. */
  2710. Vector2.Normalize = function (vector) {
  2711. var newVector = vector.clone();
  2712. newVector.normalize();
  2713. return newVector;
  2714. };
  2715. /**
  2716. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2717. * @param left defines 1st vector
  2718. * @param right defines 2nd vector
  2719. * @returns a new Vector2
  2720. */
  2721. Vector2.Minimize = function (left, right) {
  2722. var x = (left.x < right.x) ? left.x : right.x;
  2723. var y = (left.y < right.y) ? left.y : right.y;
  2724. return new Vector2(x, y);
  2725. };
  2726. /**
  2727. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2728. * @param left defines 1st vector
  2729. * @param right defines 2nd vector
  2730. * @returns a new Vector2
  2731. */
  2732. Vector2.Maximize = function (left, right) {
  2733. var x = (left.x > right.x) ? left.x : right.x;
  2734. var y = (left.y > right.y) ? left.y : right.y;
  2735. return new Vector2(x, y);
  2736. };
  2737. /**
  2738. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2739. * @param vector defines the vector to transform
  2740. * @param transformation defines the matrix to apply
  2741. * @returns a new Vector2
  2742. */
  2743. Vector2.Transform = function (vector, transformation) {
  2744. var r = Vector2.Zero();
  2745. Vector2.TransformToRef(vector, transformation, r);
  2746. return r;
  2747. };
  2748. /**
  2749. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2750. * @param vector defines the vector to transform
  2751. * @param transformation defines the matrix to apply
  2752. * @param result defines the target vector
  2753. */
  2754. Vector2.TransformToRef = function (vector, transformation, result) {
  2755. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2756. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2757. result.x = x;
  2758. result.y = y;
  2759. };
  2760. /**
  2761. * Determines if a given vector is included in a triangle
  2762. * @param p defines the vector to test
  2763. * @param p0 defines 1st triangle point
  2764. * @param p1 defines 2nd triangle point
  2765. * @param p2 defines 3rd triangle point
  2766. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2767. */
  2768. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2769. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2770. var sign = a < 0 ? -1 : 1;
  2771. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2772. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2773. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2774. };
  2775. /**
  2776. * Gets the distance between the vectors "value1" and "value2"
  2777. * @param value1 defines first vector
  2778. * @param value2 defines second vector
  2779. * @returns the distance between vectors
  2780. */
  2781. Vector2.Distance = function (value1, value2) {
  2782. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2783. };
  2784. /**
  2785. * Returns the squared distance between the vectors "value1" and "value2"
  2786. * @param value1 defines first vector
  2787. * @param value2 defines second vector
  2788. * @returns the squared distance between vectors
  2789. */
  2790. Vector2.DistanceSquared = function (value1, value2) {
  2791. var x = value1.x - value2.x;
  2792. var y = value1.y - value2.y;
  2793. return (x * x) + (y * y);
  2794. };
  2795. /**
  2796. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2797. * @param value1 defines first vector
  2798. * @param value2 defines second vector
  2799. * @returns a new Vector2
  2800. */
  2801. Vector2.Center = function (value1, value2) {
  2802. var center = value1.add(value2);
  2803. center.scaleInPlace(0.5);
  2804. return center;
  2805. };
  2806. /**
  2807. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2808. * @param p defines the middle point
  2809. * @param segA defines one point of the segment
  2810. * @param segB defines the other point of the segment
  2811. * @returns the shortest distance
  2812. */
  2813. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2814. var l2 = Vector2.DistanceSquared(segA, segB);
  2815. if (l2 === 0.0) {
  2816. return Vector2.Distance(p, segA);
  2817. }
  2818. var v = segB.subtract(segA);
  2819. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2820. var proj = segA.add(v.multiplyByFloats(t, t));
  2821. return Vector2.Distance(p, proj);
  2822. };
  2823. return Vector2;
  2824. }());
  2825. BABYLON.Vector2 = Vector2;
  2826. /**
  2827. * Classed used to store (x,y,z) vector representation
  2828. * A Vector3 is the main object used in 3D geometry
  2829. * It can represent etiher the coordinates of a point the space, either a direction
  2830. * Reminder: Babylon.js uses a left handed forward facing system
  2831. */
  2832. var Vector3 = /** @class */ (function () {
  2833. /**
  2834. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2835. * @param x defines the first coordinates (on X axis)
  2836. * @param y defines the second coordinates (on Y axis)
  2837. * @param z defines the third coordinates (on Z axis)
  2838. */
  2839. function Vector3(
  2840. /**
  2841. * Defines the first coordinates (on X axis)
  2842. */
  2843. x,
  2844. /**
  2845. * Defines the second coordinates (on Y axis)
  2846. */
  2847. y,
  2848. /**
  2849. * Defines the third coordinates (on Z axis)
  2850. */
  2851. z) {
  2852. if (x === void 0) { x = 0; }
  2853. if (y === void 0) { y = 0; }
  2854. if (z === void 0) { z = 0; }
  2855. this.x = x;
  2856. this.y = y;
  2857. this.z = z;
  2858. }
  2859. /**
  2860. * Creates a string representation of the Vector3
  2861. * @returns a string with the Vector3 coordinates.
  2862. */
  2863. Vector3.prototype.toString = function () {
  2864. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2865. };
  2866. /**
  2867. * Gets the class name
  2868. * @returns the string "Vector3"
  2869. */
  2870. Vector3.prototype.getClassName = function () {
  2871. return "Vector3";
  2872. };
  2873. /**
  2874. * Creates the Vector3 hash code
  2875. * @returns a number which tends to be unique between Vector3 instances
  2876. */
  2877. Vector3.prototype.getHashCode = function () {
  2878. var hash = this.x || 0;
  2879. hash = (hash * 397) ^ (this.y || 0);
  2880. hash = (hash * 397) ^ (this.z || 0);
  2881. return hash;
  2882. };
  2883. // Operators
  2884. /**
  2885. * Creates an array containing three elements : the coordinates of the Vector3
  2886. * @returns a new array of numbers
  2887. */
  2888. Vector3.prototype.asArray = function () {
  2889. var result = [];
  2890. this.toArray(result, 0);
  2891. return result;
  2892. };
  2893. /**
  2894. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2895. * @param array defines the destination array
  2896. * @param index defines the offset in the destination array
  2897. * @returns the current Vector3
  2898. */
  2899. Vector3.prototype.toArray = function (array, index) {
  2900. if (index === void 0) { index = 0; }
  2901. array[index] = this.x;
  2902. array[index + 1] = this.y;
  2903. array[index + 2] = this.z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2908. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2909. */
  2910. Vector3.prototype.toQuaternion = function () {
  2911. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2912. };
  2913. /**
  2914. * Adds the given vector to the current Vector3
  2915. * @param otherVector defines the second operand
  2916. * @returns the current updated Vector3
  2917. */
  2918. Vector3.prototype.addInPlace = function (otherVector) {
  2919. this.x += otherVector.x;
  2920. this.y += otherVector.y;
  2921. this.z += otherVector.z;
  2922. return this;
  2923. };
  2924. /**
  2925. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2926. * @param otherVector defines the second operand
  2927. * @returns the resulting Vector3
  2928. */
  2929. Vector3.prototype.add = function (otherVector) {
  2930. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2931. };
  2932. /**
  2933. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2934. * @param otherVector defines the second operand
  2935. * @param result defines the Vector3 object where to store the result
  2936. * @returns the current Vector3
  2937. */
  2938. Vector3.prototype.addToRef = function (otherVector, result) {
  2939. result.x = this.x + otherVector.x;
  2940. result.y = this.y + otherVector.y;
  2941. result.z = this.z + otherVector.z;
  2942. return this;
  2943. };
  2944. /**
  2945. * Subtract the given vector from the current Vector3
  2946. * @param otherVector defines the second operand
  2947. * @returns the current updated Vector3
  2948. */
  2949. Vector3.prototype.subtractInPlace = function (otherVector) {
  2950. this.x -= otherVector.x;
  2951. this.y -= otherVector.y;
  2952. this.z -= otherVector.z;
  2953. return this;
  2954. };
  2955. /**
  2956. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2957. * @param otherVector defines the second operand
  2958. * @returns the resulting Vector3
  2959. */
  2960. Vector3.prototype.subtract = function (otherVector) {
  2961. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2962. };
  2963. /**
  2964. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2965. * @param otherVector defines the second operand
  2966. * @param result defines the Vector3 object where to store the result
  2967. * @returns the current Vector3
  2968. */
  2969. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2970. result.x = this.x - otherVector.x;
  2971. result.y = this.y - otherVector.y;
  2972. result.z = this.z - otherVector.z;
  2973. return this;
  2974. };
  2975. /**
  2976. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2977. * @param x defines the x coordinate of the operand
  2978. * @param y defines the y coordinate of the operand
  2979. * @param z defines the z coordinate of the operand
  2980. * @returns the resulting Vector3
  2981. */
  2982. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2983. return new Vector3(this.x - x, this.y - y, this.z - z);
  2984. };
  2985. /**
  2986. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2987. * @param x defines the x coordinate of the operand
  2988. * @param y defines the y coordinate of the operand
  2989. * @param z defines the z coordinate of the operand
  2990. * @param result defines the Vector3 object where to store the result
  2991. * @returns the current Vector3
  2992. */
  2993. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2994. result.x = this.x - x;
  2995. result.y = this.y - y;
  2996. result.z = this.z - z;
  2997. return this;
  2998. };
  2999. /**
  3000. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3001. * @returns a new Vector3
  3002. */
  3003. Vector3.prototype.negate = function () {
  3004. return new Vector3(-this.x, -this.y, -this.z);
  3005. };
  3006. /**
  3007. * Multiplies the Vector3 coordinates by the float "scale"
  3008. * @param scale defines the multiplier factor
  3009. * @returns the current updated Vector3
  3010. */
  3011. Vector3.prototype.scaleInPlace = function (scale) {
  3012. this.x *= scale;
  3013. this.y *= scale;
  3014. this.z *= scale;
  3015. return this;
  3016. };
  3017. /**
  3018. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3019. * @param scale defines the multiplier factor
  3020. * @returns a new Vector3
  3021. */
  3022. Vector3.prototype.scale = function (scale) {
  3023. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3024. };
  3025. /**
  3026. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3027. * @param scale defines the multiplier factor
  3028. * @param result defines the Vector3 object where to store the result
  3029. * @returns the current Vector3
  3030. */
  3031. Vector3.prototype.scaleToRef = function (scale, result) {
  3032. result.x = this.x * scale;
  3033. result.y = this.y * scale;
  3034. result.z = this.z * scale;
  3035. return this;
  3036. };
  3037. /**
  3038. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3039. * @param scale defines the scale factor
  3040. * @param result defines the Vector3 object where to store the result
  3041. * @returns the unmodified current Vector3
  3042. */
  3043. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3044. result.x += this.x * scale;
  3045. result.y += this.y * scale;
  3046. result.z += this.z * scale;
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3051. * @param otherVector defines the second operand
  3052. * @returns true if both vectors are equals
  3053. */
  3054. Vector3.prototype.equals = function (otherVector) {
  3055. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3056. };
  3057. /**
  3058. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3059. * @param otherVector defines the second operand
  3060. * @param epsilon defines the minimal distance to define values as equals
  3061. * @returns true if both vectors are distant less than epsilon
  3062. */
  3063. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3064. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3065. 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);
  3066. };
  3067. /**
  3068. * Returns true if the current Vector3 coordinates equals the given floats
  3069. * @param x defines the x coordinate of the operand
  3070. * @param y defines the y coordinate of the operand
  3071. * @param z defines the z coordinate of the operand
  3072. * @returns true if both vectors are equals
  3073. */
  3074. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3075. return this.x === x && this.y === y && this.z === z;
  3076. };
  3077. /**
  3078. * Multiplies the current Vector3 coordinates by the given ones
  3079. * @param otherVector defines the second operand
  3080. * @returns the current updated Vector3
  3081. */
  3082. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3083. this.x *= otherVector.x;
  3084. this.y *= otherVector.y;
  3085. this.z *= otherVector.z;
  3086. return this;
  3087. };
  3088. /**
  3089. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3090. * @param otherVector defines the second operand
  3091. * @returns the new Vector3
  3092. */
  3093. Vector3.prototype.multiply = function (otherVector) {
  3094. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3095. };
  3096. /**
  3097. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3098. * @param otherVector defines the second operand
  3099. * @param result defines the Vector3 object where to store the result
  3100. * @returns the current Vector3
  3101. */
  3102. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3103. result.x = this.x * otherVector.x;
  3104. result.y = this.y * otherVector.y;
  3105. result.z = this.z * otherVector.z;
  3106. return this;
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3110. * @param x defines the x coordinate of the operand
  3111. * @param y defines the y coordinate of the operand
  3112. * @param z defines the z coordinate of the operand
  3113. * @returns the new Vector3
  3114. */
  3115. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3116. return new Vector3(this.x * x, this.y * y, this.z * z);
  3117. };
  3118. /**
  3119. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3120. * @param otherVector defines the second operand
  3121. * @returns the new Vector3
  3122. */
  3123. Vector3.prototype.divide = function (otherVector) {
  3124. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3125. };
  3126. /**
  3127. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3128. * @param otherVector defines the second operand
  3129. * @param result defines the Vector3 object where to store the result
  3130. * @returns the current Vector3
  3131. */
  3132. Vector3.prototype.divideToRef = function (otherVector, result) {
  3133. result.x = this.x / otherVector.x;
  3134. result.y = this.y / otherVector.y;
  3135. result.z = this.z / otherVector.z;
  3136. return this;
  3137. };
  3138. /**
  3139. * Divides the current Vector3 coordinates by the given ones.
  3140. * @param otherVector defines the second operand
  3141. * @returns the current updated Vector3
  3142. */
  3143. Vector3.prototype.divideInPlace = function (otherVector) {
  3144. return this.divideToRef(otherVector, this);
  3145. };
  3146. /**
  3147. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3148. * @param other defines the second operand
  3149. * @returns the current updated Vector3
  3150. */
  3151. Vector3.prototype.minimizeInPlace = function (other) {
  3152. if (other.x < this.x)
  3153. this.x = other.x;
  3154. if (other.y < this.y)
  3155. this.y = other.y;
  3156. if (other.z < this.z)
  3157. this.z = other.z;
  3158. return this;
  3159. };
  3160. /**
  3161. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3162. * @param other defines the second operand
  3163. * @returns the current updated Vector3
  3164. */
  3165. Vector3.prototype.maximizeInPlace = function (other) {
  3166. if (other.x > this.x)
  3167. this.x = other.x;
  3168. if (other.y > this.y)
  3169. this.y = other.y;
  3170. if (other.z > this.z)
  3171. this.z = other.z;
  3172. return this;
  3173. };
  3174. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3175. /**
  3176. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3177. */
  3178. get: function () {
  3179. var absX = Math.abs(this.x);
  3180. var absY = Math.abs(this.y);
  3181. if (absX !== absY) {
  3182. return true;
  3183. }
  3184. var absZ = Math.abs(this.z);
  3185. if (absX !== absZ) {
  3186. return true;
  3187. }
  3188. if (absY !== absZ) {
  3189. return true;
  3190. }
  3191. return false;
  3192. },
  3193. enumerable: true,
  3194. configurable: true
  3195. });
  3196. /**
  3197. * Gets a new Vector3 from current Vector3 floored values
  3198. * @returns a new Vector3
  3199. */
  3200. Vector3.prototype.floor = function () {
  3201. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3202. };
  3203. /**
  3204. * Gets a new Vector3 from current Vector3 floored values
  3205. * @returns a new Vector3
  3206. */
  3207. Vector3.prototype.fract = function () {
  3208. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3209. };
  3210. // Properties
  3211. /**
  3212. * Gets the length of the Vector3
  3213. * @returns the length of the Vecto3
  3214. */
  3215. Vector3.prototype.length = function () {
  3216. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3217. };
  3218. /**
  3219. * Gets the squared length of the Vector3
  3220. * @returns squared length of the Vector3
  3221. */
  3222. Vector3.prototype.lengthSquared = function () {
  3223. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3224. };
  3225. /**
  3226. * Normalize the current Vector3.
  3227. * Please note that this is an in place operation.
  3228. * @returns the current updated Vector3
  3229. */
  3230. Vector3.prototype.normalize = function () {
  3231. var len = this.length();
  3232. if (len === 0 || len === 1.0)
  3233. return this;
  3234. var num = 1.0 / len;
  3235. this.x *= num;
  3236. this.y *= num;
  3237. this.z *= num;
  3238. return this;
  3239. };
  3240. /**
  3241. * Normalize the current Vector3 to a new vector
  3242. * @returns the new Vector3
  3243. */
  3244. Vector3.prototype.normalizeToNew = function () {
  3245. var normalized = new Vector3(0, 0, 0);
  3246. this.normalizeToRef(normalized);
  3247. return normalized;
  3248. };
  3249. /**
  3250. * Normalize the current Vector3 to the reference
  3251. * @param reference define the Vector3 to update
  3252. * @returns the updated Vector3
  3253. */
  3254. Vector3.prototype.normalizeToRef = function (reference) {
  3255. var len = this.length();
  3256. if (len === 0 || len === 1.0) {
  3257. reference.set(this.x, this.y, this.z);
  3258. return reference;
  3259. }
  3260. var scale = 1.0 / len;
  3261. this.scaleToRef(scale, reference);
  3262. return reference;
  3263. };
  3264. /**
  3265. * Creates a new Vector3 copied from the current Vector3
  3266. * @returns the new Vector3
  3267. */
  3268. Vector3.prototype.clone = function () {
  3269. return new Vector3(this.x, this.y, this.z);
  3270. };
  3271. /**
  3272. * Copies the given vector coordinates to the current Vector3 ones
  3273. * @param source defines the source Vector3
  3274. * @returns the current updated Vector3
  3275. */
  3276. Vector3.prototype.copyFrom = function (source) {
  3277. this.x = source.x;
  3278. this.y = source.y;
  3279. this.z = source.z;
  3280. return this;
  3281. };
  3282. /**
  3283. * Copies the given floats to the current Vector3 coordinates
  3284. * @param x defines the x coordinate of the operand
  3285. * @param y defines the y coordinate of the operand
  3286. * @param z defines the z coordinate of the operand
  3287. * @returns the current updated Vector3
  3288. */
  3289. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3290. this.x = x;
  3291. this.y = y;
  3292. this.z = z;
  3293. return this;
  3294. };
  3295. /**
  3296. * Copies the given floats to the current Vector3 coordinates
  3297. * @param x defines the x coordinate of the operand
  3298. * @param y defines the y coordinate of the operand
  3299. * @param z defines the z coordinate of the operand
  3300. * @returns the current updated Vector3
  3301. */
  3302. Vector3.prototype.set = function (x, y, z) {
  3303. return this.copyFromFloats(x, y, z);
  3304. };
  3305. // Statics
  3306. /**
  3307. * Get the clip factor between two vectors
  3308. * @param vector0 defines the first operand
  3309. * @param vector1 defines the second operand
  3310. * @param axis defines the axis to use
  3311. * @param size defines the size along the axis
  3312. * @returns the clip factor
  3313. */
  3314. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3315. var d0 = Vector3.Dot(vector0, axis) - size;
  3316. var d1 = Vector3.Dot(vector1, axis) - size;
  3317. var s = d0 / (d0 - d1);
  3318. return s;
  3319. };
  3320. /**
  3321. * Get angle between two vectors
  3322. * @param vector0 angle between vector0 and vector1
  3323. * @param vector1 angle between vector0 and vector1
  3324. * @param normal direction of the normal
  3325. * @return the angle between vector0 and vector1
  3326. */
  3327. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3328. var v0 = vector0.clone().normalize();
  3329. var v1 = vector1.clone().normalize();
  3330. var dot = Vector3.Dot(v0, v1);
  3331. var n = Vector3.Cross(v0, v1);
  3332. if (Vector3.Dot(n, normal) > 0) {
  3333. return Math.acos(dot);
  3334. }
  3335. return -Math.acos(dot);
  3336. };
  3337. /**
  3338. * Returns a new Vector3 set from the index "offset" of the given array
  3339. * @param array defines the source array
  3340. * @param offset defines the offset in the source array
  3341. * @returns the new Vector3
  3342. */
  3343. Vector3.FromArray = function (array, offset) {
  3344. if (!offset) {
  3345. offset = 0;
  3346. }
  3347. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3348. };
  3349. /**
  3350. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3351. * This function is deprecated. Use FromArray instead
  3352. * @param array defines the source array
  3353. * @param offset defines the offset in the source array
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.FromFloatArray = function (array, offset) {
  3357. return Vector3.FromArray(array, offset);
  3358. };
  3359. /**
  3360. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3361. * @param array defines the source array
  3362. * @param offset defines the offset in the source array
  3363. * @param result defines the Vector3 where to store the result
  3364. */
  3365. Vector3.FromArrayToRef = function (array, offset, result) {
  3366. result.x = array[offset];
  3367. result.y = array[offset + 1];
  3368. result.z = array[offset + 2];
  3369. };
  3370. /**
  3371. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3372. * This function is deprecated. Use FromArrayToRef instead.
  3373. * @param array defines the source array
  3374. * @param offset defines the offset in the source array
  3375. * @param result defines the Vector3 where to store the result
  3376. */
  3377. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3378. return Vector3.FromArrayToRef(array, offset, result);
  3379. };
  3380. /**
  3381. * Sets the given vector "result" with the given floats.
  3382. * @param x defines the x coordinate of the source
  3383. * @param y defines the y coordinate of the source
  3384. * @param z defines the z coordinate of the source
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3388. result.x = x;
  3389. result.y = y;
  3390. result.z = z;
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3394. * @returns a new empty Vector3
  3395. */
  3396. Vector3.Zero = function () {
  3397. return new Vector3(0.0, 0.0, 0.0);
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3401. * @returns a new unit Vector3
  3402. */
  3403. Vector3.One = function () {
  3404. return new Vector3(1.0, 1.0, 1.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3408. * @returns a new up Vector3
  3409. */
  3410. Vector3.Up = function () {
  3411. return new Vector3(0.0, 1.0, 0.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3415. * @returns a new down Vector3
  3416. */
  3417. Vector3.Down = function () {
  3418. return new Vector3(0.0, -1.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3422. * @returns a new forward Vector3
  3423. */
  3424. Vector3.Forward = function () {
  3425. return new Vector3(0.0, 0.0, 1.0);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3429. * @returns a new right Vector3
  3430. */
  3431. Vector3.Right = function () {
  3432. return new Vector3(1.0, 0.0, 0.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3436. * @returns a new left Vector3
  3437. */
  3438. Vector3.Left = function () {
  3439. return new Vector3(-1.0, 0.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3443. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3444. * @param vector defines the Vector3 to transform
  3445. * @param transformation defines the transformation matrix
  3446. * @returns the transformed Vector3
  3447. */
  3448. Vector3.TransformCoordinates = function (vector, transformation) {
  3449. var result = Vector3.Zero();
  3450. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3451. return result;
  3452. };
  3453. /**
  3454. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3455. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3456. * @param vector defines the Vector3 to transform
  3457. * @param transformation defines the transformation matrix
  3458. * @param result defines the Vector3 where to store the result
  3459. */
  3460. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3461. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3462. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3463. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3464. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3465. result.x = x / w;
  3466. result.y = y / w;
  3467. result.z = z / w;
  3468. };
  3469. /**
  3470. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3471. * This method computes tranformed coordinates only, not transformed direction vectors
  3472. * @param x define the x coordinate of the source vector
  3473. * @param y define the y coordinate of the source vector
  3474. * @param z define the z coordinate of the source vector
  3475. * @param transformation defines the transformation matrix
  3476. * @param result defines the Vector3 where to store the result
  3477. */
  3478. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3479. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3480. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3481. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3482. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3483. result.x = rx / rw;
  3484. result.y = ry / rw;
  3485. result.z = rz / rw;
  3486. };
  3487. /**
  3488. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3489. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3490. * @param vector defines the Vector3 to transform
  3491. * @param transformation defines the transformation matrix
  3492. * @returns the new Vector3
  3493. */
  3494. Vector3.TransformNormal = function (vector, transformation) {
  3495. var result = Vector3.Zero();
  3496. Vector3.TransformNormalToRef(vector, transformation, result);
  3497. return result;
  3498. };
  3499. /**
  3500. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3501. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3502. * @param vector defines the Vector3 to transform
  3503. * @param transformation defines the transformation matrix
  3504. * @param result defines the Vector3 where to store the result
  3505. */
  3506. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3507. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3508. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3509. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3510. result.x = x;
  3511. result.y = y;
  3512. result.z = z;
  3513. };
  3514. /**
  3515. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3516. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3517. * @param x define the x coordinate of the source vector
  3518. * @param y define the y coordinate of the source vector
  3519. * @param z define the z coordinate of the source vector
  3520. * @param transformation defines the transformation matrix
  3521. * @param result defines the Vector3 where to store the result
  3522. */
  3523. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3524. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3525. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3526. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3527. };
  3528. /**
  3529. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3530. * @param value1 defines the first control point
  3531. * @param value2 defines the second control point
  3532. * @param value3 defines the third control point
  3533. * @param value4 defines the fourth control point
  3534. * @param amount defines the amount on the spline to use
  3535. * @returns the new Vector3
  3536. */
  3537. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3538. var squared = amount * amount;
  3539. var cubed = amount * squared;
  3540. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3541. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3542. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3543. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3544. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3545. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3546. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3547. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3548. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3549. return new Vector3(x, y, z);
  3550. };
  3551. /**
  3552. * 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"
  3553. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3554. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3555. * @param value defines the current value
  3556. * @param min defines the lower range value
  3557. * @param max defines the upper range value
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Clamp = function (value, min, max) {
  3561. var x = value.x;
  3562. x = (x > max.x) ? max.x : x;
  3563. x = (x < min.x) ? min.x : x;
  3564. var y = value.y;
  3565. y = (y > max.y) ? max.y : y;
  3566. y = (y < min.y) ? min.y : y;
  3567. var z = value.z;
  3568. z = (z > max.z) ? max.z : z;
  3569. z = (z < min.z) ? min.z : z;
  3570. return new Vector3(x, y, z);
  3571. };
  3572. /**
  3573. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3574. * @param value1 defines the first control point
  3575. * @param tangent1 defines the first tangent vector
  3576. * @param value2 defines the second control point
  3577. * @param tangent2 defines the second tangent vector
  3578. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3582. var squared = amount * amount;
  3583. var cubed = amount * squared;
  3584. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3585. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3586. var part3 = (cubed - (2.0 * squared)) + amount;
  3587. var part4 = cubed - squared;
  3588. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3589. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3590. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3591. return new Vector3(x, y, z);
  3592. };
  3593. /**
  3594. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3595. * @param start defines the start value
  3596. * @param end defines the end value
  3597. * @param amount max defines amount between both (between 0 and 1)
  3598. * @returns the new Vector3
  3599. */
  3600. Vector3.Lerp = function (start, end, amount) {
  3601. var result = new Vector3(0, 0, 0);
  3602. Vector3.LerpToRef(start, end, amount, result);
  3603. return result;
  3604. };
  3605. /**
  3606. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3607. * @param start defines the start value
  3608. * @param end defines the end value
  3609. * @param amount max defines amount between both (between 0 and 1)
  3610. * @param result defines the Vector3 where to store the result
  3611. */
  3612. Vector3.LerpToRef = function (start, end, amount, result) {
  3613. result.x = start.x + ((end.x - start.x) * amount);
  3614. result.y = start.y + ((end.y - start.y) * amount);
  3615. result.z = start.z + ((end.z - start.z) * amount);
  3616. };
  3617. /**
  3618. * Returns the dot product (float) between the vectors "left" and "right"
  3619. * @param left defines the left operand
  3620. * @param right defines the right operand
  3621. * @returns the dot product
  3622. */
  3623. Vector3.Dot = function (left, right) {
  3624. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3625. };
  3626. /**
  3627. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3628. * The cross product is then orthogonal to both "left" and "right"
  3629. * @param left defines the left operand
  3630. * @param right defines the right operand
  3631. * @returns the cross product
  3632. */
  3633. Vector3.Cross = function (left, right) {
  3634. var result = Vector3.Zero();
  3635. Vector3.CrossToRef(left, right, result);
  3636. return result;
  3637. };
  3638. /**
  3639. * Sets the given vector "result" with the cross product of "left" and "right"
  3640. * The cross product is then orthogonal to both "left" and "right"
  3641. * @param left defines the left operand
  3642. * @param right defines the right operand
  3643. * @param result defines the Vector3 where to store the result
  3644. */
  3645. Vector3.CrossToRef = function (left, right, result) {
  3646. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3647. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3648. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3649. result.copyFrom(MathTmp.Vector3[0]);
  3650. };
  3651. /**
  3652. * Returns a new Vector3 as the normalization of the given vector
  3653. * @param vector defines the Vector3 to normalize
  3654. * @returns the new Vector3
  3655. */
  3656. Vector3.Normalize = function (vector) {
  3657. var result = Vector3.Zero();
  3658. Vector3.NormalizeToRef(vector, result);
  3659. return result;
  3660. };
  3661. /**
  3662. * Sets the given vector "result" with the normalization of the given first vector
  3663. * @param vector defines the Vector3 to normalize
  3664. * @param result defines the Vector3 where to store the result
  3665. */
  3666. Vector3.NormalizeToRef = function (vector, result) {
  3667. result.copyFrom(vector);
  3668. result.normalize();
  3669. };
  3670. /**
  3671. * Project a Vector3 onto screen space
  3672. * @param vector defines the Vector3 to project
  3673. * @param world defines the world matrix to use
  3674. * @param transform defines the transform (view x projection) matrix to use
  3675. * @param viewport defines the screen viewport to use
  3676. * @returns the new Vector3
  3677. */
  3678. Vector3.Project = function (vector, world, transform, viewport) {
  3679. var cw = viewport.width;
  3680. var ch = viewport.height;
  3681. var cx = viewport.x;
  3682. var cy = viewport.y;
  3683. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3684. 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);
  3685. var matrix = MathTmp.Matrix[0];
  3686. world.multiplyToRef(transform, matrix);
  3687. matrix.multiplyToRef(viewportMatrix, matrix);
  3688. return Vector3.TransformCoordinates(vector, matrix);
  3689. };
  3690. /**
  3691. * Unproject from screen space to object space
  3692. * @param source defines the screen space Vector3 to use
  3693. * @param viewportWidth defines the current width of the viewport
  3694. * @param viewportHeight defines the current height of the viewport
  3695. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3696. * @param transform defines the transform (view x projection) matrix to use
  3697. * @returns the new Vector3
  3698. */
  3699. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3700. var matrix = MathTmp.Matrix[0];
  3701. world.multiplyToRef(transform, matrix);
  3702. matrix.invert();
  3703. source.x = source.x / viewportWidth * 2 - 1;
  3704. source.y = -(source.y / viewportHeight * 2 - 1);
  3705. var vector = Vector3.TransformCoordinates(source, matrix);
  3706. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3707. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3708. vector = vector.scale(1.0 / num);
  3709. }
  3710. return vector;
  3711. };
  3712. /**
  3713. * Unproject from screen space to object space
  3714. * @param source defines the screen space Vector3 to use
  3715. * @param viewportWidth defines the current width of the viewport
  3716. * @param viewportHeight defines the current height of the viewport
  3717. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3718. * @param view defines the view matrix to use
  3719. * @param projection defines the projection matrix to use
  3720. * @returns the new Vector3
  3721. */
  3722. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3723. var result = Vector3.Zero();
  3724. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3725. return result;
  3726. };
  3727. /**
  3728. * Unproject from screen space to object space
  3729. * @param source defines the screen space Vector3 to use
  3730. * @param viewportWidth defines the current width of the viewport
  3731. * @param viewportHeight defines the current height of the viewport
  3732. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3733. * @param view defines the view matrix to use
  3734. * @param projection defines the projection matrix to use
  3735. * @param result defines the Vector3 where to store the result
  3736. */
  3737. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3738. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3739. };
  3740. /**
  3741. * Unproject from screen space to object space
  3742. * @param sourceX defines the screen space x coordinate to use
  3743. * @param sourceY defines the screen space y coordinate to use
  3744. * @param sourceZ defines the screen space z coordinate to use
  3745. * @param viewportWidth defines the current width of the viewport
  3746. * @param viewportHeight defines the current height of the viewport
  3747. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3748. * @param view defines the view matrix to use
  3749. * @param projection defines the projection matrix to use
  3750. * @param result defines the Vector3 where to store the result
  3751. */
  3752. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3753. var matrix = MathTmp.Matrix[0];
  3754. world.multiplyToRef(view, matrix);
  3755. matrix.multiplyToRef(projection, matrix);
  3756. matrix.invert();
  3757. var screenSource = MathTmp.Vector3[0];
  3758. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3759. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3760. screenSource.z = 2 * sourceZ - 1.0;
  3761. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3762. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3763. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3764. result.scaleInPlace(1.0 / num);
  3765. }
  3766. };
  3767. /**
  3768. * Gets the minimal coordinate values between two Vector3
  3769. * @param left defines the first operand
  3770. * @param right defines the second operand
  3771. * @returns the new Vector3
  3772. */
  3773. Vector3.Minimize = function (left, right) {
  3774. var min = left.clone();
  3775. min.minimizeInPlace(right);
  3776. return min;
  3777. };
  3778. /**
  3779. * Gets the maximal coordinate values between two Vector3
  3780. * @param left defines the first operand
  3781. * @param right defines the second operand
  3782. * @returns the new Vector3
  3783. */
  3784. Vector3.Maximize = function (left, right) {
  3785. var max = left.clone();
  3786. max.maximizeInPlace(right);
  3787. return max;
  3788. };
  3789. /**
  3790. * Returns the distance between the vectors "value1" and "value2"
  3791. * @param value1 defines the first operand
  3792. * @param value2 defines the second operand
  3793. * @returns the distance
  3794. */
  3795. Vector3.Distance = function (value1, value2) {
  3796. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3797. };
  3798. /**
  3799. * Returns the squared distance between the vectors "value1" and "value2"
  3800. * @param value1 defines the first operand
  3801. * @param value2 defines the second operand
  3802. * @returns the squared distance
  3803. */
  3804. Vector3.DistanceSquared = function (value1, value2) {
  3805. var x = value1.x - value2.x;
  3806. var y = value1.y - value2.y;
  3807. var z = value1.z - value2.z;
  3808. return (x * x) + (y * y) + (z * z);
  3809. };
  3810. /**
  3811. * Returns a new Vector3 located at the center between "value1" and "value2"
  3812. * @param value1 defines the first operand
  3813. * @param value2 defines the second operand
  3814. * @returns the new Vector3
  3815. */
  3816. Vector3.Center = function (value1, value2) {
  3817. var center = value1.add(value2);
  3818. center.scaleInPlace(0.5);
  3819. return center;
  3820. };
  3821. /**
  3822. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3823. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3824. * to something in order to rotate it from its local system to the given target system
  3825. * Note: axis1, axis2 and axis3 are normalized during this operation
  3826. * @param axis1 defines the first axis
  3827. * @param axis2 defines the second axis
  3828. * @param axis3 defines the third axis
  3829. * @returns a new Vector3
  3830. */
  3831. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3832. var rotation = Vector3.Zero();
  3833. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3834. return rotation;
  3835. };
  3836. /**
  3837. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3838. * @param axis1 defines the first axis
  3839. * @param axis2 defines the second axis
  3840. * @param axis3 defines the third axis
  3841. * @param ref defines the Vector3 where to store the result
  3842. */
  3843. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3844. var quat = MathTmp.Quaternion[0];
  3845. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3846. quat.toEulerAnglesToRef(ref);
  3847. };
  3848. return Vector3;
  3849. }());
  3850. BABYLON.Vector3 = Vector3;
  3851. //Vector4 class created for EulerAngle class conversion to Quaternion
  3852. var Vector4 = /** @class */ (function () {
  3853. /**
  3854. * Creates a Vector4 object from the given floats.
  3855. */
  3856. function Vector4(x, y, z, w) {
  3857. this.x = x;
  3858. this.y = y;
  3859. this.z = z;
  3860. this.w = w;
  3861. }
  3862. /**
  3863. * Returns the string with the Vector4 coordinates.
  3864. */
  3865. Vector4.prototype.toString = function () {
  3866. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3867. };
  3868. /**
  3869. * Returns the string "Vector4".
  3870. */
  3871. Vector4.prototype.getClassName = function () {
  3872. return "Vector4";
  3873. };
  3874. /**
  3875. * Returns the Vector4 hash code.
  3876. */
  3877. Vector4.prototype.getHashCode = function () {
  3878. var hash = this.x || 0;
  3879. hash = (hash * 397) ^ (this.y || 0);
  3880. hash = (hash * 397) ^ (this.z || 0);
  3881. hash = (hash * 397) ^ (this.w || 0);
  3882. return hash;
  3883. };
  3884. // Operators
  3885. /**
  3886. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3887. */
  3888. Vector4.prototype.asArray = function () {
  3889. var result = new Array();
  3890. this.toArray(result, 0);
  3891. return result;
  3892. };
  3893. /**
  3894. * Populates the given array from the given index with the Vector4 coordinates.
  3895. * Returns the Vector4.
  3896. */
  3897. Vector4.prototype.toArray = function (array, index) {
  3898. if (index === undefined) {
  3899. index = 0;
  3900. }
  3901. array[index] = this.x;
  3902. array[index + 1] = this.y;
  3903. array[index + 2] = this.z;
  3904. array[index + 3] = this.w;
  3905. return this;
  3906. };
  3907. /**
  3908. * Adds the given vector to the current Vector4.
  3909. * Returns the updated Vector4.
  3910. */
  3911. Vector4.prototype.addInPlace = function (otherVector) {
  3912. this.x += otherVector.x;
  3913. this.y += otherVector.y;
  3914. this.z += otherVector.z;
  3915. this.w += otherVector.w;
  3916. return this;
  3917. };
  3918. /**
  3919. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3920. */
  3921. Vector4.prototype.add = function (otherVector) {
  3922. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3923. };
  3924. /**
  3925. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3926. * Returns the current Vector4.
  3927. */
  3928. Vector4.prototype.addToRef = function (otherVector, result) {
  3929. result.x = this.x + otherVector.x;
  3930. result.y = this.y + otherVector.y;
  3931. result.z = this.z + otherVector.z;
  3932. result.w = this.w + otherVector.w;
  3933. return this;
  3934. };
  3935. /**
  3936. * Subtract in place the given vector from the current Vector4.
  3937. * Returns the updated Vector4.
  3938. */
  3939. Vector4.prototype.subtractInPlace = function (otherVector) {
  3940. this.x -= otherVector.x;
  3941. this.y -= otherVector.y;
  3942. this.z -= otherVector.z;
  3943. this.w -= otherVector.w;
  3944. return this;
  3945. };
  3946. /**
  3947. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3948. */
  3949. Vector4.prototype.subtract = function (otherVector) {
  3950. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3951. };
  3952. /**
  3953. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3954. * Returns the current Vector4.
  3955. */
  3956. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3957. result.x = this.x - otherVector.x;
  3958. result.y = this.y - otherVector.y;
  3959. result.z = this.z - otherVector.z;
  3960. result.w = this.w - otherVector.w;
  3961. return this;
  3962. };
  3963. /**
  3964. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3965. */
  3966. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3967. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3968. };
  3969. /**
  3970. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3971. * Returns the current Vector4.
  3972. */
  3973. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3974. result.x = this.x - x;
  3975. result.y = this.y - y;
  3976. result.z = this.z - z;
  3977. result.w = this.w - w;
  3978. return this;
  3979. };
  3980. /**
  3981. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3982. */
  3983. Vector4.prototype.negate = function () {
  3984. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3985. };
  3986. /**
  3987. * Multiplies the current Vector4 coordinates by scale (float).
  3988. * Returns the updated Vector4.
  3989. */
  3990. Vector4.prototype.scaleInPlace = function (scale) {
  3991. this.x *= scale;
  3992. this.y *= scale;
  3993. this.z *= scale;
  3994. this.w *= scale;
  3995. return this;
  3996. };
  3997. /**
  3998. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3999. */
  4000. Vector4.prototype.scale = function (scale) {
  4001. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4002. };
  4003. /**
  4004. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4005. * Returns the current Vector4.
  4006. */
  4007. Vector4.prototype.scaleToRef = function (scale, result) {
  4008. result.x = this.x * scale;
  4009. result.y = this.y * scale;
  4010. result.z = this.z * scale;
  4011. result.w = this.w * scale;
  4012. return this;
  4013. };
  4014. /**
  4015. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4016. * @param scale defines the scale factor
  4017. * @param result defines the Vector4 object where to store the result
  4018. * @returns the unmodified current Vector4
  4019. */
  4020. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4021. result.x += this.x * scale;
  4022. result.y += this.y * scale;
  4023. result.z += this.z * scale;
  4024. result.w += this.w * scale;
  4025. return this;
  4026. };
  4027. /**
  4028. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4029. */
  4030. Vector4.prototype.equals = function (otherVector) {
  4031. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4032. };
  4033. /**
  4034. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4035. */
  4036. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4037. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4038. return otherVector
  4039. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4040. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4041. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4042. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4043. };
  4044. /**
  4045. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4046. */
  4047. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4048. return this.x === x && this.y === y && this.z === z && this.w === w;
  4049. };
  4050. /**
  4051. * Multiplies in place the current Vector4 by the given one.
  4052. * Returns the updated Vector4.
  4053. */
  4054. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4055. this.x *= otherVector.x;
  4056. this.y *= otherVector.y;
  4057. this.z *= otherVector.z;
  4058. this.w *= otherVector.w;
  4059. return this;
  4060. };
  4061. /**
  4062. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4063. */
  4064. Vector4.prototype.multiply = function (otherVector) {
  4065. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4066. };
  4067. /**
  4068. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4069. * Returns the current Vector4.
  4070. */
  4071. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4072. result.x = this.x * otherVector.x;
  4073. result.y = this.y * otherVector.y;
  4074. result.z = this.z * otherVector.z;
  4075. result.w = this.w * otherVector.w;
  4076. return this;
  4077. };
  4078. /**
  4079. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4080. */
  4081. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4082. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4083. };
  4084. /**
  4085. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4086. */
  4087. Vector4.prototype.divide = function (otherVector) {
  4088. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4089. };
  4090. /**
  4091. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4092. * Returns the current Vector4.
  4093. */
  4094. Vector4.prototype.divideToRef = function (otherVector, result) {
  4095. result.x = this.x / otherVector.x;
  4096. result.y = this.y / otherVector.y;
  4097. result.z = this.z / otherVector.z;
  4098. result.w = this.w / otherVector.w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Divides the current Vector3 coordinates by the given ones.
  4103. * @returns the updated Vector3.
  4104. */
  4105. Vector4.prototype.divideInPlace = function (otherVector) {
  4106. return this.divideToRef(otherVector, this);
  4107. };
  4108. /**
  4109. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4110. * @param other defines the second operand
  4111. * @returns the current updated Vector4
  4112. */
  4113. Vector4.prototype.minimizeInPlace = function (other) {
  4114. if (other.x < this.x)
  4115. this.x = other.x;
  4116. if (other.y < this.y)
  4117. this.y = other.y;
  4118. if (other.z < this.z)
  4119. this.z = other.z;
  4120. if (other.w < this.w)
  4121. this.w = other.w;
  4122. return this;
  4123. };
  4124. /**
  4125. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4126. * @param other defines the second operand
  4127. * @returns the current updated Vector4
  4128. */
  4129. Vector4.prototype.maximizeInPlace = function (other) {
  4130. if (other.x > this.x)
  4131. this.x = other.x;
  4132. if (other.y > this.y)
  4133. this.y = other.y;
  4134. if (other.z > this.z)
  4135. this.z = other.z;
  4136. if (other.w > this.w)
  4137. this.w = other.w;
  4138. return this;
  4139. };
  4140. /**
  4141. * Gets a new Vector4 from current Vector4 floored values
  4142. * @returns a new Vector4
  4143. */
  4144. Vector4.prototype.floor = function () {
  4145. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4146. };
  4147. /**
  4148. * Gets a new Vector4 from current Vector3 floored values
  4149. * @returns a new Vector4
  4150. */
  4151. Vector4.prototype.fract = function () {
  4152. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4153. };
  4154. // Properties
  4155. /**
  4156. * Returns the Vector4 length (float).
  4157. */
  4158. Vector4.prototype.length = function () {
  4159. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4160. };
  4161. /**
  4162. * Returns the Vector4 squared length (float).
  4163. */
  4164. Vector4.prototype.lengthSquared = function () {
  4165. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4166. };
  4167. // Methods
  4168. /**
  4169. * Normalizes in place the Vector4.
  4170. * Returns the updated Vector4.
  4171. */
  4172. Vector4.prototype.normalize = function () {
  4173. var len = this.length();
  4174. if (len === 0)
  4175. return this;
  4176. var num = 1.0 / len;
  4177. this.x *= num;
  4178. this.y *= num;
  4179. this.z *= num;
  4180. this.w *= num;
  4181. return this;
  4182. };
  4183. /**
  4184. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4185. */
  4186. Vector4.prototype.toVector3 = function () {
  4187. return new Vector3(this.x, this.y, this.z);
  4188. };
  4189. /**
  4190. * Returns a new Vector4 copied from the current one.
  4191. */
  4192. Vector4.prototype.clone = function () {
  4193. return new Vector4(this.x, this.y, this.z, this.w);
  4194. };
  4195. /**
  4196. * Updates the current Vector4 with the given one coordinates.
  4197. * Returns the updated Vector4.
  4198. */
  4199. Vector4.prototype.copyFrom = function (source) {
  4200. this.x = source.x;
  4201. this.y = source.y;
  4202. this.z = source.z;
  4203. this.w = source.w;
  4204. return this;
  4205. };
  4206. /**
  4207. * Updates the current Vector4 coordinates with the given floats.
  4208. * Returns the updated Vector4.
  4209. */
  4210. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4211. this.x = x;
  4212. this.y = y;
  4213. this.z = z;
  4214. this.w = w;
  4215. return this;
  4216. };
  4217. /**
  4218. * Updates the current Vector4 coordinates with the given floats.
  4219. * Returns the updated Vector4.
  4220. */
  4221. Vector4.prototype.set = function (x, y, z, w) {
  4222. return this.copyFromFloats(x, y, z, w);
  4223. };
  4224. // Statics
  4225. /**
  4226. * Returns a new Vector4 set from the starting index of the given array.
  4227. */
  4228. Vector4.FromArray = function (array, offset) {
  4229. if (!offset) {
  4230. offset = 0;
  4231. }
  4232. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4233. };
  4234. /**
  4235. * Updates the given vector "result" from the starting index of the given array.
  4236. */
  4237. Vector4.FromArrayToRef = function (array, offset, result) {
  4238. result.x = array[offset];
  4239. result.y = array[offset + 1];
  4240. result.z = array[offset + 2];
  4241. result.w = array[offset + 3];
  4242. };
  4243. /**
  4244. * Updates the given vector "result" from the starting index of the given Float32Array.
  4245. */
  4246. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4247. Vector4.FromArrayToRef(array, offset, result);
  4248. };
  4249. /**
  4250. * Updates the given vector "result" coordinates from the given floats.
  4251. */
  4252. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4253. result.x = x;
  4254. result.y = y;
  4255. result.z = z;
  4256. result.w = w;
  4257. };
  4258. /**
  4259. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4260. */
  4261. Vector4.Zero = function () {
  4262. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4263. };
  4264. /**
  4265. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4266. */
  4267. Vector4.One = function () {
  4268. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4269. };
  4270. /**
  4271. * Returns a new normalized Vector4 from the given one.
  4272. */
  4273. Vector4.Normalize = function (vector) {
  4274. var result = Vector4.Zero();
  4275. Vector4.NormalizeToRef(vector, result);
  4276. return result;
  4277. };
  4278. /**
  4279. * Updates the given vector "result" from the normalization of the given one.
  4280. */
  4281. Vector4.NormalizeToRef = function (vector, result) {
  4282. result.copyFrom(vector);
  4283. result.normalize();
  4284. };
  4285. Vector4.Minimize = function (left, right) {
  4286. var min = left.clone();
  4287. min.minimizeInPlace(right);
  4288. return min;
  4289. };
  4290. Vector4.Maximize = function (left, right) {
  4291. var max = left.clone();
  4292. max.maximizeInPlace(right);
  4293. return max;
  4294. };
  4295. /**
  4296. * Returns the distance (float) between the vectors "value1" and "value2".
  4297. */
  4298. Vector4.Distance = function (value1, value2) {
  4299. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4300. };
  4301. /**
  4302. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4303. */
  4304. Vector4.DistanceSquared = function (value1, value2) {
  4305. var x = value1.x - value2.x;
  4306. var y = value1.y - value2.y;
  4307. var z = value1.z - value2.z;
  4308. var w = value1.w - value2.w;
  4309. return (x * x) + (y * y) + (z * z) + (w * w);
  4310. };
  4311. /**
  4312. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4313. */
  4314. Vector4.Center = function (value1, value2) {
  4315. var center = value1.add(value2);
  4316. center.scaleInPlace(0.5);
  4317. return center;
  4318. };
  4319. /**
  4320. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4321. * This methods computes transformed normalized direction vectors only.
  4322. */
  4323. Vector4.TransformNormal = function (vector, transformation) {
  4324. var result = Vector4.Zero();
  4325. Vector4.TransformNormalToRef(vector, transformation, result);
  4326. return result;
  4327. };
  4328. /**
  4329. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4330. * This methods computes transformed normalized direction vectors only.
  4331. */
  4332. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4333. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4334. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4335. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4336. result.x = x;
  4337. result.y = y;
  4338. result.z = z;
  4339. result.w = vector.w;
  4340. };
  4341. /**
  4342. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4343. * This methods computes transformed normalized direction vectors only.
  4344. */
  4345. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4346. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4347. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4348. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4349. result.w = w;
  4350. };
  4351. return Vector4;
  4352. }());
  4353. BABYLON.Vector4 = Vector4;
  4354. var Size = /** @class */ (function () {
  4355. /**
  4356. * Creates a Size object from the given width and height (floats).
  4357. */
  4358. function Size(width, height) {
  4359. this.width = width;
  4360. this.height = height;
  4361. }
  4362. // Returns a string with the Size width and height.
  4363. Size.prototype.toString = function () {
  4364. return "{W: " + this.width + ", H: " + this.height + "}";
  4365. };
  4366. /**
  4367. * Returns the string "Size"
  4368. */
  4369. Size.prototype.getClassName = function () {
  4370. return "Size";
  4371. };
  4372. /**
  4373. * Returns the Size hash code.
  4374. */
  4375. Size.prototype.getHashCode = function () {
  4376. var hash = this.width || 0;
  4377. hash = (hash * 397) ^ (this.height || 0);
  4378. return hash;
  4379. };
  4380. /**
  4381. * Updates the current size from the given one.
  4382. * Returns the updated Size.
  4383. */
  4384. Size.prototype.copyFrom = function (src) {
  4385. this.width = src.width;
  4386. this.height = src.height;
  4387. };
  4388. /**
  4389. * Updates in place the current Size from the given floats.
  4390. * Returns the updated Size.
  4391. */
  4392. Size.prototype.copyFromFloats = function (width, height) {
  4393. this.width = width;
  4394. this.height = height;
  4395. return this;
  4396. };
  4397. /**
  4398. * Updates in place the current Size from the given floats.
  4399. * Returns the updated Size.
  4400. */
  4401. Size.prototype.set = function (width, height) {
  4402. return this.copyFromFloats(width, height);
  4403. };
  4404. /**
  4405. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4406. */
  4407. Size.prototype.multiplyByFloats = function (w, h) {
  4408. return new Size(this.width * w, this.height * h);
  4409. };
  4410. /**
  4411. * Returns a new Size copied from the given one.
  4412. */
  4413. Size.prototype.clone = function () {
  4414. return new Size(this.width, this.height);
  4415. };
  4416. /**
  4417. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4418. */
  4419. Size.prototype.equals = function (other) {
  4420. if (!other) {
  4421. return false;
  4422. }
  4423. return (this.width === other.width) && (this.height === other.height);
  4424. };
  4425. Object.defineProperty(Size.prototype, "surface", {
  4426. /**
  4427. * Returns the surface of the Size : width * height (float).
  4428. */
  4429. get: function () {
  4430. return this.width * this.height;
  4431. },
  4432. enumerable: true,
  4433. configurable: true
  4434. });
  4435. /**
  4436. * Returns a new Size set to (0.0, 0.0)
  4437. */
  4438. Size.Zero = function () {
  4439. return new Size(0.0, 0.0);
  4440. };
  4441. /**
  4442. * Returns a new Size set as the addition result of the current Size and the given one.
  4443. */
  4444. Size.prototype.add = function (otherSize) {
  4445. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4446. return r;
  4447. };
  4448. /**
  4449. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4450. */
  4451. Size.prototype.subtract = function (otherSize) {
  4452. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4453. return r;
  4454. };
  4455. /**
  4456. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4457. */
  4458. Size.Lerp = function (start, end, amount) {
  4459. var w = start.width + ((end.width - start.width) * amount);
  4460. var h = start.height + ((end.height - start.height) * amount);
  4461. return new Size(w, h);
  4462. };
  4463. return Size;
  4464. }());
  4465. BABYLON.Size = Size;
  4466. /**
  4467. * Class used to store quaternion data
  4468. * @see https://en.wikipedia.org/wiki/Quaternion
  4469. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4470. */
  4471. var Quaternion = /** @class */ (function () {
  4472. /**
  4473. * Creates a new Quaternion from the given floats
  4474. * @param x defines the first component (0 by default)
  4475. * @param y defines the second component (0 by default)
  4476. * @param z defines the third component (0 by default)
  4477. * @param w defines the fourth component (1.0 by default)
  4478. */
  4479. function Quaternion(
  4480. /** defines the first component (0 by default) */
  4481. x,
  4482. /** defines the second component (0 by default) */
  4483. y,
  4484. /** defines the third component (0 by default) */
  4485. z,
  4486. /** defines the fourth component (1.0 by default) */
  4487. w) {
  4488. if (x === void 0) { x = 0.0; }
  4489. if (y === void 0) { y = 0.0; }
  4490. if (z === void 0) { z = 0.0; }
  4491. if (w === void 0) { w = 1.0; }
  4492. this.x = x;
  4493. this.y = y;
  4494. this.z = z;
  4495. this.w = w;
  4496. }
  4497. /**
  4498. * Gets a string representation for the current quaternion
  4499. * @returns a string with the Quaternion coordinates
  4500. */
  4501. Quaternion.prototype.toString = function () {
  4502. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4503. };
  4504. /**
  4505. * Gets the class name of the quaternion
  4506. * @returns the string "Quaternion"
  4507. */
  4508. Quaternion.prototype.getClassName = function () {
  4509. return "Quaternion";
  4510. };
  4511. /**
  4512. * Gets a hash code for this quaternion
  4513. * @returns the quaternion hash code
  4514. */
  4515. Quaternion.prototype.getHashCode = function () {
  4516. var hash = this.x || 0;
  4517. hash = (hash * 397) ^ (this.y || 0);
  4518. hash = (hash * 397) ^ (this.z || 0);
  4519. hash = (hash * 397) ^ (this.w || 0);
  4520. return hash;
  4521. };
  4522. /**
  4523. * Copy the quaternion to an array
  4524. * @returns a new array populated with 4 elements from the quaternion coordinates
  4525. */
  4526. Quaternion.prototype.asArray = function () {
  4527. return [this.x, this.y, this.z, this.w];
  4528. };
  4529. /**
  4530. * Check if two quaternions are equals
  4531. * @param otherQuaternion defines the second operand
  4532. * @return true if the current quaternion and the given one coordinates are strictly equals
  4533. */
  4534. Quaternion.prototype.equals = function (otherQuaternion) {
  4535. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4536. };
  4537. /**
  4538. * Clone the current quaternion
  4539. * @returns a new quaternion copied from the current one
  4540. */
  4541. Quaternion.prototype.clone = function () {
  4542. return new Quaternion(this.x, this.y, this.z, this.w);
  4543. };
  4544. /**
  4545. * Copy a quaternion to the current one
  4546. * @param other defines the other quaternion
  4547. * @returns the updated current quaternion
  4548. */
  4549. Quaternion.prototype.copyFrom = function (other) {
  4550. this.x = other.x;
  4551. this.y = other.y;
  4552. this.z = other.z;
  4553. this.w = other.w;
  4554. return this;
  4555. };
  4556. /**
  4557. * Updates the current quaternion with the given float coordinates
  4558. * @param x defines the x coordinate
  4559. * @param y defines the y coordinate
  4560. * @param z defines the z coordinate
  4561. * @param w defines the w coordinate
  4562. * @returns the updated current quaternion
  4563. */
  4564. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4565. this.x = x;
  4566. this.y = y;
  4567. this.z = z;
  4568. this.w = w;
  4569. return this;
  4570. };
  4571. /**
  4572. * Updates the current quaternion from the given float coordinates
  4573. * @param x defines the x coordinate
  4574. * @param y defines the y coordinate
  4575. * @param z defines the z coordinate
  4576. * @param w defines the w coordinate
  4577. * @returns the updated current quaternion
  4578. */
  4579. Quaternion.prototype.set = function (x, y, z, w) {
  4580. return this.copyFromFloats(x, y, z, w);
  4581. };
  4582. /**
  4583. * Adds two quaternions
  4584. * @param other defines the second operand
  4585. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4586. */
  4587. Quaternion.prototype.add = function (other) {
  4588. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4589. };
  4590. /**
  4591. * Add a quaternion to the current one
  4592. * @param other defines the quaternion to add
  4593. * @returns the current quaternion
  4594. */
  4595. Quaternion.prototype.addInPlace = function (other) {
  4596. this.x += other.x;
  4597. this.y += other.y;
  4598. this.z += other.z;
  4599. this.w += other.w;
  4600. return this;
  4601. };
  4602. /**
  4603. * Subtract two quaternions
  4604. * @param other defines the second operand
  4605. * @returns a new quaternion as the subtraction result of the given one from the current one
  4606. */
  4607. Quaternion.prototype.subtract = function (other) {
  4608. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4609. };
  4610. /**
  4611. * Multiplies the current quaternion by a scale factor
  4612. * @param value defines the scale factor
  4613. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4614. */
  4615. Quaternion.prototype.scale = function (value) {
  4616. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4617. };
  4618. /**
  4619. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4620. * @param scale defines the scale factor
  4621. * @param result defines the Quaternion object where to store the result
  4622. * @returns the unmodified current quaternion
  4623. */
  4624. Quaternion.prototype.scaleToRef = function (scale, result) {
  4625. result.x = this.x * scale;
  4626. result.y = this.y * scale;
  4627. result.z = this.z * scale;
  4628. result.w = this.w * scale;
  4629. return this;
  4630. };
  4631. /**
  4632. * Multiplies in place the current quaternion by a scale factor
  4633. * @param value defines the scale factor
  4634. * @returns the current modified quaternion
  4635. */
  4636. Quaternion.prototype.scaleInPlace = function (value) {
  4637. this.x *= value;
  4638. this.y *= value;
  4639. this.z *= value;
  4640. this.w *= value;
  4641. return this;
  4642. };
  4643. /**
  4644. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4645. * @param scale defines the scale factor
  4646. * @param result defines the Quaternion object where to store the result
  4647. * @returns the unmodified current quaternion
  4648. */
  4649. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4650. result.x += this.x * scale;
  4651. result.y += this.y * scale;
  4652. result.z += this.z * scale;
  4653. result.w += this.w * scale;
  4654. return this;
  4655. };
  4656. /**
  4657. * Multiplies two quaternions
  4658. * @param q1 defines the second operand
  4659. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4660. */
  4661. Quaternion.prototype.multiply = function (q1) {
  4662. var result = new Quaternion(0, 0, 0, 1.0);
  4663. this.multiplyToRef(q1, result);
  4664. return result;
  4665. };
  4666. /**
  4667. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4668. * @param q1 defines the second operand
  4669. * @param result defines the target quaternion
  4670. * @returns the current quaternion
  4671. */
  4672. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4673. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4674. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4675. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4676. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4677. result.copyFromFloats(x, y, z, w);
  4678. return this;
  4679. };
  4680. /**
  4681. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4682. * @param q1 defines the second operand
  4683. * @returns the currentupdated quaternion
  4684. */
  4685. Quaternion.prototype.multiplyInPlace = function (q1) {
  4686. this.multiplyToRef(q1, this);
  4687. return this;
  4688. };
  4689. /**
  4690. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4691. * @param ref defines the target quaternion
  4692. * @returns the current quaternion
  4693. */
  4694. Quaternion.prototype.conjugateToRef = function (ref) {
  4695. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4696. return this;
  4697. };
  4698. /**
  4699. * Conjugates in place (1-q) the current quaternion
  4700. * @returns the current updated quaternion
  4701. */
  4702. Quaternion.prototype.conjugateInPlace = function () {
  4703. this.x *= -1;
  4704. this.y *= -1;
  4705. this.z *= -1;
  4706. return this;
  4707. };
  4708. /**
  4709. * Conjugates in place (1-q) the current quaternion
  4710. * @returns a new quaternion
  4711. */
  4712. Quaternion.prototype.conjugate = function () {
  4713. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4714. return result;
  4715. };
  4716. /**
  4717. * Gets length of current quaternion
  4718. * @returns the quaternion length (float)
  4719. */
  4720. Quaternion.prototype.length = function () {
  4721. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4722. };
  4723. /**
  4724. * Normalize in place the current quaternion
  4725. * @returns the current updated quaternion
  4726. */
  4727. Quaternion.prototype.normalize = function () {
  4728. var length = 1.0 / this.length();
  4729. this.x *= length;
  4730. this.y *= length;
  4731. this.z *= length;
  4732. this.w *= length;
  4733. return this;
  4734. };
  4735. /**
  4736. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4737. * @param order is a reserved parameter and is ignore for now
  4738. * @returns a new Vector3 containing the Euler angles
  4739. */
  4740. Quaternion.prototype.toEulerAngles = function (order) {
  4741. if (order === void 0) { order = "YZX"; }
  4742. var result = Vector3.Zero();
  4743. this.toEulerAnglesToRef(result, order);
  4744. return result;
  4745. };
  4746. /**
  4747. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4748. * @param result defines the vector which will be filled with the Euler angles
  4749. * @param order is a reserved parameter and is ignore for now
  4750. * @returns the current unchanged quaternion
  4751. */
  4752. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4753. if (order === void 0) { order = "YZX"; }
  4754. var qz = this.z;
  4755. var qx = this.x;
  4756. var qy = this.y;
  4757. var qw = this.w;
  4758. var sqw = qw * qw;
  4759. var sqz = qz * qz;
  4760. var sqx = qx * qx;
  4761. var sqy = qy * qy;
  4762. var zAxisY = qy * qz - qx * qw;
  4763. var limit = .4999999;
  4764. if (zAxisY < -limit) {
  4765. result.y = 2 * Math.atan2(qy, qw);
  4766. result.x = Math.PI / 2;
  4767. result.z = 0;
  4768. }
  4769. else if (zAxisY > limit) {
  4770. result.y = 2 * Math.atan2(qy, qw);
  4771. result.x = -Math.PI / 2;
  4772. result.z = 0;
  4773. }
  4774. else {
  4775. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4776. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4777. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4778. }
  4779. return this;
  4780. };
  4781. /**
  4782. * Updates the given rotation matrix with the current quaternion values
  4783. * @param result defines the target matrix
  4784. * @returns the current unchanged quaternion
  4785. */
  4786. Quaternion.prototype.toRotationMatrix = function (result) {
  4787. var xx = this.x * this.x;
  4788. var yy = this.y * this.y;
  4789. var zz = this.z * this.z;
  4790. var xy = this.x * this.y;
  4791. var zw = this.z * this.w;
  4792. var zx = this.z * this.x;
  4793. var yw = this.y * this.w;
  4794. var yz = this.y * this.z;
  4795. var xw = this.x * this.w;
  4796. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4797. result.m[1] = 2.0 * (xy + zw);
  4798. result.m[2] = 2.0 * (zx - yw);
  4799. result.m[3] = 0;
  4800. result.m[4] = 2.0 * (xy - zw);
  4801. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4802. result.m[6] = 2.0 * (yz + xw);
  4803. result.m[7] = 0;
  4804. result.m[8] = 2.0 * (zx + yw);
  4805. result.m[9] = 2.0 * (yz - xw);
  4806. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4807. result.m[11] = 0;
  4808. result.m[12] = 0;
  4809. result.m[13] = 0;
  4810. result.m[14] = 0;
  4811. result.m[15] = 1.0;
  4812. result._markAsUpdated();
  4813. return this;
  4814. };
  4815. /**
  4816. * Updates the current quaternion from the given rotation matrix values
  4817. * @param matrix defines the source matrix
  4818. * @returns the current updated quaternion
  4819. */
  4820. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4821. Quaternion.FromRotationMatrixToRef(matrix, this);
  4822. return this;
  4823. };
  4824. // Statics
  4825. /**
  4826. * Creates a new quaternion from a rotation matrix
  4827. * @param matrix defines the source matrix
  4828. * @returns a new quaternion created from the given rotation matrix values
  4829. */
  4830. Quaternion.FromRotationMatrix = function (matrix) {
  4831. var result = new Quaternion();
  4832. Quaternion.FromRotationMatrixToRef(matrix, result);
  4833. return result;
  4834. };
  4835. /**
  4836. * Updates the given quaternion with the given rotation matrix values
  4837. * @param matrix defines the source matrix
  4838. * @param result defines the target quaternion
  4839. */
  4840. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4841. var data = matrix.m;
  4842. var m11 = data[0], m12 = data[4], m13 = data[8];
  4843. var m21 = data[1], m22 = data[5], m23 = data[9];
  4844. var m31 = data[2], m32 = data[6], m33 = data[10];
  4845. var trace = m11 + m22 + m33;
  4846. var s;
  4847. if (trace > 0) {
  4848. s = 0.5 / Math.sqrt(trace + 1.0);
  4849. result.w = 0.25 / s;
  4850. result.x = (m32 - m23) * s;
  4851. result.y = (m13 - m31) * s;
  4852. result.z = (m21 - m12) * s;
  4853. }
  4854. else if (m11 > m22 && m11 > m33) {
  4855. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4856. result.w = (m32 - m23) / s;
  4857. result.x = 0.25 * s;
  4858. result.y = (m12 + m21) / s;
  4859. result.z = (m13 + m31) / s;
  4860. }
  4861. else if (m22 > m33) {
  4862. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4863. result.w = (m13 - m31) / s;
  4864. result.x = (m12 + m21) / s;
  4865. result.y = 0.25 * s;
  4866. result.z = (m23 + m32) / s;
  4867. }
  4868. else {
  4869. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4870. result.w = (m21 - m12) / s;
  4871. result.x = (m13 + m31) / s;
  4872. result.y = (m23 + m32) / s;
  4873. result.z = 0.25 * s;
  4874. }
  4875. };
  4876. /**
  4877. * Returns the dot product (float) between the quaternions "left" and "right"
  4878. * @param left defines the left operand
  4879. * @param right defines the right operand
  4880. * @returns the dot product
  4881. */
  4882. Quaternion.Dot = function (left, right) {
  4883. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4884. };
  4885. /**
  4886. * Checks if the two quaternions are close to each other
  4887. * @param quat0 defines the first quaternion to check
  4888. * @param quat1 defines the second quaternion to check
  4889. * @returns true if the two quaternions are close to each other
  4890. */
  4891. Quaternion.AreClose = function (quat0, quat1) {
  4892. var dot = Quaternion.Dot(quat0, quat1);
  4893. return dot >= 0;
  4894. };
  4895. /**
  4896. * Creates an empty quaternion
  4897. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4898. */
  4899. Quaternion.Zero = function () {
  4900. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4901. };
  4902. /**
  4903. * Inverse a given quaternion
  4904. * @param q defines the source quaternion
  4905. * @returns a new quaternion as the inverted current quaternion
  4906. */
  4907. Quaternion.Inverse = function (q) {
  4908. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4909. };
  4910. /**
  4911. * Creates an identity quaternion
  4912. * @returns the identity quaternion
  4913. */
  4914. Quaternion.Identity = function () {
  4915. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4916. };
  4917. /**
  4918. * Gets a boolean indicating if the given quaternion is identity
  4919. * @param quaternion defines the quaternion to check
  4920. * @returns true if the quaternion is identity
  4921. */
  4922. Quaternion.IsIdentity = function (quaternion) {
  4923. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4924. };
  4925. /**
  4926. * Creates a quaternion from a rotation around an axis
  4927. * @param axis defines the axis to use
  4928. * @param angle defines the angle to use
  4929. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4930. */
  4931. Quaternion.RotationAxis = function (axis, angle) {
  4932. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4933. };
  4934. /**
  4935. * Creates a rotation around an axis and stores it into the given quaternion
  4936. * @param axis defines the axis to use
  4937. * @param angle defines the angle to use
  4938. * @param result defines the target quaternion
  4939. * @returns the target quaternion
  4940. */
  4941. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4942. var sin = Math.sin(angle / 2);
  4943. axis.normalize();
  4944. result.w = Math.cos(angle / 2);
  4945. result.x = axis.x * sin;
  4946. result.y = axis.y * sin;
  4947. result.z = axis.z * sin;
  4948. return result;
  4949. };
  4950. /**
  4951. * Creates a new quaternion from data stored into an array
  4952. * @param array defines the data source
  4953. * @param offset defines the offset in the source array where the data starts
  4954. * @returns a new quaternion
  4955. */
  4956. Quaternion.FromArray = function (array, offset) {
  4957. if (!offset) {
  4958. offset = 0;
  4959. }
  4960. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4961. };
  4962. /**
  4963. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4964. * @param yaw defines the rotation around Y axis
  4965. * @param pitch defines the rotation around X axis
  4966. * @param roll defines the rotation around Z axis
  4967. * @returns the new quaternion
  4968. */
  4969. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4970. var q = new Quaternion();
  4971. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4972. return q;
  4973. };
  4974. /**
  4975. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4976. * @param yaw defines the rotation around Y axis
  4977. * @param pitch defines the rotation around X axis
  4978. * @param roll defines the rotation around Z axis
  4979. * @param result defines the target quaternion
  4980. */
  4981. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4982. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4983. var halfRoll = roll * 0.5;
  4984. var halfPitch = pitch * 0.5;
  4985. var halfYaw = yaw * 0.5;
  4986. var sinRoll = Math.sin(halfRoll);
  4987. var cosRoll = Math.cos(halfRoll);
  4988. var sinPitch = Math.sin(halfPitch);
  4989. var cosPitch = Math.cos(halfPitch);
  4990. var sinYaw = Math.sin(halfYaw);
  4991. var cosYaw = Math.cos(halfYaw);
  4992. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4993. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4994. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4995. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4996. };
  4997. /**
  4998. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4999. * @param alpha defines the rotation around first axis
  5000. * @param beta defines the rotation around second axis
  5001. * @param gamma defines the rotation around third axis
  5002. * @returns the new quaternion
  5003. */
  5004. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5005. var result = new Quaternion();
  5006. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5007. return result;
  5008. };
  5009. /**
  5010. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5011. * @param alpha defines the rotation around first axis
  5012. * @param beta defines the rotation around second axis
  5013. * @param gamma defines the rotation around third axis
  5014. * @param result defines the target quaternion
  5015. */
  5016. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5017. // Produces a quaternion from Euler angles in the z-x-z orientation
  5018. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5019. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5020. var halfBeta = beta * 0.5;
  5021. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5022. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5023. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5024. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5025. };
  5026. /**
  5027. * 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)
  5028. * @param axis1 defines the first axis
  5029. * @param axis2 defines the second axis
  5030. * @param axis3 defines the third axis
  5031. * @returns the new quaternion
  5032. */
  5033. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5034. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5035. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5036. return quat;
  5037. };
  5038. /**
  5039. * 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
  5040. * @param axis1 defines the first axis
  5041. * @param axis2 defines the second axis
  5042. * @param axis3 defines the third axis
  5043. * @param ref defines the target quaternion
  5044. */
  5045. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5046. var rotMat = MathTmp.Matrix[0];
  5047. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5048. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5049. };
  5050. /**
  5051. * Interpolates between two quaternions
  5052. * @param left defines first quaternion
  5053. * @param right defines second quaternion
  5054. * @param amount defines the gradient to use
  5055. * @returns the new interpolated quaternion
  5056. */
  5057. Quaternion.Slerp = function (left, right, amount) {
  5058. var result = Quaternion.Identity();
  5059. Quaternion.SlerpToRef(left, right, amount, result);
  5060. return result;
  5061. };
  5062. /**
  5063. * Interpolates between two quaternions and stores it into a target quaternion
  5064. * @param left defines first quaternion
  5065. * @param right defines second quaternion
  5066. * @param amount defines the gradient to use
  5067. * @param result defines the target quaternion
  5068. */
  5069. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5070. var num2;
  5071. var num3;
  5072. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5073. var flag = false;
  5074. if (num4 < 0) {
  5075. flag = true;
  5076. num4 = -num4;
  5077. }
  5078. if (num4 > 0.999999) {
  5079. num3 = 1 - amount;
  5080. num2 = flag ? -amount : amount;
  5081. }
  5082. else {
  5083. var num5 = Math.acos(num4);
  5084. var num6 = (1.0 / Math.sin(num5));
  5085. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5086. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5087. }
  5088. result.x = (num3 * left.x) + (num2 * right.x);
  5089. result.y = (num3 * left.y) + (num2 * right.y);
  5090. result.z = (num3 * left.z) + (num2 * right.z);
  5091. result.w = (num3 * left.w) + (num2 * right.w);
  5092. };
  5093. /**
  5094. * Interpolate between two quaternions using Hermite interpolation
  5095. * @param value1 defines first quaternion
  5096. * @param tangent1 defines the incoming tangent
  5097. * @param value2 defines second quaternion
  5098. * @param tangent2 defines the outgoing tangent
  5099. * @param amount defines the target quaternion
  5100. * @returns the new interpolated quaternion
  5101. */
  5102. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5103. var squared = amount * amount;
  5104. var cubed = amount * squared;
  5105. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5106. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5107. var part3 = (cubed - (2.0 * squared)) + amount;
  5108. var part4 = cubed - squared;
  5109. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5110. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5111. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5112. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5113. return new Quaternion(x, y, z, w);
  5114. };
  5115. return Quaternion;
  5116. }());
  5117. BABYLON.Quaternion = Quaternion;
  5118. /**
  5119. * Class used to store matrix data (4x4)
  5120. */
  5121. var Matrix = /** @class */ (function () {
  5122. /**
  5123. * Creates an empty matrix (filled with zeros)
  5124. */
  5125. function Matrix() {
  5126. this._isIdentity = false;
  5127. this._isIdentityDirty = true;
  5128. /**
  5129. * Gets or sets the internal data of the matrix
  5130. */
  5131. this.m = new Float32Array(16);
  5132. this._markAsUpdated();
  5133. }
  5134. /** @hidden */
  5135. Matrix.prototype._markAsUpdated = function () {
  5136. this.updateFlag = Matrix._updateFlagSeed++;
  5137. this._isIdentityDirty = true;
  5138. };
  5139. // Properties
  5140. /**
  5141. * Check if the current matrix is indentity
  5142. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5143. * @returns true is the matrix is the identity matrix
  5144. */
  5145. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5146. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5147. if (this._isIdentityDirty) {
  5148. this._isIdentityDirty = false;
  5149. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5150. this._isIdentity = false;
  5151. }
  5152. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5153. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5154. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5155. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5156. this._isIdentity = false;
  5157. }
  5158. else {
  5159. this._isIdentity = true;
  5160. }
  5161. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5162. this._isIdentity = false;
  5163. }
  5164. }
  5165. return this._isIdentity;
  5166. };
  5167. /**
  5168. * Gets the determinant of the matrix
  5169. * @returns the matrix determinant
  5170. */
  5171. Matrix.prototype.determinant = function () {
  5172. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5173. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5174. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5175. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5176. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5177. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5178. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5179. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5180. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5181. };
  5182. // Methods
  5183. /**
  5184. * Returns the matrix as a Float32Array
  5185. * @returns the matrix underlying array
  5186. */
  5187. Matrix.prototype.toArray = function () {
  5188. return this.m;
  5189. };
  5190. /**
  5191. * Returns the matrix as a Float32Array
  5192. * @returns the matrix underlying array.
  5193. */
  5194. Matrix.prototype.asArray = function () {
  5195. return this.toArray();
  5196. };
  5197. /**
  5198. * Inverts the current matrix in place
  5199. * @returns the current inverted matrix
  5200. */
  5201. Matrix.prototype.invert = function () {
  5202. this.invertToRef(this);
  5203. return this;
  5204. };
  5205. /**
  5206. * Sets all the matrix elements to zero
  5207. * @returns the current matrix
  5208. */
  5209. Matrix.prototype.reset = function () {
  5210. for (var index = 0; index < 16; index++) {
  5211. this.m[index] = 0.0;
  5212. }
  5213. this._markAsUpdated();
  5214. return this;
  5215. };
  5216. /**
  5217. * Adds the current matrix with a second one
  5218. * @param other defines the matrix to add
  5219. * @returns a new matrix as the addition of the current matrix and the given one
  5220. */
  5221. Matrix.prototype.add = function (other) {
  5222. var result = new Matrix();
  5223. this.addToRef(other, result);
  5224. return result;
  5225. };
  5226. /**
  5227. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5228. * @param other defines the matrix to add
  5229. * @param result defines the target matrix
  5230. * @returns the current matrix
  5231. */
  5232. Matrix.prototype.addToRef = function (other, result) {
  5233. for (var index = 0; index < 16; index++) {
  5234. result.m[index] = this.m[index] + other.m[index];
  5235. }
  5236. result._markAsUpdated();
  5237. return this;
  5238. };
  5239. /**
  5240. * Adds in place the given matrix to the current matrix
  5241. * @param other defines the second operand
  5242. * @returns the current updated matrix
  5243. */
  5244. Matrix.prototype.addToSelf = function (other) {
  5245. for (var index = 0; index < 16; index++) {
  5246. this.m[index] += other.m[index];
  5247. }
  5248. this._markAsUpdated();
  5249. return this;
  5250. };
  5251. /**
  5252. * Sets the given matrix to the current inverted Matrix
  5253. * @param other defines the target matrix
  5254. * @returns the unmodified current matrix
  5255. */
  5256. Matrix.prototype.invertToRef = function (other) {
  5257. var l1 = this.m[0];
  5258. var l2 = this.m[1];
  5259. var l3 = this.m[2];
  5260. var l4 = this.m[3];
  5261. var l5 = this.m[4];
  5262. var l6 = this.m[5];
  5263. var l7 = this.m[6];
  5264. var l8 = this.m[7];
  5265. var l9 = this.m[8];
  5266. var l10 = this.m[9];
  5267. var l11 = this.m[10];
  5268. var l12 = this.m[11];
  5269. var l13 = this.m[12];
  5270. var l14 = this.m[13];
  5271. var l15 = this.m[14];
  5272. var l16 = this.m[15];
  5273. var l17 = (l11 * l16) - (l12 * l15);
  5274. var l18 = (l10 * l16) - (l12 * l14);
  5275. var l19 = (l10 * l15) - (l11 * l14);
  5276. var l20 = (l9 * l16) - (l12 * l13);
  5277. var l21 = (l9 * l15) - (l11 * l13);
  5278. var l22 = (l9 * l14) - (l10 * l13);
  5279. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5280. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5281. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5282. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5283. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5284. var l28 = (l7 * l16) - (l8 * l15);
  5285. var l29 = (l6 * l16) - (l8 * l14);
  5286. var l30 = (l6 * l15) - (l7 * l14);
  5287. var l31 = (l5 * l16) - (l8 * l13);
  5288. var l32 = (l5 * l15) - (l7 * l13);
  5289. var l33 = (l5 * l14) - (l6 * l13);
  5290. var l34 = (l7 * l12) - (l8 * l11);
  5291. var l35 = (l6 * l12) - (l8 * l10);
  5292. var l36 = (l6 * l11) - (l7 * l10);
  5293. var l37 = (l5 * l12) - (l8 * l9);
  5294. var l38 = (l5 * l11) - (l7 * l9);
  5295. var l39 = (l5 * l10) - (l6 * l9);
  5296. other.m[0] = l23 * l27;
  5297. other.m[4] = l24 * l27;
  5298. other.m[8] = l25 * l27;
  5299. other.m[12] = l26 * l27;
  5300. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5301. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5302. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5303. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5304. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5305. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5306. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5307. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5308. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5309. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5310. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5311. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5312. other._markAsUpdated();
  5313. return this;
  5314. };
  5315. /**
  5316. * Inserts the translation vector (using 3 floats) in the current matrix
  5317. * @param x defines the 1st component of the translation
  5318. * @param y defines the 2nd component of the translation
  5319. * @param z defines the 3rd component of the translation
  5320. * @returns the current updated matrix
  5321. */
  5322. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5323. this.m[12] = x;
  5324. this.m[13] = y;
  5325. this.m[14] = z;
  5326. this._markAsUpdated();
  5327. return this;
  5328. };
  5329. /**
  5330. * Inserts the translation vector in the current matrix
  5331. * @param vector3 defines the translation to insert
  5332. * @returns the current updated matrix
  5333. */
  5334. Matrix.prototype.setTranslation = function (vector3) {
  5335. this.m[12] = vector3.x;
  5336. this.m[13] = vector3.y;
  5337. this.m[14] = vector3.z;
  5338. this._markAsUpdated();
  5339. return this;
  5340. };
  5341. /**
  5342. * Gets the translation value of the current matrix
  5343. * @returns a new Vector3 as the extracted translation from the matrix
  5344. */
  5345. Matrix.prototype.getTranslation = function () {
  5346. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5347. };
  5348. /**
  5349. * Fill a Vector3 with the extracted translation from the matrix
  5350. * @param result defines the Vector3 where to store the translation
  5351. * @returns the current matrix
  5352. */
  5353. Matrix.prototype.getTranslationToRef = function (result) {
  5354. result.x = this.m[12];
  5355. result.y = this.m[13];
  5356. result.z = this.m[14];
  5357. return this;
  5358. };
  5359. /**
  5360. * Remove rotation and scaling part from the matrix
  5361. * @returns the updated matrix
  5362. */
  5363. Matrix.prototype.removeRotationAndScaling = function () {
  5364. this.setRowFromFloats(0, 1, 0, 0, 0);
  5365. this.setRowFromFloats(1, 0, 1, 0, 0);
  5366. this.setRowFromFloats(2, 0, 0, 1, 0);
  5367. return this;
  5368. };
  5369. /**
  5370. * Multiply two matrices
  5371. * @param other defines the second operand
  5372. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5373. */
  5374. Matrix.prototype.multiply = function (other) {
  5375. var result = new Matrix();
  5376. this.multiplyToRef(other, result);
  5377. return result;
  5378. };
  5379. /**
  5380. * Copy the current matrix from the given one
  5381. * @param other defines the source matrix
  5382. * @returns the current updated matrix
  5383. */
  5384. Matrix.prototype.copyFrom = function (other) {
  5385. for (var index = 0; index < 16; index++) {
  5386. this.m[index] = other.m[index];
  5387. }
  5388. this._markAsUpdated();
  5389. return this;
  5390. };
  5391. /**
  5392. * Populates the given array from the starting index with the current matrix values
  5393. * @param array defines the target array
  5394. * @param offset defines the offset in the target array where to start storing values
  5395. * @returns the current matrix
  5396. */
  5397. Matrix.prototype.copyToArray = function (array, offset) {
  5398. if (offset === void 0) { offset = 0; }
  5399. for (var index = 0; index < 16; index++) {
  5400. array[offset + index] = this.m[index];
  5401. }
  5402. return this;
  5403. };
  5404. /**
  5405. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5406. * @param other defines the second operand
  5407. * @param result defines the matrix where to store the multiplication
  5408. * @returns the current matrix
  5409. */
  5410. Matrix.prototype.multiplyToRef = function (other, result) {
  5411. this.multiplyToArray(other, result.m, 0);
  5412. result._markAsUpdated();
  5413. return this;
  5414. };
  5415. /**
  5416. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5417. * @param other defines the second operand
  5418. * @param result defines the array where to store the multiplication
  5419. * @param offset defines the offset in the target array where to start storing values
  5420. * @returns the current matrix
  5421. */
  5422. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5423. var tm0 = this.m[0];
  5424. var tm1 = this.m[1];
  5425. var tm2 = this.m[2];
  5426. var tm3 = this.m[3];
  5427. var tm4 = this.m[4];
  5428. var tm5 = this.m[5];
  5429. var tm6 = this.m[6];
  5430. var tm7 = this.m[7];
  5431. var tm8 = this.m[8];
  5432. var tm9 = this.m[9];
  5433. var tm10 = this.m[10];
  5434. var tm11 = this.m[11];
  5435. var tm12 = this.m[12];
  5436. var tm13 = this.m[13];
  5437. var tm14 = this.m[14];
  5438. var tm15 = this.m[15];
  5439. var om0 = other.m[0];
  5440. var om1 = other.m[1];
  5441. var om2 = other.m[2];
  5442. var om3 = other.m[3];
  5443. var om4 = other.m[4];
  5444. var om5 = other.m[5];
  5445. var om6 = other.m[6];
  5446. var om7 = other.m[7];
  5447. var om8 = other.m[8];
  5448. var om9 = other.m[9];
  5449. var om10 = other.m[10];
  5450. var om11 = other.m[11];
  5451. var om12 = other.m[12];
  5452. var om13 = other.m[13];
  5453. var om14 = other.m[14];
  5454. var om15 = other.m[15];
  5455. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5456. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5457. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5458. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5459. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5460. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5461. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5462. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5463. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5464. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5465. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5466. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5467. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5468. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5469. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5470. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5471. return this;
  5472. };
  5473. /**
  5474. * Check equality between this matrix and a second one
  5475. * @param value defines the second matrix to compare
  5476. * @returns true is the current matrix and the given one values are strictly equal
  5477. */
  5478. Matrix.prototype.equals = function (value) {
  5479. return value &&
  5480. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5481. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5482. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5483. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5484. };
  5485. /**
  5486. * Clone the current matrix
  5487. * @returns a new matrix from the current matrix
  5488. */
  5489. Matrix.prototype.clone = function () {
  5490. 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]);
  5491. };
  5492. /**
  5493. * Returns the name of the current matrix class
  5494. * @returns the string "Matrix"
  5495. */
  5496. Matrix.prototype.getClassName = function () {
  5497. return "Matrix";
  5498. };
  5499. /**
  5500. * Gets the hash code of the current matrix
  5501. * @returns the hash code
  5502. */
  5503. Matrix.prototype.getHashCode = function () {
  5504. var hash = this.m[0] || 0;
  5505. for (var i = 1; i < 16; i++) {
  5506. hash = (hash * 397) ^ (this.m[i] || 0);
  5507. }
  5508. return hash;
  5509. };
  5510. /**
  5511. * Decomposes the current Matrix into a translation, rotation and scaling components
  5512. * @param scale defines the scale vector3 given as a reference to update
  5513. * @param rotation defines the rotation quaternion given as a reference to update
  5514. * @param translation defines the translation vector3 given as a reference to update
  5515. * @returns true if operation was successful
  5516. */
  5517. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5518. if (translation) {
  5519. translation.x = this.m[12];
  5520. translation.y = this.m[13];
  5521. translation.z = this.m[14];
  5522. }
  5523. scale = scale || MathTmp.Vector3[0];
  5524. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5525. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5526. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5527. if (this.determinant() <= 0) {
  5528. scale.y *= -1;
  5529. }
  5530. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5531. if (rotation) {
  5532. rotation.x = 0;
  5533. rotation.y = 0;
  5534. rotation.z = 0;
  5535. rotation.w = 1;
  5536. }
  5537. return false;
  5538. }
  5539. if (rotation) {
  5540. 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]);
  5541. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5542. }
  5543. return true;
  5544. };
  5545. /**
  5546. * Gets specific row of the matrix
  5547. * @param index defines the number of the row to get
  5548. * @returns the index-th row of the current matrix as a new Vector4
  5549. */
  5550. Matrix.prototype.getRow = function (index) {
  5551. if (index < 0 || index > 3) {
  5552. return null;
  5553. }
  5554. var i = index * 4;
  5555. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5556. };
  5557. /**
  5558. * Sets the index-th row of the current matrix to the vector4 values
  5559. * @param index defines the number of the row to set
  5560. * @param row defines the target vector4
  5561. * @returns the updated current matrix
  5562. */
  5563. Matrix.prototype.setRow = function (index, row) {
  5564. if (index < 0 || index > 3) {
  5565. return this;
  5566. }
  5567. var i = index * 4;
  5568. this.m[i + 0] = row.x;
  5569. this.m[i + 1] = row.y;
  5570. this.m[i + 2] = row.z;
  5571. this.m[i + 3] = row.w;
  5572. this._markAsUpdated();
  5573. return this;
  5574. };
  5575. /**
  5576. * Compute the transpose of the matrix
  5577. * @returns the new transposed matrix
  5578. */
  5579. Matrix.prototype.transpose = function () {
  5580. return Matrix.Transpose(this);
  5581. };
  5582. /**
  5583. * Compute the transpose of the matrix and store it in a given matrix
  5584. * @param result defines the target matrix
  5585. * @returns the current matrix
  5586. */
  5587. Matrix.prototype.transposeToRef = function (result) {
  5588. Matrix.TransposeToRef(this, result);
  5589. return this;
  5590. };
  5591. /**
  5592. * Sets the index-th row of the current matrix with the given 4 x float values
  5593. * @param index defines the row index
  5594. * @param x defines the x component to set
  5595. * @param y defines the y component to set
  5596. * @param z defines the z component to set
  5597. * @param w defines the w component to set
  5598. * @returns the updated current matrix
  5599. */
  5600. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5601. if (index < 0 || index > 3) {
  5602. return this;
  5603. }
  5604. var i = index * 4;
  5605. this.m[i + 0] = x;
  5606. this.m[i + 1] = y;
  5607. this.m[i + 2] = z;
  5608. this.m[i + 3] = w;
  5609. this._markAsUpdated();
  5610. return this;
  5611. };
  5612. /**
  5613. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5614. * @param scale defines the scale factor
  5615. * @returns a new matrix
  5616. */
  5617. Matrix.prototype.scale = function (scale) {
  5618. var result = new Matrix();
  5619. this.scaleToRef(scale, result);
  5620. return result;
  5621. };
  5622. /**
  5623. * Scale the current matrix values by a factor to a given result matrix
  5624. * @param scale defines the scale factor
  5625. * @param result defines the matrix to store the result
  5626. * @returns the current matrix
  5627. */
  5628. Matrix.prototype.scaleToRef = function (scale, result) {
  5629. for (var index = 0; index < 16; index++) {
  5630. result.m[index] = this.m[index] * scale;
  5631. }
  5632. result._markAsUpdated();
  5633. return this;
  5634. };
  5635. /**
  5636. * Scale the current matrix values by a factor and add the result to a given matrix
  5637. * @param scale defines the scale factor
  5638. * @param result defines the Matrix to store the result
  5639. * @returns the current matrix
  5640. */
  5641. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5642. for (var index = 0; index < 16; index++) {
  5643. result.m[index] += this.m[index] * scale;
  5644. }
  5645. result._markAsUpdated();
  5646. return this;
  5647. };
  5648. /**
  5649. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5650. * @param ref matrix to store the result
  5651. */
  5652. Matrix.prototype.toNormalMatrix = function (ref) {
  5653. this.invertToRef(ref);
  5654. ref.transpose();
  5655. var m = ref.m;
  5656. 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);
  5657. };
  5658. /**
  5659. * Gets only rotation part of the current matrix
  5660. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5661. */
  5662. Matrix.prototype.getRotationMatrix = function () {
  5663. var result = Matrix.Identity();
  5664. this.getRotationMatrixToRef(result);
  5665. return result;
  5666. };
  5667. /**
  5668. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5669. * @param result defines the target matrix to store data to
  5670. * @returns the current matrix
  5671. */
  5672. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5673. var m = this.m;
  5674. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5675. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5676. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5677. if (this.determinant() <= 0) {
  5678. sy *= -1;
  5679. }
  5680. if (sx === 0 || sy === 0 || sz === 0) {
  5681. Matrix.IdentityToRef(result);
  5682. }
  5683. else {
  5684. 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);
  5685. }
  5686. return this;
  5687. };
  5688. // Statics
  5689. /**
  5690. * Creates a matrix from an array
  5691. * @param array defines the source array
  5692. * @param offset defines an offset in the source array
  5693. * @returns a new Matrix set from the starting index of the given array
  5694. */
  5695. Matrix.FromArray = function (array, offset) {
  5696. var result = new Matrix();
  5697. if (!offset) {
  5698. offset = 0;
  5699. }
  5700. Matrix.FromArrayToRef(array, offset, result);
  5701. return result;
  5702. };
  5703. /**
  5704. * Copy the content of an array into a given matrix
  5705. * @param array defines the source array
  5706. * @param offset defines an offset in the source array
  5707. * @param result defines the target matrix
  5708. */
  5709. Matrix.FromArrayToRef = function (array, offset, result) {
  5710. for (var index = 0; index < 16; index++) {
  5711. result.m[index] = array[index + offset];
  5712. }
  5713. result._markAsUpdated();
  5714. };
  5715. /**
  5716. * Stores an array into a matrix after having multiplied each component by a given factor
  5717. * @param array defines the source array
  5718. * @param offset defines the offset in the source array
  5719. * @param scale defines the scaling factor
  5720. * @param result defines the target matrix
  5721. */
  5722. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5723. for (var index = 0; index < 16; index++) {
  5724. result.m[index] = array[index + offset] * scale;
  5725. }
  5726. result._markAsUpdated();
  5727. };
  5728. /**
  5729. * Stores a list of values (16) inside a given matrix
  5730. * @param initialM11 defines 1st value of 1st row
  5731. * @param initialM12 defines 2nd value of 1st row
  5732. * @param initialM13 defines 3rd value of 1st row
  5733. * @param initialM14 defines 4th value of 1st row
  5734. * @param initialM21 defines 1st value of 2nd row
  5735. * @param initialM22 defines 2nd value of 2nd row
  5736. * @param initialM23 defines 3rd value of 2nd row
  5737. * @param initialM24 defines 4th value of 2nd row
  5738. * @param initialM31 defines 1st value of 3rd row
  5739. * @param initialM32 defines 2nd value of 3rd row
  5740. * @param initialM33 defines 3rd value of 3rd row
  5741. * @param initialM34 defines 4th value of 3rd row
  5742. * @param initialM41 defines 1st value of 4th row
  5743. * @param initialM42 defines 2nd value of 4th row
  5744. * @param initialM43 defines 3rd value of 4th row
  5745. * @param initialM44 defines 4th value of 4th row
  5746. * @param result defines the target matrix
  5747. */
  5748. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5749. result.m[0] = initialM11;
  5750. result.m[1] = initialM12;
  5751. result.m[2] = initialM13;
  5752. result.m[3] = initialM14;
  5753. result.m[4] = initialM21;
  5754. result.m[5] = initialM22;
  5755. result.m[6] = initialM23;
  5756. result.m[7] = initialM24;
  5757. result.m[8] = initialM31;
  5758. result.m[9] = initialM32;
  5759. result.m[10] = initialM33;
  5760. result.m[11] = initialM34;
  5761. result.m[12] = initialM41;
  5762. result.m[13] = initialM42;
  5763. result.m[14] = initialM43;
  5764. result.m[15] = initialM44;
  5765. result._markAsUpdated();
  5766. };
  5767. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5768. /**
  5769. * Gets an identity matrix that must not be updated
  5770. */
  5771. get: function () {
  5772. return Matrix._identityReadOnly;
  5773. },
  5774. enumerable: true,
  5775. configurable: true
  5776. });
  5777. /**
  5778. * Creates new matrix from a list of values (16)
  5779. * @param initialM11 defines 1st value of 1st row
  5780. * @param initialM12 defines 2nd value of 1st row
  5781. * @param initialM13 defines 3rd value of 1st row
  5782. * @param initialM14 defines 4th value of 1st row
  5783. * @param initialM21 defines 1st value of 2nd row
  5784. * @param initialM22 defines 2nd value of 2nd row
  5785. * @param initialM23 defines 3rd value of 2nd row
  5786. * @param initialM24 defines 4th value of 2nd row
  5787. * @param initialM31 defines 1st value of 3rd row
  5788. * @param initialM32 defines 2nd value of 3rd row
  5789. * @param initialM33 defines 3rd value of 3rd row
  5790. * @param initialM34 defines 4th value of 3rd row
  5791. * @param initialM41 defines 1st value of 4th row
  5792. * @param initialM42 defines 2nd value of 4th row
  5793. * @param initialM43 defines 3rd value of 4th row
  5794. * @param initialM44 defines 4th value of 4th row
  5795. * @returns the new matrix
  5796. */
  5797. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5798. var result = new Matrix();
  5799. result.m[0] = initialM11;
  5800. result.m[1] = initialM12;
  5801. result.m[2] = initialM13;
  5802. result.m[3] = initialM14;
  5803. result.m[4] = initialM21;
  5804. result.m[5] = initialM22;
  5805. result.m[6] = initialM23;
  5806. result.m[7] = initialM24;
  5807. result.m[8] = initialM31;
  5808. result.m[9] = initialM32;
  5809. result.m[10] = initialM33;
  5810. result.m[11] = initialM34;
  5811. result.m[12] = initialM41;
  5812. result.m[13] = initialM42;
  5813. result.m[14] = initialM43;
  5814. result.m[15] = initialM44;
  5815. return result;
  5816. };
  5817. /**
  5818. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5819. * @param scale defines the scale vector3
  5820. * @param rotation defines the rotation quaternion
  5821. * @param translation defines the translation vector3
  5822. * @returns a new matrix
  5823. */
  5824. Matrix.Compose = function (scale, rotation, translation) {
  5825. var result = Matrix.Identity();
  5826. Matrix.ComposeToRef(scale, rotation, translation, result);
  5827. return result;
  5828. };
  5829. /**
  5830. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5831. * @param scale defines the scale vector3
  5832. * @param rotation defines the rotation quaternion
  5833. * @param translation defines the translation vector3
  5834. * @param result defines the target matrix
  5835. */
  5836. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5837. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5838. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5839. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5840. result.setTranslation(translation);
  5841. };
  5842. /**
  5843. * Creates a new identity matrix
  5844. * @returns a new identity matrix
  5845. */
  5846. Matrix.Identity = function () {
  5847. 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);
  5848. };
  5849. /**
  5850. * Creates a new identity matrix and stores the result in a given matrix
  5851. * @param result defines the target matrix
  5852. */
  5853. Matrix.IdentityToRef = function (result) {
  5854. 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);
  5855. };
  5856. /**
  5857. * Creates a new zero matrix
  5858. * @returns a new zero matrix
  5859. */
  5860. Matrix.Zero = function () {
  5861. 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);
  5862. };
  5863. /**
  5864. * Creates a new rotation matrix for "angle" radians around the X axis
  5865. * @param angle defines the angle (in radians) to use
  5866. * @return the new matrix
  5867. */
  5868. Matrix.RotationX = function (angle) {
  5869. var result = new Matrix();
  5870. Matrix.RotationXToRef(angle, result);
  5871. return result;
  5872. };
  5873. /**
  5874. * Creates a new matrix as the invert of a given matrix
  5875. * @param source defines the source matrix
  5876. * @returns the new matrix
  5877. */
  5878. Matrix.Invert = function (source) {
  5879. var result = new Matrix();
  5880. source.invertToRef(result);
  5881. return result;
  5882. };
  5883. /**
  5884. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5885. * @param angle defines the angle (in radians) to use
  5886. * @param result defines the target matrix
  5887. */
  5888. Matrix.RotationXToRef = function (angle, result) {
  5889. var s = Math.sin(angle);
  5890. var c = Math.cos(angle);
  5891. result.m[0] = 1.0;
  5892. result.m[15] = 1.0;
  5893. result.m[5] = c;
  5894. result.m[10] = c;
  5895. result.m[9] = -s;
  5896. result.m[6] = s;
  5897. result.m[1] = 0.0;
  5898. result.m[2] = 0.0;
  5899. result.m[3] = 0.0;
  5900. result.m[4] = 0.0;
  5901. result.m[7] = 0.0;
  5902. result.m[8] = 0.0;
  5903. result.m[11] = 0.0;
  5904. result.m[12] = 0.0;
  5905. result.m[13] = 0.0;
  5906. result.m[14] = 0.0;
  5907. result._markAsUpdated();
  5908. };
  5909. /**
  5910. * Creates a new rotation matrix for "angle" radians around the Y axis
  5911. * @param angle defines the angle (in radians) to use
  5912. * @return the new matrix
  5913. */
  5914. Matrix.RotationY = function (angle) {
  5915. var result = new Matrix();
  5916. Matrix.RotationYToRef(angle, result);
  5917. return result;
  5918. };
  5919. /**
  5920. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5921. * @param angle defines the angle (in radians) to use
  5922. * @param result defines the target matrix
  5923. */
  5924. Matrix.RotationYToRef = function (angle, result) {
  5925. var s = Math.sin(angle);
  5926. var c = Math.cos(angle);
  5927. result.m[5] = 1.0;
  5928. result.m[15] = 1.0;
  5929. result.m[0] = c;
  5930. result.m[2] = -s;
  5931. result.m[8] = s;
  5932. result.m[10] = c;
  5933. result.m[1] = 0.0;
  5934. result.m[3] = 0.0;
  5935. result.m[4] = 0.0;
  5936. result.m[6] = 0.0;
  5937. result.m[7] = 0.0;
  5938. result.m[9] = 0.0;
  5939. result.m[11] = 0.0;
  5940. result.m[12] = 0.0;
  5941. result.m[13] = 0.0;
  5942. result.m[14] = 0.0;
  5943. result._markAsUpdated();
  5944. };
  5945. /**
  5946. * Creates a new rotation matrix for "angle" radians around the Z axis
  5947. * @param angle defines the angle (in radians) to use
  5948. * @return the new matrix
  5949. */
  5950. Matrix.RotationZ = function (angle) {
  5951. var result = new Matrix();
  5952. Matrix.RotationZToRef(angle, result);
  5953. return result;
  5954. };
  5955. /**
  5956. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5957. * @param angle defines the angle (in radians) to use
  5958. * @param result defines the target matrix
  5959. */
  5960. Matrix.RotationZToRef = function (angle, result) {
  5961. var s = Math.sin(angle);
  5962. var c = Math.cos(angle);
  5963. result.m[10] = 1.0;
  5964. result.m[15] = 1.0;
  5965. result.m[0] = c;
  5966. result.m[1] = s;
  5967. result.m[4] = -s;
  5968. result.m[5] = c;
  5969. result.m[2] = 0.0;
  5970. result.m[3] = 0.0;
  5971. result.m[6] = 0.0;
  5972. result.m[7] = 0.0;
  5973. result.m[8] = 0.0;
  5974. result.m[9] = 0.0;
  5975. result.m[11] = 0.0;
  5976. result.m[12] = 0.0;
  5977. result.m[13] = 0.0;
  5978. result.m[14] = 0.0;
  5979. result._markAsUpdated();
  5980. };
  5981. /**
  5982. * Creates a new rotation matrix for "angle" radians around the given axis
  5983. * @param axis defines the axis to use
  5984. * @param angle defines the angle (in radians) to use
  5985. * @return the new matrix
  5986. */
  5987. Matrix.RotationAxis = function (axis, angle) {
  5988. var result = Matrix.Zero();
  5989. Matrix.RotationAxisToRef(axis, angle, result);
  5990. return result;
  5991. };
  5992. /**
  5993. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5994. * @param axis defines the axis to use
  5995. * @param angle defines the angle (in radians) to use
  5996. * @param result defines the target matrix
  5997. */
  5998. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5999. var s = Math.sin(-angle);
  6000. var c = Math.cos(-angle);
  6001. var c1 = 1 - c;
  6002. axis.normalize();
  6003. result.m[0] = (axis.x * axis.x) * c1 + c;
  6004. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6005. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6006. result.m[3] = 0.0;
  6007. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6008. result.m[5] = (axis.y * axis.y) * c1 + c;
  6009. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6010. result.m[7] = 0.0;
  6011. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6012. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6013. result.m[10] = (axis.z * axis.z) * c1 + c;
  6014. result.m[11] = 0.0;
  6015. result.m[15] = 1.0;
  6016. result._markAsUpdated();
  6017. };
  6018. /**
  6019. * Creates a rotation matrix
  6020. * @param yaw defines the yaw angle in radians (Y axis)
  6021. * @param pitch defines the pitch angle in radians (X axis)
  6022. * @param roll defines the roll angle in radians (X axis)
  6023. * @returns the new rotation matrix
  6024. */
  6025. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6026. var result = new Matrix();
  6027. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6028. return result;
  6029. };
  6030. /**
  6031. * Creates a rotation matrix and stores it in a given matrix
  6032. * @param yaw defines the yaw angle in radians (Y axis)
  6033. * @param pitch defines the pitch angle in radians (X axis)
  6034. * @param roll defines the roll angle in radians (X axis)
  6035. * @param result defines the target matrix
  6036. */
  6037. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6038. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6039. this._tempQuaternion.toRotationMatrix(result);
  6040. };
  6041. /**
  6042. * Creates a scaling matrix
  6043. * @param x defines the scale factor on X axis
  6044. * @param y defines the scale factor on Y axis
  6045. * @param z defines the scale factor on Z axis
  6046. * @returns the new matrix
  6047. */
  6048. Matrix.Scaling = function (x, y, z) {
  6049. var result = Matrix.Zero();
  6050. Matrix.ScalingToRef(x, y, z, result);
  6051. return result;
  6052. };
  6053. /**
  6054. * Creates a scaling matrix and stores it in a given matrix
  6055. * @param x defines the scale factor on X axis
  6056. * @param y defines the scale factor on Y axis
  6057. * @param z defines the scale factor on Z axis
  6058. * @param result defines the target matrix
  6059. */
  6060. Matrix.ScalingToRef = function (x, y, z, result) {
  6061. result.m[0] = x;
  6062. result.m[1] = 0.0;
  6063. result.m[2] = 0.0;
  6064. result.m[3] = 0.0;
  6065. result.m[4] = 0.0;
  6066. result.m[5] = y;
  6067. result.m[6] = 0.0;
  6068. result.m[7] = 0.0;
  6069. result.m[8] = 0.0;
  6070. result.m[9] = 0.0;
  6071. result.m[10] = z;
  6072. result.m[11] = 0.0;
  6073. result.m[12] = 0.0;
  6074. result.m[13] = 0.0;
  6075. result.m[14] = 0.0;
  6076. result.m[15] = 1.0;
  6077. result._markAsUpdated();
  6078. };
  6079. /**
  6080. * Creates a translation matrix
  6081. * @param x defines the translation on X axis
  6082. * @param y defines the translation on Y axis
  6083. * @param z defines the translationon Z axis
  6084. * @returns the new matrix
  6085. */
  6086. Matrix.Translation = function (x, y, z) {
  6087. var result = Matrix.Identity();
  6088. Matrix.TranslationToRef(x, y, z, result);
  6089. return result;
  6090. };
  6091. /**
  6092. * Creates a translation matrix and stores it in a given matrix
  6093. * @param x defines the translation on X axis
  6094. * @param y defines the translation on Y axis
  6095. * @param z defines the translationon Z axis
  6096. * @param result defines the target matrix
  6097. */
  6098. Matrix.TranslationToRef = function (x, y, z, result) {
  6099. 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);
  6100. };
  6101. /**
  6102. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6103. * @param startValue defines the start value
  6104. * @param endValue defines the end value
  6105. * @param gradient defines the gradient factor
  6106. * @returns the new matrix
  6107. */
  6108. Matrix.Lerp = function (startValue, endValue, gradient) {
  6109. var result = Matrix.Zero();
  6110. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6111. return result;
  6112. };
  6113. /**
  6114. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6115. * @param startValue defines the start value
  6116. * @param endValue defines the end value
  6117. * @param gradient defines the gradient factor
  6118. * @param result defines the Matrix object where to store data
  6119. */
  6120. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6121. for (var index = 0; index < 16; index++) {
  6122. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6123. }
  6124. result._markAsUpdated();
  6125. };
  6126. /**
  6127. * Builds a new matrix whose values are computed by:
  6128. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6129. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6130. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6131. * @param startValue defines the first matrix
  6132. * @param endValue defines the second matrix
  6133. * @param gradient defines the gradient between the two matrices
  6134. * @returns the new matrix
  6135. */
  6136. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6137. var result = Matrix.Zero();
  6138. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6139. return result;
  6140. };
  6141. /**
  6142. * Update a matrix to values which are computed by:
  6143. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6144. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6145. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6146. * @param startValue defines the first matrix
  6147. * @param endValue defines the second matrix
  6148. * @param gradient defines the gradient between the two matrices
  6149. * @param result defines the target matrix
  6150. */
  6151. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6152. var startScale = MathTmp.Vector3[0];
  6153. var startRotation = MathTmp.Quaternion[0];
  6154. var startTranslation = MathTmp.Vector3[1];
  6155. startValue.decompose(startScale, startRotation, startTranslation);
  6156. var endScale = MathTmp.Vector3[2];
  6157. var endRotation = MathTmp.Quaternion[1];
  6158. var endTranslation = MathTmp.Vector3[3];
  6159. endValue.decompose(endScale, endRotation, endTranslation);
  6160. var resultScale = MathTmp.Vector3[4];
  6161. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6162. var resultRotation = MathTmp.Quaternion[2];
  6163. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6164. var resultTranslation = MathTmp.Vector3[5];
  6165. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6166. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6167. };
  6168. /**
  6169. * 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"
  6170. * This function works in left handed mode
  6171. * @param eye defines the final position of the entity
  6172. * @param target defines where the entity should look at
  6173. * @param up defines the up vector for the entity
  6174. * @returns the new matrix
  6175. */
  6176. Matrix.LookAtLH = function (eye, target, up) {
  6177. var result = Matrix.Zero();
  6178. Matrix.LookAtLHToRef(eye, target, up, result);
  6179. return result;
  6180. };
  6181. /**
  6182. * 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".
  6183. * This function works in left handed mode
  6184. * @param eye defines the final position of the entity
  6185. * @param target defines where the entity should look at
  6186. * @param up defines the up vector for the entity
  6187. * @param result defines the target matrix
  6188. */
  6189. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6190. // Z axis
  6191. target.subtractToRef(eye, this._zAxis);
  6192. this._zAxis.normalize();
  6193. // X axis
  6194. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6195. if (this._xAxis.lengthSquared() === 0) {
  6196. this._xAxis.x = 1.0;
  6197. }
  6198. else {
  6199. this._xAxis.normalize();
  6200. }
  6201. // Y axis
  6202. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6203. this._yAxis.normalize();
  6204. // Eye angles
  6205. var ex = -Vector3.Dot(this._xAxis, eye);
  6206. var ey = -Vector3.Dot(this._yAxis, eye);
  6207. var ez = -Vector3.Dot(this._zAxis, eye);
  6208. 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);
  6209. };
  6210. /**
  6211. * 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"
  6212. * This function works in right handed mode
  6213. * @param eye defines the final position of the entity
  6214. * @param target defines where the entity should look at
  6215. * @param up defines the up vector for the entity
  6216. * @returns the new matrix
  6217. */
  6218. Matrix.LookAtRH = function (eye, target, up) {
  6219. var result = Matrix.Zero();
  6220. Matrix.LookAtRHToRef(eye, target, up, result);
  6221. return result;
  6222. };
  6223. /**
  6224. * 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".
  6225. * This function works in right handed mode
  6226. * @param eye defines the final position of the entity
  6227. * @param target defines where the entity should look at
  6228. * @param up defines the up vector for the entity
  6229. * @param result defines the target matrix
  6230. */
  6231. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6232. // Z axis
  6233. eye.subtractToRef(target, this._zAxis);
  6234. this._zAxis.normalize();
  6235. // X axis
  6236. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6237. if (this._xAxis.lengthSquared() === 0) {
  6238. this._xAxis.x = 1.0;
  6239. }
  6240. else {
  6241. this._xAxis.normalize();
  6242. }
  6243. // Y axis
  6244. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6245. this._yAxis.normalize();
  6246. // Eye angles
  6247. var ex = -Vector3.Dot(this._xAxis, eye);
  6248. var ey = -Vector3.Dot(this._yAxis, eye);
  6249. var ez = -Vector3.Dot(this._zAxis, eye);
  6250. 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);
  6251. };
  6252. /**
  6253. * Create a left-handed orthographic projection matrix
  6254. * @param width defines the viewport width
  6255. * @param height defines the viewport height
  6256. * @param znear defines the near clip plane
  6257. * @param zfar defines the far clip plane
  6258. * @returns a new matrix as a left-handed orthographic projection matrix
  6259. */
  6260. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6261. var matrix = Matrix.Zero();
  6262. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6263. return matrix;
  6264. };
  6265. /**
  6266. * Store a left-handed orthographic projection to a given matrix
  6267. * @param width defines the viewport width
  6268. * @param height defines the viewport height
  6269. * @param znear defines the near clip plane
  6270. * @param zfar defines the far clip plane
  6271. * @param result defines the target matrix
  6272. */
  6273. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6274. var n = znear;
  6275. var f = zfar;
  6276. var a = 2.0 / width;
  6277. var b = 2.0 / height;
  6278. var c = 2.0 / (f - n);
  6279. var d = -(f + n) / (f - n);
  6280. 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);
  6281. };
  6282. /**
  6283. * Create a left-handed orthographic projection matrix
  6284. * @param left defines the viewport left coordinate
  6285. * @param right defines the viewport right coordinate
  6286. * @param bottom defines the viewport bottom coordinate
  6287. * @param top defines the viewport top coordinate
  6288. * @param znear defines the near clip plane
  6289. * @param zfar defines the far clip plane
  6290. * @returns a new matrix as a left-handed orthographic projection matrix
  6291. */
  6292. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6293. var matrix = Matrix.Zero();
  6294. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6295. return matrix;
  6296. };
  6297. /**
  6298. * Stores a left-handed orthographic projection into a given matrix
  6299. * @param left defines the viewport left coordinate
  6300. * @param right defines the viewport right coordinate
  6301. * @param bottom defines the viewport bottom coordinate
  6302. * @param top defines the viewport top coordinate
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @param result defines the target matrix
  6306. */
  6307. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6308. var n = znear;
  6309. var f = zfar;
  6310. var a = 2.0 / (right - left);
  6311. var b = 2.0 / (top - bottom);
  6312. var c = 2.0 / (f - n);
  6313. var d = -(f + n) / (f - n);
  6314. var i0 = (left + right) / (left - right);
  6315. var i1 = (top + bottom) / (bottom - top);
  6316. 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);
  6317. };
  6318. /**
  6319. * Creates a right-handed orthographic projection matrix
  6320. * @param left defines the viewport left coordinate
  6321. * @param right defines the viewport right coordinate
  6322. * @param bottom defines the viewport bottom coordinate
  6323. * @param top defines the viewport top coordinate
  6324. * @param znear defines the near clip plane
  6325. * @param zfar defines the far clip plane
  6326. * @returns a new matrix as a right-handed orthographic projection matrix
  6327. */
  6328. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6329. var matrix = Matrix.Zero();
  6330. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6331. return matrix;
  6332. };
  6333. /**
  6334. * Stores a right-handed orthographic projection into a given matrix
  6335. * @param left defines the viewport left coordinate
  6336. * @param right defines the viewport right coordinate
  6337. * @param bottom defines the viewport bottom coordinate
  6338. * @param top defines the viewport top coordinate
  6339. * @param znear defines the near clip plane
  6340. * @param zfar defines the far clip plane
  6341. * @param result defines the target matrix
  6342. */
  6343. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6344. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6345. result.m[10] *= -1.0;
  6346. };
  6347. /**
  6348. * Creates a left-handed perspective projection matrix
  6349. * @param width defines the viewport width
  6350. * @param height defines the viewport height
  6351. * @param znear defines the near clip plane
  6352. * @param zfar defines the far clip plane
  6353. * @returns a new matrix as a left-handed perspective projection matrix
  6354. */
  6355. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6356. var matrix = Matrix.Zero();
  6357. var n = znear;
  6358. var f = zfar;
  6359. var a = 2.0 * n / width;
  6360. var b = 2.0 * n / height;
  6361. var c = (f + n) / (f - n);
  6362. var d = -2.0 * f * n / (f - n);
  6363. 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);
  6364. return matrix;
  6365. };
  6366. /**
  6367. * Creates a left-handed perspective projection matrix
  6368. * @param fov defines the horizontal field of view
  6369. * @param aspect defines the aspect ratio
  6370. * @param znear defines the near clip plane
  6371. * @param zfar defines the far clip plane
  6372. * @returns a new matrix as a left-handed perspective projection matrix
  6373. */
  6374. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6375. var matrix = Matrix.Zero();
  6376. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6377. return matrix;
  6378. };
  6379. /**
  6380. * Stores a left-handed perspective projection into a given matrix
  6381. * @param fov defines the horizontal field of view
  6382. * @param aspect defines the aspect ratio
  6383. * @param znear defines the near clip plane
  6384. * @param zfar defines the far clip plane
  6385. * @param result defines the target matrix
  6386. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6387. */
  6388. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6389. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6390. var n = znear;
  6391. var f = zfar;
  6392. var t = 1.0 / (Math.tan(fov * 0.5));
  6393. var a = isVerticalFovFixed ? (t / aspect) : t;
  6394. var b = isVerticalFovFixed ? t : (t * aspect);
  6395. var c = (f + n) / (f - n);
  6396. var d = -2.0 * f * n / (f - n);
  6397. 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);
  6398. };
  6399. /**
  6400. * Creates a right-handed perspective projection matrix
  6401. * @param fov defines the horizontal field of view
  6402. * @param aspect defines the aspect ratio
  6403. * @param znear defines the near clip plane
  6404. * @param zfar defines the far clip plane
  6405. * @returns a new matrix as a right-handed perspective projection matrix
  6406. */
  6407. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6408. var matrix = Matrix.Zero();
  6409. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6410. return matrix;
  6411. };
  6412. /**
  6413. * Stores a right-handed perspective projection into a given matrix
  6414. * @param fov defines the horizontal field of view
  6415. * @param aspect defines the aspect ratio
  6416. * @param znear defines the near clip plane
  6417. * @param zfar defines the far clip plane
  6418. * @param result defines the target matrix
  6419. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6420. */
  6421. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6422. //alternatively this could be expressed as:
  6423. // m = PerspectiveFovLHToRef
  6424. // m[10] *= -1.0;
  6425. // m[11] *= -1.0;
  6426. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6427. var n = znear;
  6428. var f = zfar;
  6429. var t = 1.0 / (Math.tan(fov * 0.5));
  6430. var a = isVerticalFovFixed ? (t / aspect) : t;
  6431. var b = isVerticalFovFixed ? t : (t * aspect);
  6432. var c = -(f + n) / (f - n);
  6433. var d = -2 * f * n / (f - n);
  6434. 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);
  6435. };
  6436. /**
  6437. * Stores a perspective projection for WebVR info a given matrix
  6438. * @param fov defines the field of view
  6439. * @param znear defines the near clip plane
  6440. * @param zfar defines the far clip plane
  6441. * @param result defines the target matrix
  6442. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6443. */
  6444. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6445. if (rightHanded === void 0) { rightHanded = false; }
  6446. var rightHandedFactor = rightHanded ? -1 : 1;
  6447. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6448. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6449. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6450. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6451. var xScale = 2.0 / (leftTan + rightTan);
  6452. var yScale = 2.0 / (upTan + downTan);
  6453. result.m[0] = xScale;
  6454. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6455. result.m[5] = yScale;
  6456. result.m[6] = result.m[7] = 0.0;
  6457. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6458. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6459. result.m[10] = -zfar / (znear - zfar);
  6460. result.m[11] = 1.0 * rightHandedFactor;
  6461. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6462. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6463. result._markAsUpdated();
  6464. };
  6465. /**
  6466. * Computes a complete transformation matrix
  6467. * @param viewport defines the viewport to use
  6468. * @param world defines the world matrix
  6469. * @param view defines the view matrix
  6470. * @param projection defines the projection matrix
  6471. * @param zmin defines the near clip plane
  6472. * @param zmax defines the far clip plane
  6473. * @returns the transformation matrix
  6474. */
  6475. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6476. var cw = viewport.width;
  6477. var ch = viewport.height;
  6478. var cx = viewport.x;
  6479. var cy = viewport.y;
  6480. 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);
  6481. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6482. };
  6483. /**
  6484. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6485. * @param matrix defines the matrix to use
  6486. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6487. */
  6488. Matrix.GetAsMatrix2x2 = function (matrix) {
  6489. return new Float32Array([
  6490. matrix.m[0], matrix.m[1],
  6491. matrix.m[4], matrix.m[5]
  6492. ]);
  6493. };
  6494. /**
  6495. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6496. * @param matrix defines the matrix to use
  6497. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6498. */
  6499. Matrix.GetAsMatrix3x3 = function (matrix) {
  6500. return new Float32Array([
  6501. matrix.m[0], matrix.m[1], matrix.m[2],
  6502. matrix.m[4], matrix.m[5], matrix.m[6],
  6503. matrix.m[8], matrix.m[9], matrix.m[10]
  6504. ]);
  6505. };
  6506. /**
  6507. * Compute the transpose of a given matrix
  6508. * @param matrix defines the matrix to transpose
  6509. * @returns the new matrix
  6510. */
  6511. Matrix.Transpose = function (matrix) {
  6512. var result = new Matrix();
  6513. Matrix.TransposeToRef(matrix, result);
  6514. return result;
  6515. };
  6516. /**
  6517. * Compute the transpose of a matrix and store it in a target matrix
  6518. * @param matrix defines the matrix to transpose
  6519. * @param result defines the target matrix
  6520. */
  6521. Matrix.TransposeToRef = function (matrix, result) {
  6522. result.m[0] = matrix.m[0];
  6523. result.m[1] = matrix.m[4];
  6524. result.m[2] = matrix.m[8];
  6525. result.m[3] = matrix.m[12];
  6526. result.m[4] = matrix.m[1];
  6527. result.m[5] = matrix.m[5];
  6528. result.m[6] = matrix.m[9];
  6529. result.m[7] = matrix.m[13];
  6530. result.m[8] = matrix.m[2];
  6531. result.m[9] = matrix.m[6];
  6532. result.m[10] = matrix.m[10];
  6533. result.m[11] = matrix.m[14];
  6534. result.m[12] = matrix.m[3];
  6535. result.m[13] = matrix.m[7];
  6536. result.m[14] = matrix.m[11];
  6537. result.m[15] = matrix.m[15];
  6538. };
  6539. /**
  6540. * Computes a reflection matrix from a plane
  6541. * @param plane defines the reflection plane
  6542. * @returns a new matrix
  6543. */
  6544. Matrix.Reflection = function (plane) {
  6545. var matrix = new Matrix();
  6546. Matrix.ReflectionToRef(plane, matrix);
  6547. return matrix;
  6548. };
  6549. /**
  6550. * Computes a reflection matrix from a plane
  6551. * @param plane defines the reflection plane
  6552. * @param result defines the target matrix
  6553. */
  6554. Matrix.ReflectionToRef = function (plane, result) {
  6555. plane.normalize();
  6556. var x = plane.normal.x;
  6557. var y = plane.normal.y;
  6558. var z = plane.normal.z;
  6559. var temp = -2 * x;
  6560. var temp2 = -2 * y;
  6561. var temp3 = -2 * z;
  6562. result.m[0] = (temp * x) + 1;
  6563. result.m[1] = temp2 * x;
  6564. result.m[2] = temp3 * x;
  6565. result.m[3] = 0.0;
  6566. result.m[4] = temp * y;
  6567. result.m[5] = (temp2 * y) + 1;
  6568. result.m[6] = temp3 * y;
  6569. result.m[7] = 0.0;
  6570. result.m[8] = temp * z;
  6571. result.m[9] = temp2 * z;
  6572. result.m[10] = (temp3 * z) + 1;
  6573. result.m[11] = 0.0;
  6574. result.m[12] = temp * plane.d;
  6575. result.m[13] = temp2 * plane.d;
  6576. result.m[14] = temp3 * plane.d;
  6577. result.m[15] = 1.0;
  6578. result._markAsUpdated();
  6579. };
  6580. /**
  6581. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6582. * @param xaxis defines the value of the 1st axis
  6583. * @param yaxis defines the value of the 2nd axis
  6584. * @param zaxis defines the value of the 3rd axis
  6585. * @param result defines the target matrix
  6586. */
  6587. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6588. result.m[0] = xaxis.x;
  6589. result.m[1] = xaxis.y;
  6590. result.m[2] = xaxis.z;
  6591. result.m[3] = 0.0;
  6592. result.m[4] = yaxis.x;
  6593. result.m[5] = yaxis.y;
  6594. result.m[6] = yaxis.z;
  6595. result.m[7] = 0.0;
  6596. result.m[8] = zaxis.x;
  6597. result.m[9] = zaxis.y;
  6598. result.m[10] = zaxis.z;
  6599. result.m[11] = 0.0;
  6600. result.m[12] = 0.0;
  6601. result.m[13] = 0.0;
  6602. result.m[14] = 0.0;
  6603. result.m[15] = 1.0;
  6604. result._markAsUpdated();
  6605. };
  6606. /**
  6607. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6608. * @param quat defines the quaternion to use
  6609. * @param result defines the target matrix
  6610. */
  6611. Matrix.FromQuaternionToRef = function (quat, result) {
  6612. var xx = quat.x * quat.x;
  6613. var yy = quat.y * quat.y;
  6614. var zz = quat.z * quat.z;
  6615. var xy = quat.x * quat.y;
  6616. var zw = quat.z * quat.w;
  6617. var zx = quat.z * quat.x;
  6618. var yw = quat.y * quat.w;
  6619. var yz = quat.y * quat.z;
  6620. var xw = quat.x * quat.w;
  6621. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6622. result.m[1] = 2.0 * (xy + zw);
  6623. result.m[2] = 2.0 * (zx - yw);
  6624. result.m[3] = 0.0;
  6625. result.m[4] = 2.0 * (xy - zw);
  6626. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6627. result.m[6] = 2.0 * (yz + xw);
  6628. result.m[7] = 0.0;
  6629. result.m[8] = 2.0 * (zx + yw);
  6630. result.m[9] = 2.0 * (yz - xw);
  6631. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6632. result.m[11] = 0.0;
  6633. result.m[12] = 0.0;
  6634. result.m[13] = 0.0;
  6635. result.m[14] = 0.0;
  6636. result.m[15] = 1.0;
  6637. result._markAsUpdated();
  6638. };
  6639. Matrix._tempQuaternion = new Quaternion();
  6640. Matrix._xAxis = Vector3.Zero();
  6641. Matrix._yAxis = Vector3.Zero();
  6642. Matrix._zAxis = Vector3.Zero();
  6643. Matrix._updateFlagSeed = 0;
  6644. Matrix._identityReadOnly = Matrix.Identity();
  6645. return Matrix;
  6646. }());
  6647. BABYLON.Matrix = Matrix;
  6648. var Plane = /** @class */ (function () {
  6649. /**
  6650. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6651. */
  6652. function Plane(a, b, c, d) {
  6653. this.normal = new Vector3(a, b, c);
  6654. this.d = d;
  6655. }
  6656. /**
  6657. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6658. */
  6659. Plane.prototype.asArray = function () {
  6660. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6661. };
  6662. // Methods
  6663. /**
  6664. * Returns a new plane copied from the current Plane.
  6665. */
  6666. Plane.prototype.clone = function () {
  6667. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6668. };
  6669. /**
  6670. * Returns the string "Plane".
  6671. */
  6672. Plane.prototype.getClassName = function () {
  6673. return "Plane";
  6674. };
  6675. /**
  6676. * Returns the Plane hash code.
  6677. */
  6678. Plane.prototype.getHashCode = function () {
  6679. var hash = this.normal.getHashCode();
  6680. hash = (hash * 397) ^ (this.d || 0);
  6681. return hash;
  6682. };
  6683. /**
  6684. * Normalize the current Plane in place.
  6685. * Returns the updated Plane.
  6686. */
  6687. Plane.prototype.normalize = function () {
  6688. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6689. var magnitude = 0.0;
  6690. if (norm !== 0) {
  6691. magnitude = 1.0 / norm;
  6692. }
  6693. this.normal.x *= magnitude;
  6694. this.normal.y *= magnitude;
  6695. this.normal.z *= magnitude;
  6696. this.d *= magnitude;
  6697. return this;
  6698. };
  6699. /**
  6700. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6701. */
  6702. Plane.prototype.transform = function (transformation) {
  6703. var transposedMatrix = Matrix.Transpose(transformation);
  6704. var x = this.normal.x;
  6705. var y = this.normal.y;
  6706. var z = this.normal.z;
  6707. var d = this.d;
  6708. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6709. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6710. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6711. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6712. return new Plane(normalX, normalY, normalZ, finalD);
  6713. };
  6714. /**
  6715. * Returns the dot product (float) of the point coordinates and the plane normal.
  6716. */
  6717. Plane.prototype.dotCoordinate = function (point) {
  6718. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6719. };
  6720. /**
  6721. * Updates the current Plane from the plane defined by the three given points.
  6722. * Returns the updated Plane.
  6723. */
  6724. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6725. var x1 = point2.x - point1.x;
  6726. var y1 = point2.y - point1.y;
  6727. var z1 = point2.z - point1.z;
  6728. var x2 = point3.x - point1.x;
  6729. var y2 = point3.y - point1.y;
  6730. var z2 = point3.z - point1.z;
  6731. var yz = (y1 * z2) - (z1 * y2);
  6732. var xz = (z1 * x2) - (x1 * z2);
  6733. var xy = (x1 * y2) - (y1 * x2);
  6734. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6735. var invPyth;
  6736. if (pyth !== 0) {
  6737. invPyth = 1.0 / pyth;
  6738. }
  6739. else {
  6740. invPyth = 0.0;
  6741. }
  6742. this.normal.x = yz * invPyth;
  6743. this.normal.y = xz * invPyth;
  6744. this.normal.z = xy * invPyth;
  6745. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6746. return this;
  6747. };
  6748. /**
  6749. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6750. */
  6751. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6752. var dot = Vector3.Dot(this.normal, direction);
  6753. return (dot <= epsilon);
  6754. };
  6755. /**
  6756. * Returns the signed distance (float) from the given point to the Plane.
  6757. */
  6758. Plane.prototype.signedDistanceTo = function (point) {
  6759. return Vector3.Dot(point, this.normal) + this.d;
  6760. };
  6761. // Statics
  6762. /**
  6763. * Returns a new Plane from the given array.
  6764. */
  6765. Plane.FromArray = function (array) {
  6766. return new Plane(array[0], array[1], array[2], array[3]);
  6767. };
  6768. /**
  6769. * Returns a new Plane defined by the three given points.
  6770. */
  6771. Plane.FromPoints = function (point1, point2, point3) {
  6772. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6773. result.copyFromPoints(point1, point2, point3);
  6774. return result;
  6775. };
  6776. /**
  6777. * Returns a new Plane the normal vector to this plane at the given origin point.
  6778. * Note : the vector "normal" is updated because normalized.
  6779. */
  6780. Plane.FromPositionAndNormal = function (origin, normal) {
  6781. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6782. normal.normalize();
  6783. result.normal = normal;
  6784. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6785. return result;
  6786. };
  6787. /**
  6788. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6789. */
  6790. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6791. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6792. return Vector3.Dot(point, normal) + d;
  6793. };
  6794. return Plane;
  6795. }());
  6796. BABYLON.Plane = Plane;
  6797. var Viewport = /** @class */ (function () {
  6798. /**
  6799. * Creates a Viewport object located at (x, y) and sized (width, height).
  6800. */
  6801. function Viewport(x, y, width, height) {
  6802. this.x = x;
  6803. this.y = y;
  6804. this.width = width;
  6805. this.height = height;
  6806. }
  6807. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6808. if (renderWidthOrEngine.getRenderWidth) {
  6809. var engine = renderWidthOrEngine;
  6810. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6811. }
  6812. var renderWidth = renderWidthOrEngine;
  6813. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6814. };
  6815. /**
  6816. * Returns a new Viewport copied from the current one.
  6817. */
  6818. Viewport.prototype.clone = function () {
  6819. return new Viewport(this.x, this.y, this.width, this.height);
  6820. };
  6821. return Viewport;
  6822. }());
  6823. BABYLON.Viewport = Viewport;
  6824. var Frustum = /** @class */ (function () {
  6825. function Frustum() {
  6826. }
  6827. /**
  6828. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6829. */
  6830. Frustum.GetPlanes = function (transform) {
  6831. var frustumPlanes = [];
  6832. for (var index = 0; index < 6; index++) {
  6833. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6834. }
  6835. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6836. return frustumPlanes;
  6837. };
  6838. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6840. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6841. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6842. frustumPlane.d = transform.m[15] + transform.m[14];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6847. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6848. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6849. frustumPlane.d = transform.m[15] - transform.m[14];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6854. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6855. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6856. frustumPlane.d = transform.m[15] + transform.m[12];
  6857. frustumPlane.normalize();
  6858. };
  6859. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6860. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6861. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6862. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6863. frustumPlane.d = transform.m[15] - transform.m[12];
  6864. frustumPlane.normalize();
  6865. };
  6866. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6867. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6868. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6869. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6870. frustumPlane.d = transform.m[15] - transform.m[13];
  6871. frustumPlane.normalize();
  6872. };
  6873. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6874. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6875. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6876. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6877. frustumPlane.d = transform.m[15] + transform.m[13];
  6878. frustumPlane.normalize();
  6879. };
  6880. /**
  6881. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6882. */
  6883. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6884. // Near
  6885. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6886. // Far
  6887. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6888. // Left
  6889. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6890. // Right
  6891. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6892. // Top
  6893. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6894. // Bottom
  6895. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6896. };
  6897. return Frustum;
  6898. }());
  6899. BABYLON.Frustum = Frustum;
  6900. /** Defines supported spaces */
  6901. var Space;
  6902. (function (Space) {
  6903. /** Local (object) space */
  6904. Space[Space["LOCAL"] = 0] = "LOCAL";
  6905. /** World space */
  6906. Space[Space["WORLD"] = 1] = "WORLD";
  6907. /** Bone space */
  6908. Space[Space["BONE"] = 2] = "BONE";
  6909. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6910. /** Defines the 3 main axes */
  6911. var Axis = /** @class */ (function () {
  6912. function Axis() {
  6913. }
  6914. /** X axis */
  6915. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6916. /** Y axis */
  6917. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6918. /** Z axis */
  6919. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6920. return Axis;
  6921. }());
  6922. BABYLON.Axis = Axis;
  6923. ;
  6924. var BezierCurve = /** @class */ (function () {
  6925. function BezierCurve() {
  6926. }
  6927. /**
  6928. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6929. */
  6930. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6931. // Extract X (which is equal to time here)
  6932. var f0 = 1 - 3 * x2 + 3 * x1;
  6933. var f1 = 3 * x2 - 6 * x1;
  6934. var f2 = 3 * x1;
  6935. var refinedT = t;
  6936. for (var i = 0; i < 5; i++) {
  6937. var refinedT2 = refinedT * refinedT;
  6938. var refinedT3 = refinedT2 * refinedT;
  6939. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6940. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6941. refinedT -= (x - t) * slope;
  6942. refinedT = Math.min(1, Math.max(0, refinedT));
  6943. }
  6944. // Resolve cubic bezier for the given x
  6945. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6946. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6947. Math.pow(refinedT, 3);
  6948. };
  6949. return BezierCurve;
  6950. }());
  6951. BABYLON.BezierCurve = BezierCurve;
  6952. /**
  6953. * Defines potential orientation for back face culling
  6954. */
  6955. var Orientation;
  6956. (function (Orientation) {
  6957. /**
  6958. * Clockwise
  6959. */
  6960. Orientation[Orientation["CW"] = 0] = "CW";
  6961. /** Counter clockwise */
  6962. Orientation[Orientation["CCW"] = 1] = "CCW";
  6963. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6964. /**
  6965. * Defines angle representation
  6966. */
  6967. var Angle = /** @class */ (function () {
  6968. /**
  6969. * Creates an Angle object of "radians" radians (float).
  6970. */
  6971. function Angle(radians) {
  6972. this._radians = radians;
  6973. if (this._radians < 0.0)
  6974. this._radians += (2.0 * Math.PI);
  6975. }
  6976. /**
  6977. * Get value in degrees
  6978. * @returns the Angle value in degrees (float)
  6979. */
  6980. Angle.prototype.degrees = function () {
  6981. return this._radians * 180.0 / Math.PI;
  6982. };
  6983. /**
  6984. * Get value in radians
  6985. * @returns the Angle value in radians (float)
  6986. */
  6987. Angle.prototype.radians = function () {
  6988. return this._radians;
  6989. };
  6990. /**
  6991. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6992. * @param a defines first vector
  6993. * @param b defines second vector
  6994. * @returns a new Angle
  6995. */
  6996. Angle.BetweenTwoPoints = function (a, b) {
  6997. var delta = b.subtract(a);
  6998. var theta = Math.atan2(delta.y, delta.x);
  6999. return new Angle(theta);
  7000. };
  7001. /**
  7002. * Gets a new Angle object from the given float in radians
  7003. * @param radians defines the angle value in radians
  7004. * @returns a new Angle
  7005. */
  7006. Angle.FromRadians = function (radians) {
  7007. return new Angle(radians);
  7008. };
  7009. /**
  7010. * Gets a new Angle object from the given float in degrees
  7011. * @param degrees defines the angle value in degrees
  7012. * @returns a new Angle
  7013. */
  7014. Angle.FromDegrees = function (degrees) {
  7015. return new Angle(degrees * Math.PI / 180.0);
  7016. };
  7017. return Angle;
  7018. }());
  7019. BABYLON.Angle = Angle;
  7020. var Arc2 = /** @class */ (function () {
  7021. /**
  7022. * Creates an Arc object from the three given points : start, middle and end.
  7023. */
  7024. function Arc2(startPoint, midPoint, endPoint) {
  7025. this.startPoint = startPoint;
  7026. this.midPoint = midPoint;
  7027. this.endPoint = endPoint;
  7028. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7029. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7030. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7031. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7032. 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);
  7033. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7034. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7035. var a1 = this.startAngle.degrees();
  7036. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7037. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7038. // angles correction
  7039. if (a2 - a1 > +180.0)
  7040. a2 -= 360.0;
  7041. if (a2 - a1 < -180.0)
  7042. a2 += 360.0;
  7043. if (a3 - a2 > +180.0)
  7044. a3 -= 360.0;
  7045. if (a3 - a2 < -180.0)
  7046. a3 += 360.0;
  7047. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7048. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7049. }
  7050. return Arc2;
  7051. }());
  7052. BABYLON.Arc2 = Arc2;
  7053. var Path2 = /** @class */ (function () {
  7054. /**
  7055. * Creates a Path2 object from the starting 2D coordinates x and y.
  7056. */
  7057. function Path2(x, y) {
  7058. this._points = new Array();
  7059. this._length = 0.0;
  7060. this.closed = false;
  7061. this._points.push(new Vector2(x, y));
  7062. }
  7063. /**
  7064. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7065. * Returns the updated Path2.
  7066. */
  7067. Path2.prototype.addLineTo = function (x, y) {
  7068. if (this.closed) {
  7069. return this;
  7070. }
  7071. var newPoint = new Vector2(x, y);
  7072. var previousPoint = this._points[this._points.length - 1];
  7073. this._points.push(newPoint);
  7074. this._length += newPoint.subtract(previousPoint).length();
  7075. return this;
  7076. };
  7077. /**
  7078. * 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.
  7079. * Returns the updated Path2.
  7080. */
  7081. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7082. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7083. if (this.closed) {
  7084. return this;
  7085. }
  7086. var startPoint = this._points[this._points.length - 1];
  7087. var midPoint = new Vector2(midX, midY);
  7088. var endPoint = new Vector2(endX, endY);
  7089. var arc = new Arc2(startPoint, midPoint, endPoint);
  7090. var increment = arc.angle.radians() / numberOfSegments;
  7091. if (arc.orientation === Orientation.CW)
  7092. increment *= -1;
  7093. var currentAngle = arc.startAngle.radians() + increment;
  7094. for (var i = 0; i < numberOfSegments; i++) {
  7095. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7096. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7097. this.addLineTo(x, y);
  7098. currentAngle += increment;
  7099. }
  7100. return this;
  7101. };
  7102. /**
  7103. * Closes the Path2.
  7104. * Returns the Path2.
  7105. */
  7106. Path2.prototype.close = function () {
  7107. this.closed = true;
  7108. return this;
  7109. };
  7110. /**
  7111. * Returns the Path2 total length (float).
  7112. */
  7113. Path2.prototype.length = function () {
  7114. var result = this._length;
  7115. if (!this.closed) {
  7116. var lastPoint = this._points[this._points.length - 1];
  7117. var firstPoint = this._points[0];
  7118. result += (firstPoint.subtract(lastPoint).length());
  7119. }
  7120. return result;
  7121. };
  7122. /**
  7123. * Returns the Path2 internal array of points.
  7124. */
  7125. Path2.prototype.getPoints = function () {
  7126. return this._points;
  7127. };
  7128. /**
  7129. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7130. */
  7131. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7132. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7133. return Vector2.Zero();
  7134. }
  7135. var lengthPosition = normalizedLengthPosition * this.length();
  7136. var previousOffset = 0;
  7137. for (var i = 0; i < this._points.length; i++) {
  7138. var j = (i + 1) % this._points.length;
  7139. var a = this._points[i];
  7140. var b = this._points[j];
  7141. var bToA = b.subtract(a);
  7142. var nextOffset = (bToA.length() + previousOffset);
  7143. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7144. var dir = bToA.normalize();
  7145. var localOffset = lengthPosition - previousOffset;
  7146. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7147. }
  7148. previousOffset = nextOffset;
  7149. }
  7150. return Vector2.Zero();
  7151. };
  7152. /**
  7153. * Returns a new Path2 starting at the coordinates (x, y).
  7154. */
  7155. Path2.StartingAt = function (x, y) {
  7156. return new Path2(x, y);
  7157. };
  7158. return Path2;
  7159. }());
  7160. BABYLON.Path2 = Path2;
  7161. var Path3D = /** @class */ (function () {
  7162. /**
  7163. * new Path3D(path, normal, raw)
  7164. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7165. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7166. * path : an array of Vector3, the curve axis of the Path3D
  7167. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7168. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7169. */
  7170. function Path3D(path, firstNormal, raw) {
  7171. if (firstNormal === void 0) { firstNormal = null; }
  7172. this.path = path;
  7173. this._curve = new Array();
  7174. this._distances = new Array();
  7175. this._tangents = new Array();
  7176. this._normals = new Array();
  7177. this._binormals = new Array();
  7178. for (var p = 0; p < path.length; p++) {
  7179. this._curve[p] = path[p].clone(); // hard copy
  7180. }
  7181. this._raw = raw || false;
  7182. this._compute(firstNormal);
  7183. }
  7184. /**
  7185. * Returns the Path3D array of successive Vector3 designing its curve.
  7186. */
  7187. Path3D.prototype.getCurve = function () {
  7188. return this._curve;
  7189. };
  7190. /**
  7191. * Returns an array populated with tangent vectors on each Path3D curve point.
  7192. */
  7193. Path3D.prototype.getTangents = function () {
  7194. return this._tangents;
  7195. };
  7196. /**
  7197. * Returns an array populated with normal vectors on each Path3D curve point.
  7198. */
  7199. Path3D.prototype.getNormals = function () {
  7200. return this._normals;
  7201. };
  7202. /**
  7203. * Returns an array populated with binormal vectors on each Path3D curve point.
  7204. */
  7205. Path3D.prototype.getBinormals = function () {
  7206. return this._binormals;
  7207. };
  7208. /**
  7209. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7210. */
  7211. Path3D.prototype.getDistances = function () {
  7212. return this._distances;
  7213. };
  7214. /**
  7215. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7216. * Returns the same object updated.
  7217. */
  7218. Path3D.prototype.update = function (path, firstNormal) {
  7219. if (firstNormal === void 0) { firstNormal = null; }
  7220. for (var p = 0; p < path.length; p++) {
  7221. this._curve[p].x = path[p].x;
  7222. this._curve[p].y = path[p].y;
  7223. this._curve[p].z = path[p].z;
  7224. }
  7225. this._compute(firstNormal);
  7226. return this;
  7227. };
  7228. // private function compute() : computes tangents, normals and binormals
  7229. Path3D.prototype._compute = function (firstNormal) {
  7230. var l = this._curve.length;
  7231. // first and last tangents
  7232. this._tangents[0] = this._getFirstNonNullVector(0);
  7233. if (!this._raw) {
  7234. this._tangents[0].normalize();
  7235. }
  7236. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7237. if (!this._raw) {
  7238. this._tangents[l - 1].normalize();
  7239. }
  7240. // normals and binormals at first point : arbitrary vector with _normalVector()
  7241. var tg0 = this._tangents[0];
  7242. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7243. this._normals[0] = pp0;
  7244. if (!this._raw) {
  7245. this._normals[0].normalize();
  7246. }
  7247. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7248. if (!this._raw) {
  7249. this._binormals[0].normalize();
  7250. }
  7251. this._distances[0] = 0.0;
  7252. // normals and binormals : next points
  7253. var prev; // previous vector (segment)
  7254. var cur; // current vector (segment)
  7255. var curTang; // current tangent
  7256. // previous normal
  7257. var prevBinor; // previous binormal
  7258. for (var i = 1; i < l; i++) {
  7259. // tangents
  7260. prev = this._getLastNonNullVector(i);
  7261. if (i < l - 1) {
  7262. cur = this._getFirstNonNullVector(i);
  7263. this._tangents[i] = prev.add(cur);
  7264. this._tangents[i].normalize();
  7265. }
  7266. this._distances[i] = this._distances[i - 1] + prev.length();
  7267. // normals and binormals
  7268. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7269. curTang = this._tangents[i];
  7270. prevBinor = this._binormals[i - 1];
  7271. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7272. if (!this._raw) {
  7273. this._normals[i].normalize();
  7274. }
  7275. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7276. if (!this._raw) {
  7277. this._binormals[i].normalize();
  7278. }
  7279. }
  7280. };
  7281. // private function getFirstNonNullVector(index)
  7282. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7283. Path3D.prototype._getFirstNonNullVector = function (index) {
  7284. var i = 1;
  7285. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7286. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7287. i++;
  7288. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7289. }
  7290. return nNVector;
  7291. };
  7292. // private function getLastNonNullVector(index)
  7293. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7294. Path3D.prototype._getLastNonNullVector = function (index) {
  7295. var i = 1;
  7296. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7297. while (nLVector.length() === 0 && index > i + 1) {
  7298. i++;
  7299. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7300. }
  7301. return nLVector;
  7302. };
  7303. // private function normalVector(v0, vt, va) :
  7304. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7305. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7306. Path3D.prototype._normalVector = function (v0, vt, va) {
  7307. var normal0;
  7308. var tgl = vt.length();
  7309. if (tgl === 0.0) {
  7310. tgl = 1.0;
  7311. }
  7312. if (va === undefined || va === null) {
  7313. var point;
  7314. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7315. point = new Vector3(0.0, -1.0, 0.0);
  7316. }
  7317. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7318. point = new Vector3(1.0, 0.0, 0.0);
  7319. }
  7320. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7321. point = new Vector3(0.0, 0.0, 1.0);
  7322. }
  7323. else {
  7324. point = Vector3.Zero();
  7325. }
  7326. normal0 = Vector3.Cross(vt, point);
  7327. }
  7328. else {
  7329. normal0 = Vector3.Cross(vt, va);
  7330. Vector3.CrossToRef(normal0, vt, normal0);
  7331. }
  7332. normal0.normalize();
  7333. return normal0;
  7334. };
  7335. return Path3D;
  7336. }());
  7337. BABYLON.Path3D = Path3D;
  7338. var Curve3 = /** @class */ (function () {
  7339. /**
  7340. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7341. * A Curve3 is designed from a series of successive Vector3.
  7342. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7343. */
  7344. function Curve3(points) {
  7345. this._length = 0.0;
  7346. this._points = points;
  7347. this._length = this._computeLength(points);
  7348. }
  7349. /**
  7350. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7351. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7352. * @param v1 (Vector3) the control point
  7353. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7354. * @param nbPoints (integer) the wanted number of points in the curve
  7355. */
  7356. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7357. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7358. var bez = new Array();
  7359. var equation = function (t, val0, val1, val2) {
  7360. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7361. return res;
  7362. };
  7363. for (var i = 0; i <= nbPoints; i++) {
  7364. 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)));
  7365. }
  7366. return new Curve3(bez);
  7367. };
  7368. /**
  7369. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7370. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7371. * @param v1 (Vector3) the first control point
  7372. * @param v2 (Vector3) the second control point
  7373. * @param v3 (Vector3) the end point of the Cubic Bezier
  7374. * @param nbPoints (integer) the wanted number of points in the curve
  7375. */
  7376. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7377. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7378. var bez = new Array();
  7379. var equation = function (t, val0, val1, val2, val3) {
  7380. 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;
  7381. return res;
  7382. };
  7383. for (var i = 0; i <= nbPoints; i++) {
  7384. 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)));
  7385. }
  7386. return new Curve3(bez);
  7387. };
  7388. /**
  7389. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7390. * @param p1 (Vector3) the origin point of the Hermite Spline
  7391. * @param t1 (Vector3) the tangent vector at the origin point
  7392. * @param p2 (Vector3) the end point of the Hermite Spline
  7393. * @param t2 (Vector3) the tangent vector at the end point
  7394. * @param nbPoints (integer) the wanted number of points in the curve
  7395. */
  7396. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7397. var hermite = new Array();
  7398. var step = 1.0 / nbPoints;
  7399. for (var i = 0; i <= nbPoints; i++) {
  7400. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7401. }
  7402. return new Curve3(hermite);
  7403. };
  7404. /**
  7405. * Returns a Curve3 object along a CatmullRom Spline curve :
  7406. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7407. * @param nbPoints (integer) the wanted number of points between each curve control points
  7408. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7409. */
  7410. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7411. var catmullRom = new Array();
  7412. var step = 1.0 / nbPoints;
  7413. var amount = 0.0;
  7414. if (closed) {
  7415. var pointsCount = points.length;
  7416. for (var i = 0; i < pointsCount; i++) {
  7417. amount = 0;
  7418. for (var c = 0; c < nbPoints; c++) {
  7419. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7420. amount += step;
  7421. }
  7422. }
  7423. catmullRom.push(catmullRom[0]);
  7424. }
  7425. else {
  7426. var totalPoints = new Array();
  7427. totalPoints.push(points[0].clone());
  7428. Array.prototype.push.apply(totalPoints, points);
  7429. totalPoints.push(points[points.length - 1].clone());
  7430. for (var i = 0; i < totalPoints.length - 3; i++) {
  7431. amount = 0;
  7432. for (var c = 0; c < nbPoints; c++) {
  7433. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7434. amount += step;
  7435. }
  7436. }
  7437. i--;
  7438. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7439. }
  7440. return new Curve3(catmullRom);
  7441. };
  7442. /**
  7443. * Returns the Curve3 stored array of successive Vector3
  7444. */
  7445. Curve3.prototype.getPoints = function () {
  7446. return this._points;
  7447. };
  7448. /**
  7449. * Returns the computed length (float) of the curve.
  7450. */
  7451. Curve3.prototype.length = function () {
  7452. return this._length;
  7453. };
  7454. /**
  7455. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7456. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7457. * curveA and curveB keep unchanged.
  7458. */
  7459. Curve3.prototype.continue = function (curve) {
  7460. var lastPoint = this._points[this._points.length - 1];
  7461. var continuedPoints = this._points.slice();
  7462. var curvePoints = curve.getPoints();
  7463. for (var i = 1; i < curvePoints.length; i++) {
  7464. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7465. }
  7466. var continuedCurve = new Curve3(continuedPoints);
  7467. return continuedCurve;
  7468. };
  7469. Curve3.prototype._computeLength = function (path) {
  7470. var l = 0;
  7471. for (var i = 1; i < path.length; i++) {
  7472. l += (path[i].subtract(path[i - 1])).length();
  7473. }
  7474. return l;
  7475. };
  7476. return Curve3;
  7477. }());
  7478. BABYLON.Curve3 = Curve3;
  7479. // Vertex formats
  7480. var PositionNormalVertex = /** @class */ (function () {
  7481. function PositionNormalVertex(position, normal) {
  7482. if (position === void 0) { position = Vector3.Zero(); }
  7483. if (normal === void 0) { normal = Vector3.Up(); }
  7484. this.position = position;
  7485. this.normal = normal;
  7486. }
  7487. PositionNormalVertex.prototype.clone = function () {
  7488. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7489. };
  7490. return PositionNormalVertex;
  7491. }());
  7492. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7493. var PositionNormalTextureVertex = /** @class */ (function () {
  7494. function PositionNormalTextureVertex(position, normal, uv) {
  7495. if (position === void 0) { position = Vector3.Zero(); }
  7496. if (normal === void 0) { normal = Vector3.Up(); }
  7497. if (uv === void 0) { uv = Vector2.Zero(); }
  7498. this.position = position;
  7499. this.normal = normal;
  7500. this.uv = uv;
  7501. }
  7502. PositionNormalTextureVertex.prototype.clone = function () {
  7503. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7504. };
  7505. return PositionNormalTextureVertex;
  7506. }());
  7507. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7508. // Temporary pre-allocated objects for engine internal use
  7509. // usage in any internal function :
  7510. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7511. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7512. var Tmp = /** @class */ (function () {
  7513. function Tmp() {
  7514. }
  7515. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7516. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7517. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7518. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7519. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7520. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7521. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7522. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7523. Matrix.Zero(), Matrix.Zero(),
  7524. Matrix.Zero(), Matrix.Zero(),
  7525. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7526. return Tmp;
  7527. }());
  7528. BABYLON.Tmp = Tmp;
  7529. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7530. var MathTmp = /** @class */ (function () {
  7531. function MathTmp() {
  7532. }
  7533. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7534. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7535. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7536. return MathTmp;
  7537. }());
  7538. })(BABYLON || (BABYLON = {}));
  7539. //# sourceMappingURL=babylon.math.js.map
  7540. var BABYLON;
  7541. (function (BABYLON) {
  7542. var Scalar = /** @class */ (function () {
  7543. function Scalar() {
  7544. }
  7545. /**
  7546. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7547. */
  7548. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7549. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7550. var num = a - b;
  7551. return -epsilon <= num && num <= epsilon;
  7552. };
  7553. /**
  7554. * Returns a string : the upper case translation of the number i to hexadecimal.
  7555. */
  7556. Scalar.ToHex = function (i) {
  7557. var str = i.toString(16);
  7558. if (i <= 15) {
  7559. return ("0" + str).toUpperCase();
  7560. }
  7561. return str.toUpperCase();
  7562. };
  7563. /**
  7564. * Returns -1 if value is negative and +1 is value is positive.
  7565. * Returns the value itself if it's equal to zero.
  7566. */
  7567. Scalar.Sign = function (value) {
  7568. value = +value; // convert to a number
  7569. if (value === 0 || isNaN(value))
  7570. return value;
  7571. return value > 0 ? 1 : -1;
  7572. };
  7573. /**
  7574. * Returns the value itself if it's between min and max.
  7575. * Returns min if the value is lower than min.
  7576. * Returns max if the value is greater than max.
  7577. */
  7578. Scalar.Clamp = function (value, min, max) {
  7579. if (min === void 0) { min = 0; }
  7580. if (max === void 0) { max = 1; }
  7581. return Math.min(max, Math.max(min, value));
  7582. };
  7583. /**
  7584. * Returns the log2 of value.
  7585. */
  7586. Scalar.Log2 = function (value) {
  7587. return Math.log(value) * Math.LOG2E;
  7588. };
  7589. /**
  7590. * Loops the value, so that it is never larger than length and never smaller than 0.
  7591. *
  7592. * This is similar to the modulo operator but it works with floating point numbers.
  7593. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7594. * With t = 5 and length = 2.5, the result would be 0.0.
  7595. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7596. */
  7597. Scalar.Repeat = function (value, length) {
  7598. return value - Math.floor(value / length) * length;
  7599. };
  7600. /**
  7601. * Normalize the value between 0.0 and 1.0 using min and max values
  7602. */
  7603. Scalar.Normalize = function (value, min, max) {
  7604. return (value - min) / (max - min);
  7605. };
  7606. /**
  7607. * Denormalize the value from 0.0 and 1.0 using min and max values
  7608. */
  7609. Scalar.Denormalize = function (normalized, min, max) {
  7610. return (normalized * (max - min) + min);
  7611. };
  7612. /**
  7613. * Calculates the shortest difference between two given angles given in degrees.
  7614. */
  7615. Scalar.DeltaAngle = function (current, target) {
  7616. var num = Scalar.Repeat(target - current, 360.0);
  7617. if (num > 180.0) {
  7618. num -= 360.0;
  7619. }
  7620. return num;
  7621. };
  7622. /**
  7623. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7624. *
  7625. * The returned value will move back and forth between 0 and length
  7626. */
  7627. Scalar.PingPong = function (tx, length) {
  7628. var t = Scalar.Repeat(tx, length * 2.0);
  7629. return length - Math.abs(t - length);
  7630. };
  7631. /**
  7632. * Interpolates between min and max with smoothing at the limits.
  7633. *
  7634. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7635. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7636. */
  7637. Scalar.SmoothStep = function (from, to, tx) {
  7638. var t = Scalar.Clamp(tx);
  7639. t = -2.0 * t * t * t + 3.0 * t * t;
  7640. return to * t + from * (1.0 - t);
  7641. };
  7642. /**
  7643. * Moves a value current towards target.
  7644. *
  7645. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7646. * Negative values of maxDelta pushes the value away from target.
  7647. */
  7648. Scalar.MoveTowards = function (current, target, maxDelta) {
  7649. var result = 0;
  7650. if (Math.abs(target - current) <= maxDelta) {
  7651. result = target;
  7652. }
  7653. else {
  7654. result = current + Scalar.Sign(target - current) * maxDelta;
  7655. }
  7656. return result;
  7657. };
  7658. /**
  7659. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7660. *
  7661. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7662. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7663. */
  7664. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7665. var num = Scalar.DeltaAngle(current, target);
  7666. var result = 0;
  7667. if (-maxDelta < num && num < maxDelta) {
  7668. result = target;
  7669. }
  7670. else {
  7671. target = current + num;
  7672. result = Scalar.MoveTowards(current, target, maxDelta);
  7673. }
  7674. return result;
  7675. };
  7676. /**
  7677. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7678. */
  7679. Scalar.Lerp = function (start, end, amount) {
  7680. return start + ((end - start) * amount);
  7681. };
  7682. /**
  7683. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7684. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7685. */
  7686. Scalar.LerpAngle = function (start, end, amount) {
  7687. var num = Scalar.Repeat(end - start, 360.0);
  7688. if (num > 180.0) {
  7689. num -= 360.0;
  7690. }
  7691. return start + num * Scalar.Clamp(amount);
  7692. };
  7693. /**
  7694. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7695. */
  7696. Scalar.InverseLerp = function (a, b, value) {
  7697. var result = 0;
  7698. if (a != b) {
  7699. result = Scalar.Clamp((value - a) / (b - a));
  7700. }
  7701. else {
  7702. result = 0.0;
  7703. }
  7704. return result;
  7705. };
  7706. /**
  7707. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7708. */
  7709. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7710. var squared = amount * amount;
  7711. var cubed = amount * squared;
  7712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7714. var part3 = (cubed - (2.0 * squared)) + amount;
  7715. var part4 = cubed - squared;
  7716. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7717. };
  7718. /**
  7719. * Returns a random float number between and min and max values
  7720. */
  7721. Scalar.RandomRange = function (min, max) {
  7722. if (min === max)
  7723. return min;
  7724. return ((Math.random() * (max - min)) + min);
  7725. };
  7726. /**
  7727. * This function returns percentage of a number in a given range.
  7728. *
  7729. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7730. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7731. */
  7732. Scalar.RangeToPercent = function (number, min, max) {
  7733. return ((number - min) / (max - min));
  7734. };
  7735. /**
  7736. * This function returns number that corresponds to the percentage in a given range.
  7737. *
  7738. * PercentToRange(0.34,0,100) will return 34.
  7739. */
  7740. Scalar.PercentToRange = function (percent, min, max) {
  7741. return ((max - min) * percent + min);
  7742. };
  7743. /**
  7744. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7745. * @param angle The angle to normalize in radian.
  7746. * @return The converted angle.
  7747. */
  7748. Scalar.NormalizeRadians = function (angle) {
  7749. // More precise but slower version kept for reference.
  7750. // angle = angle % Tools.TwoPi;
  7751. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7752. //if (angle > Math.PI) {
  7753. // angle -= Tools.TwoPi;
  7754. //}
  7755. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7756. return angle;
  7757. };
  7758. /**
  7759. * Two pi constants convenient for computation.
  7760. */
  7761. Scalar.TwoPi = Math.PI * 2;
  7762. return Scalar;
  7763. }());
  7764. BABYLON.Scalar = Scalar;
  7765. })(BABYLON || (BABYLON = {}));
  7766. //# sourceMappingURL=babylon.math.scalar.js.map
  7767. //# sourceMappingURL=babylon.mixins.js.map
  7768. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7769. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7770. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7771. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7772. //# sourceMappingURL=babylon.webgl2.js.map
  7773. var BABYLON;
  7774. (function (BABYLON) {
  7775. var __decoratorInitialStore = {};
  7776. var __mergedStore = {};
  7777. var _copySource = function (creationFunction, source, instanciate) {
  7778. var destination = creationFunction();
  7779. // Tags
  7780. if (BABYLON.Tags) {
  7781. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7782. }
  7783. var classStore = getMergedStore(destination);
  7784. // Properties
  7785. for (var property in classStore) {
  7786. var propertyDescriptor = classStore[property];
  7787. var sourceProperty = source[property];
  7788. var propertyType = propertyDescriptor.type;
  7789. if (sourceProperty !== undefined && sourceProperty !== null) {
  7790. switch (propertyType) {
  7791. case 0: // Value
  7792. case 6: // Mesh reference
  7793. case 11: // Camera reference
  7794. destination[property] = sourceProperty;
  7795. break;
  7796. case 1: // Texture
  7797. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7798. break;
  7799. case 2: // Color3
  7800. case 3: // FresnelParameters
  7801. case 4: // Vector2
  7802. case 5: // Vector3
  7803. case 7: // Color Curves
  7804. case 10: // Quaternion
  7805. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7806. break;
  7807. }
  7808. }
  7809. }
  7810. return destination;
  7811. };
  7812. function getDirectStore(target) {
  7813. var classKey = target.getClassName();
  7814. if (!__decoratorInitialStore[classKey]) {
  7815. __decoratorInitialStore[classKey] = {};
  7816. }
  7817. return __decoratorInitialStore[classKey];
  7818. }
  7819. /**
  7820. * Return the list of properties flagged as serializable
  7821. * @param target: host object
  7822. */
  7823. function getMergedStore(target) {
  7824. var classKey = target.getClassName();
  7825. if (__mergedStore[classKey]) {
  7826. return __mergedStore[classKey];
  7827. }
  7828. __mergedStore[classKey] = {};
  7829. var store = __mergedStore[classKey];
  7830. var currentTarget = target;
  7831. var currentKey = classKey;
  7832. while (currentKey) {
  7833. var initialStore = __decoratorInitialStore[currentKey];
  7834. for (var property in initialStore) {
  7835. store[property] = initialStore[property];
  7836. }
  7837. var parent_1 = void 0;
  7838. var done = false;
  7839. do {
  7840. parent_1 = Object.getPrototypeOf(currentTarget);
  7841. if (!parent_1.getClassName) {
  7842. done = true;
  7843. break;
  7844. }
  7845. if (parent_1.getClassName() !== currentKey) {
  7846. break;
  7847. }
  7848. currentTarget = parent_1;
  7849. } while (parent_1);
  7850. if (done) {
  7851. break;
  7852. }
  7853. currentKey = parent_1.getClassName();
  7854. currentTarget = parent_1;
  7855. }
  7856. return store;
  7857. }
  7858. function generateSerializableMember(type, sourceName) {
  7859. return function (target, propertyKey) {
  7860. var classStore = getDirectStore(target);
  7861. if (!classStore[propertyKey]) {
  7862. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7863. }
  7864. };
  7865. }
  7866. function generateExpandMember(setCallback, targetKey) {
  7867. if (targetKey === void 0) { targetKey = null; }
  7868. return function (target, propertyKey) {
  7869. var key = targetKey || ("_" + propertyKey);
  7870. Object.defineProperty(target, propertyKey, {
  7871. get: function () {
  7872. return this[key];
  7873. },
  7874. set: function (value) {
  7875. if (this[key] === value) {
  7876. return;
  7877. }
  7878. this[key] = value;
  7879. target[setCallback].apply(this);
  7880. },
  7881. enumerable: true,
  7882. configurable: true
  7883. });
  7884. };
  7885. }
  7886. function expandToProperty(callback, targetKey) {
  7887. if (targetKey === void 0) { targetKey = null; }
  7888. return generateExpandMember(callback, targetKey);
  7889. }
  7890. BABYLON.expandToProperty = expandToProperty;
  7891. function serialize(sourceName) {
  7892. return generateSerializableMember(0, sourceName); // value member
  7893. }
  7894. BABYLON.serialize = serialize;
  7895. function serializeAsTexture(sourceName) {
  7896. return generateSerializableMember(1, sourceName); // texture member
  7897. }
  7898. BABYLON.serializeAsTexture = serializeAsTexture;
  7899. function serializeAsColor3(sourceName) {
  7900. return generateSerializableMember(2, sourceName); // color3 member
  7901. }
  7902. BABYLON.serializeAsColor3 = serializeAsColor3;
  7903. function serializeAsFresnelParameters(sourceName) {
  7904. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7905. }
  7906. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7907. function serializeAsVector2(sourceName) {
  7908. return generateSerializableMember(4, sourceName); // vector2 member
  7909. }
  7910. BABYLON.serializeAsVector2 = serializeAsVector2;
  7911. function serializeAsVector3(sourceName) {
  7912. return generateSerializableMember(5, sourceName); // vector3 member
  7913. }
  7914. BABYLON.serializeAsVector3 = serializeAsVector3;
  7915. function serializeAsMeshReference(sourceName) {
  7916. return generateSerializableMember(6, sourceName); // mesh reference member
  7917. }
  7918. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7919. function serializeAsColorCurves(sourceName) {
  7920. return generateSerializableMember(7, sourceName); // color curves
  7921. }
  7922. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7923. function serializeAsColor4(sourceName) {
  7924. return generateSerializableMember(8, sourceName); // color 4
  7925. }
  7926. BABYLON.serializeAsColor4 = serializeAsColor4;
  7927. function serializeAsImageProcessingConfiguration(sourceName) {
  7928. return generateSerializableMember(9, sourceName); // image processing
  7929. }
  7930. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7931. function serializeAsQuaternion(sourceName) {
  7932. return generateSerializableMember(10, sourceName); // quaternion member
  7933. }
  7934. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7935. /**
  7936. * Decorator used to define property that can be serialized as reference to a camera
  7937. * @param sourceName defines the name of the property to decorate
  7938. */
  7939. function serializeAsCameraReference(sourceName) {
  7940. return generateSerializableMember(11, sourceName); // camera reference member
  7941. }
  7942. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7943. var SerializationHelper = /** @class */ (function () {
  7944. function SerializationHelper() {
  7945. }
  7946. SerializationHelper.Serialize = function (entity, serializationObject) {
  7947. if (!serializationObject) {
  7948. serializationObject = {};
  7949. }
  7950. // Tags
  7951. if (BABYLON.Tags) {
  7952. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7953. }
  7954. var serializedProperties = getMergedStore(entity);
  7955. // Properties
  7956. for (var property in serializedProperties) {
  7957. var propertyDescriptor = serializedProperties[property];
  7958. var targetPropertyName = propertyDescriptor.sourceName || property;
  7959. var propertyType = propertyDescriptor.type;
  7960. var sourceProperty = entity[property];
  7961. if (sourceProperty !== undefined && sourceProperty !== null) {
  7962. switch (propertyType) {
  7963. case 0: // Value
  7964. serializationObject[targetPropertyName] = sourceProperty;
  7965. break;
  7966. case 1: // Texture
  7967. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7968. break;
  7969. case 2: // Color3
  7970. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7971. break;
  7972. case 3: // FresnelParameters
  7973. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7974. break;
  7975. case 4: // Vector2
  7976. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7977. break;
  7978. case 5: // Vector3
  7979. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7980. break;
  7981. case 6: // Mesh reference
  7982. serializationObject[targetPropertyName] = sourceProperty.id;
  7983. break;
  7984. case 7: // Color Curves
  7985. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7986. break;
  7987. case 8: // Color 4
  7988. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7989. break;
  7990. case 9: // Image Processing
  7991. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7992. break;
  7993. case 10: // Quaternion
  7994. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7995. break;
  7996. case 11: // Camera reference
  7997. serializationObject[targetPropertyName] = sourceProperty.id;
  7998. break;
  7999. }
  8000. }
  8001. }
  8002. return serializationObject;
  8003. };
  8004. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8005. if (rootUrl === void 0) { rootUrl = null; }
  8006. var destination = creationFunction();
  8007. if (!rootUrl) {
  8008. rootUrl = "";
  8009. }
  8010. // Tags
  8011. if (BABYLON.Tags) {
  8012. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8013. }
  8014. var classStore = getMergedStore(destination);
  8015. // Properties
  8016. for (var property in classStore) {
  8017. var propertyDescriptor = classStore[property];
  8018. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8019. var propertyType = propertyDescriptor.type;
  8020. if (sourceProperty !== undefined && sourceProperty !== null) {
  8021. var dest = destination;
  8022. switch (propertyType) {
  8023. case 0: // Value
  8024. dest[property] = sourceProperty;
  8025. break;
  8026. case 1: // Texture
  8027. if (scene) {
  8028. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8029. }
  8030. break;
  8031. case 2: // Color3
  8032. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8033. break;
  8034. case 3: // FresnelParameters
  8035. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8036. break;
  8037. case 4: // Vector2
  8038. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8039. break;
  8040. case 5: // Vector3
  8041. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8042. break;
  8043. case 6: // Mesh reference
  8044. if (scene) {
  8045. dest[property] = scene.getLastMeshByID(sourceProperty);
  8046. }
  8047. break;
  8048. case 7: // Color Curves
  8049. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8050. break;
  8051. case 8: // Color 4
  8052. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8053. break;
  8054. case 9: // Image Processing
  8055. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8056. break;
  8057. case 10: // Quaternion
  8058. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8059. break;
  8060. case 11: // Camera reference
  8061. if (scene) {
  8062. dest[property] = scene.getCameraByID(sourceProperty);
  8063. }
  8064. break;
  8065. }
  8066. }
  8067. }
  8068. return destination;
  8069. };
  8070. SerializationHelper.Clone = function (creationFunction, source) {
  8071. return _copySource(creationFunction, source, false);
  8072. };
  8073. SerializationHelper.Instanciate = function (creationFunction, source) {
  8074. return _copySource(creationFunction, source, true);
  8075. };
  8076. return SerializationHelper;
  8077. }());
  8078. BABYLON.SerializationHelper = SerializationHelper;
  8079. })(BABYLON || (BABYLON = {}));
  8080. //# sourceMappingURL=babylon.decorators.js.map
  8081. var BABYLON;
  8082. (function (BABYLON) {
  8083. /**
  8084. * Wrapper class for promise with external resolve and reject.
  8085. */
  8086. var Deferred = /** @class */ (function () {
  8087. /**
  8088. * Constructor for this deferred object.
  8089. */
  8090. function Deferred() {
  8091. var _this = this;
  8092. this.promise = new Promise(function (resolve, reject) {
  8093. _this._resolve = resolve;
  8094. _this._reject = reject;
  8095. });
  8096. }
  8097. Object.defineProperty(Deferred.prototype, "resolve", {
  8098. /**
  8099. * The resolve method of the promise associated with this deferred object.
  8100. */
  8101. get: function () {
  8102. return this._resolve;
  8103. },
  8104. enumerable: true,
  8105. configurable: true
  8106. });
  8107. Object.defineProperty(Deferred.prototype, "reject", {
  8108. /**
  8109. * The reject method of the promise associated with this deferred object.
  8110. */
  8111. get: function () {
  8112. return this._reject;
  8113. },
  8114. enumerable: true,
  8115. configurable: true
  8116. });
  8117. return Deferred;
  8118. }());
  8119. BABYLON.Deferred = Deferred;
  8120. })(BABYLON || (BABYLON = {}));
  8121. //# sourceMappingURL=babylon.deferred.js.map
  8122. var BABYLON;
  8123. (function (BABYLON) {
  8124. /**
  8125. * A class serves as a medium between the observable and its observers
  8126. */
  8127. var EventState = /** @class */ (function () {
  8128. /**
  8129. * Create a new EventState
  8130. * @param mask defines the mask associated with this state
  8131. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8132. * @param target defines the original target of the state
  8133. * @param currentTarget defines the current target of the state
  8134. */
  8135. function EventState(mask, skipNextObservers, target, currentTarget) {
  8136. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8137. this.initalize(mask, skipNextObservers, target, currentTarget);
  8138. }
  8139. /**
  8140. * Initialize the current event state
  8141. * @param mask defines the mask associated with this state
  8142. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8143. * @param target defines the original target of the state
  8144. * @param currentTarget defines the current target of the state
  8145. * @returns the current event state
  8146. */
  8147. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8148. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8149. this.mask = mask;
  8150. this.skipNextObservers = skipNextObservers;
  8151. this.target = target;
  8152. this.currentTarget = currentTarget;
  8153. return this;
  8154. };
  8155. return EventState;
  8156. }());
  8157. BABYLON.EventState = EventState;
  8158. /**
  8159. * Represent an Observer registered to a given Observable object.
  8160. */
  8161. var Observer = /** @class */ (function () {
  8162. /**
  8163. * Creates a new observer
  8164. * @param callback defines the callback to call when the observer is notified
  8165. * @param mask defines the mask of the observer (used to filter notifications)
  8166. * @param scope defines the current scope used to restore the JS context
  8167. */
  8168. function Observer(
  8169. /**
  8170. * Defines the callback to call when the observer is notified
  8171. */
  8172. callback,
  8173. /**
  8174. * Defines the mask of the observer (used to filter notifications)
  8175. */
  8176. mask,
  8177. /**
  8178. * Defines the current scope used to restore the JS context
  8179. */
  8180. scope) {
  8181. if (scope === void 0) { scope = null; }
  8182. this.callback = callback;
  8183. this.mask = mask;
  8184. this.scope = scope;
  8185. /** @hidden */
  8186. this._willBeUnregistered = false;
  8187. /**
  8188. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8189. */
  8190. this.unregisterOnNextCall = false;
  8191. }
  8192. return Observer;
  8193. }());
  8194. BABYLON.Observer = Observer;
  8195. /**
  8196. * Represent a list of observers registered to multiple Observables object.
  8197. */
  8198. var MultiObserver = /** @class */ (function () {
  8199. function MultiObserver() {
  8200. }
  8201. /**
  8202. * Release associated resources
  8203. */
  8204. MultiObserver.prototype.dispose = function () {
  8205. if (this._observers && this._observables) {
  8206. for (var index = 0; index < this._observers.length; index++) {
  8207. this._observables[index].remove(this._observers[index]);
  8208. }
  8209. }
  8210. this._observers = null;
  8211. this._observables = null;
  8212. };
  8213. /**
  8214. * Raise a callback when one of the observable will notify
  8215. * @param observables defines a list of observables to watch
  8216. * @param callback defines the callback to call on notification
  8217. * @param mask defines the mask used to filter notifications
  8218. * @param scope defines the current scope used to restore the JS context
  8219. * @returns the new MultiObserver
  8220. */
  8221. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8222. if (mask === void 0) { mask = -1; }
  8223. if (scope === void 0) { scope = null; }
  8224. var result = new MultiObserver();
  8225. result._observers = new Array();
  8226. result._observables = observables;
  8227. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8228. var observable = observables_1[_i];
  8229. var observer = observable.add(callback, mask, false, scope);
  8230. if (observer) {
  8231. result._observers.push(observer);
  8232. }
  8233. }
  8234. return result;
  8235. };
  8236. return MultiObserver;
  8237. }());
  8238. BABYLON.MultiObserver = MultiObserver;
  8239. /**
  8240. * The Observable class is a simple implementation of the Observable pattern.
  8241. *
  8242. * 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.
  8243. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8244. * 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).
  8245. * 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.
  8246. */
  8247. var Observable = /** @class */ (function () {
  8248. /**
  8249. * Creates a new observable
  8250. * @param onObserverAdded defines a callback to call when a new observer is added
  8251. */
  8252. function Observable(onObserverAdded) {
  8253. this._observers = new Array();
  8254. this._eventState = new EventState(0);
  8255. if (onObserverAdded) {
  8256. this._onObserverAdded = onObserverAdded;
  8257. }
  8258. }
  8259. /**
  8260. * Create a new Observer with the specified callback
  8261. * @param callback the callback that will be executed for that Observer
  8262. * @param mask the mask used to filter observers
  8263. * @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.
  8264. * @param scope optional scope for the callback to be called from
  8265. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8266. * @returns the new observer created for the callback
  8267. */
  8268. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8269. if (mask === void 0) { mask = -1; }
  8270. if (insertFirst === void 0) { insertFirst = false; }
  8271. if (scope === void 0) { scope = null; }
  8272. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8273. if (!callback) {
  8274. return null;
  8275. }
  8276. var observer = new Observer(callback, mask, scope);
  8277. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8278. if (insertFirst) {
  8279. this._observers.unshift(observer);
  8280. }
  8281. else {
  8282. this._observers.push(observer);
  8283. }
  8284. if (this._onObserverAdded) {
  8285. this._onObserverAdded(observer);
  8286. }
  8287. return observer;
  8288. };
  8289. /**
  8290. * Create a new Observer with the specified callback and unregisters after the next notification
  8291. * @param callback the callback that will be executed for that Observer
  8292. * @returns the new observer created for the callback
  8293. */
  8294. Observable.prototype.addOnce = function (callback) {
  8295. return this.add(callback, undefined, undefined, undefined, true);
  8296. };
  8297. /**
  8298. * Remove an Observer from the Observable object
  8299. * @param observer the instance of the Observer to remove
  8300. * @returns false if it doesn't belong to this Observable
  8301. */
  8302. Observable.prototype.remove = function (observer) {
  8303. if (!observer) {
  8304. return false;
  8305. }
  8306. var index = this._observers.indexOf(observer);
  8307. if (index !== -1) {
  8308. this._deferUnregister(observer);
  8309. return true;
  8310. }
  8311. return false;
  8312. };
  8313. /**
  8314. * Remove a callback from the Observable object
  8315. * @param callback the callback to remove
  8316. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8317. * @returns false if it doesn't belong to this Observable
  8318. */
  8319. Observable.prototype.removeCallback = function (callback, scope) {
  8320. for (var index = 0; index < this._observers.length; index++) {
  8321. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8322. this._deferUnregister(this._observers[index]);
  8323. return true;
  8324. }
  8325. }
  8326. return false;
  8327. };
  8328. Observable.prototype._deferUnregister = function (observer) {
  8329. var _this = this;
  8330. observer.unregisterOnNextCall = false;
  8331. observer._willBeUnregistered = true;
  8332. BABYLON.Tools.SetImmediate(function () {
  8333. _this._remove(observer);
  8334. });
  8335. };
  8336. // This should only be called when not iterating over _observers to avoid callback skipping.
  8337. // Removes an observer from the _observer Array.
  8338. Observable.prototype._remove = function (observer) {
  8339. if (!observer) {
  8340. return false;
  8341. }
  8342. var index = this._observers.indexOf(observer);
  8343. if (index !== -1) {
  8344. this._observers.splice(index, 1);
  8345. return true;
  8346. }
  8347. return false;
  8348. };
  8349. /**
  8350. * Notify all Observers by calling their respective callback with the given data
  8351. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8352. * @param eventData defines the data to send to all observers
  8353. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8354. * @param target defines the original target of the state
  8355. * @param currentTarget defines the current target of the state
  8356. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8357. */
  8358. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8359. if (mask === void 0) { mask = -1; }
  8360. if (!this._observers.length) {
  8361. return true;
  8362. }
  8363. var state = this._eventState;
  8364. state.mask = mask;
  8365. state.target = target;
  8366. state.currentTarget = currentTarget;
  8367. state.skipNextObservers = false;
  8368. state.lastReturnValue = eventData;
  8369. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8370. var obs = _a[_i];
  8371. if (obs._willBeUnregistered) {
  8372. continue;
  8373. }
  8374. if (obs.mask & mask) {
  8375. if (obs.scope) {
  8376. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8377. }
  8378. else {
  8379. state.lastReturnValue = obs.callback(eventData, state);
  8380. }
  8381. if (obs.unregisterOnNextCall) {
  8382. this._deferUnregister(obs);
  8383. }
  8384. }
  8385. if (state.skipNextObservers) {
  8386. return false;
  8387. }
  8388. }
  8389. return true;
  8390. };
  8391. /**
  8392. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8393. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8394. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8395. * and it is crucial that all callbacks will be executed.
  8396. * The order of the callbacks is kept, callbacks are not executed parallel.
  8397. *
  8398. * @param eventData The data to be sent to each callback
  8399. * @param mask is used to filter observers defaults to -1
  8400. * @param target defines the callback target (see EventState)
  8401. * @param currentTarget defines he current object in the bubbling phase
  8402. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8403. */
  8404. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8405. var _this = this;
  8406. if (mask === void 0) { mask = -1; }
  8407. // create an empty promise
  8408. var p = Promise.resolve(eventData);
  8409. // no observers? return this promise.
  8410. if (!this._observers.length) {
  8411. return p;
  8412. }
  8413. var state = this._eventState;
  8414. state.mask = mask;
  8415. state.target = target;
  8416. state.currentTarget = currentTarget;
  8417. state.skipNextObservers = false;
  8418. // execute one callback after another (not using Promise.all, the order is important)
  8419. this._observers.forEach(function (obs) {
  8420. if (state.skipNextObservers) {
  8421. return;
  8422. }
  8423. if (obs._willBeUnregistered) {
  8424. return;
  8425. }
  8426. if (obs.mask & mask) {
  8427. if (obs.scope) {
  8428. p = p.then(function (lastReturnedValue) {
  8429. state.lastReturnValue = lastReturnedValue;
  8430. return obs.callback.apply(obs.scope, [eventData, state]);
  8431. });
  8432. }
  8433. else {
  8434. p = p.then(function (lastReturnedValue) {
  8435. state.lastReturnValue = lastReturnedValue;
  8436. return obs.callback(eventData, state);
  8437. });
  8438. }
  8439. if (obs.unregisterOnNextCall) {
  8440. _this._deferUnregister(obs);
  8441. }
  8442. }
  8443. });
  8444. // return the eventData
  8445. return p.then(function () { return eventData; });
  8446. };
  8447. /**
  8448. * Notify a specific observer
  8449. * @param observer defines the observer to notify
  8450. * @param eventData defines the data to be sent to each callback
  8451. * @param mask is used to filter observers defaults to -1
  8452. */
  8453. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8454. if (mask === void 0) { mask = -1; }
  8455. var state = this._eventState;
  8456. state.mask = mask;
  8457. state.skipNextObservers = false;
  8458. observer.callback(eventData, state);
  8459. };
  8460. /**
  8461. * Gets a boolean indicating if the observable has at least one observer
  8462. * @returns true is the Observable has at least one Observer registered
  8463. */
  8464. Observable.prototype.hasObservers = function () {
  8465. return this._observers.length > 0;
  8466. };
  8467. /**
  8468. * Clear the list of observers
  8469. */
  8470. Observable.prototype.clear = function () {
  8471. this._observers = new Array();
  8472. this._onObserverAdded = null;
  8473. };
  8474. /**
  8475. * Clone the current observable
  8476. * @returns a new observable
  8477. */
  8478. Observable.prototype.clone = function () {
  8479. var result = new Observable();
  8480. result._observers = this._observers.slice(0);
  8481. return result;
  8482. };
  8483. /**
  8484. * Does this observable handles observer registered with a given mask
  8485. * @param mask defines the mask to be tested
  8486. * @return whether or not one observer registered with the given mask is handeled
  8487. **/
  8488. Observable.prototype.hasSpecificMask = function (mask) {
  8489. if (mask === void 0) { mask = -1; }
  8490. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8491. var obs = _a[_i];
  8492. if (obs.mask & mask || obs.mask === mask) {
  8493. return true;
  8494. }
  8495. }
  8496. return false;
  8497. };
  8498. return Observable;
  8499. }());
  8500. BABYLON.Observable = Observable;
  8501. })(BABYLON || (BABYLON = {}));
  8502. //# sourceMappingURL=babylon.observable.js.map
  8503. var BABYLON;
  8504. (function (BABYLON) {
  8505. /**
  8506. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8507. */
  8508. var SmartArray = /** @class */ (function () {
  8509. /**
  8510. * Instantiates a Smart Array.
  8511. * @param capacity defines the default capacity of the array.
  8512. */
  8513. function SmartArray(capacity) {
  8514. /**
  8515. * The active length of the array.
  8516. */
  8517. this.length = 0;
  8518. this.data = new Array(capacity);
  8519. this._id = SmartArray._GlobalId++;
  8520. }
  8521. /**
  8522. * Pushes a value at the end of the active data.
  8523. * @param value defines the object to push in the array.
  8524. */
  8525. SmartArray.prototype.push = function (value) {
  8526. this.data[this.length++] = value;
  8527. if (this.length > this.data.length) {
  8528. this.data.length *= 2;
  8529. }
  8530. };
  8531. /**
  8532. * Iterates over the active data and apply the lambda to them.
  8533. * @param func defines the action to apply on each value.
  8534. */
  8535. SmartArray.prototype.forEach = function (func) {
  8536. for (var index = 0; index < this.length; index++) {
  8537. func(this.data[index]);
  8538. }
  8539. };
  8540. /**
  8541. * Sorts the full sets of data.
  8542. * @param compareFn defines the comparison function to apply.
  8543. */
  8544. SmartArray.prototype.sort = function (compareFn) {
  8545. this.data.sort(compareFn);
  8546. };
  8547. /**
  8548. * Resets the active data to an empty array.
  8549. */
  8550. SmartArray.prototype.reset = function () {
  8551. this.length = 0;
  8552. };
  8553. /**
  8554. * Releases all the data from the array as well as the array.
  8555. */
  8556. SmartArray.prototype.dispose = function () {
  8557. this.reset();
  8558. if (this.data) {
  8559. this.data.length = 0;
  8560. this.data = [];
  8561. }
  8562. };
  8563. /**
  8564. * Concats the active data with a given array.
  8565. * @param array defines the data to concatenate with.
  8566. */
  8567. SmartArray.prototype.concat = function (array) {
  8568. if (array.length === 0) {
  8569. return;
  8570. }
  8571. if (this.length + array.length > this.data.length) {
  8572. this.data.length = (this.length + array.length) * 2;
  8573. }
  8574. for (var index = 0; index < array.length; index++) {
  8575. this.data[this.length++] = (array.data || array)[index];
  8576. }
  8577. };
  8578. /**
  8579. * Returns the position of a value in the active data.
  8580. * @param value defines the value to find the index for
  8581. * @returns the index if found in the active data otherwise -1
  8582. */
  8583. SmartArray.prototype.indexOf = function (value) {
  8584. var position = this.data.indexOf(value);
  8585. if (position >= this.length) {
  8586. return -1;
  8587. }
  8588. return position;
  8589. };
  8590. /**
  8591. * Returns whether an element is part of the active data.
  8592. * @param value defines the value to look for
  8593. * @returns true if found in the active data otherwise false
  8594. */
  8595. SmartArray.prototype.contains = function (value) {
  8596. return this.indexOf(value) !== -1;
  8597. };
  8598. // Statics
  8599. SmartArray._GlobalId = 0;
  8600. return SmartArray;
  8601. }());
  8602. BABYLON.SmartArray = SmartArray;
  8603. /**
  8604. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8605. * The data in this array can only be present once
  8606. */
  8607. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8608. __extends(SmartArrayNoDuplicate, _super);
  8609. function SmartArrayNoDuplicate() {
  8610. var _this = _super !== null && _super.apply(this, arguments) || this;
  8611. _this._duplicateId = 0;
  8612. return _this;
  8613. }
  8614. /**
  8615. * Pushes a value at the end of the active data.
  8616. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8617. * @param value defines the object to push in the array.
  8618. */
  8619. SmartArrayNoDuplicate.prototype.push = function (value) {
  8620. _super.prototype.push.call(this, value);
  8621. if (!value.__smartArrayFlags) {
  8622. value.__smartArrayFlags = {};
  8623. }
  8624. value.__smartArrayFlags[this._id] = this._duplicateId;
  8625. };
  8626. /**
  8627. * Pushes a value at the end of the active data.
  8628. * If the data is already present, it won t be added again
  8629. * @param value defines the object to push in the array.
  8630. * @returns true if added false if it was already present
  8631. */
  8632. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8633. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8634. return false;
  8635. }
  8636. this.push(value);
  8637. return true;
  8638. };
  8639. /**
  8640. * Resets the active data to an empty array.
  8641. */
  8642. SmartArrayNoDuplicate.prototype.reset = function () {
  8643. _super.prototype.reset.call(this);
  8644. this._duplicateId++;
  8645. };
  8646. /**
  8647. * Concats the active data with a given array.
  8648. * This ensures no dupplicate will be present in the result.
  8649. * @param array defines the data to concatenate with.
  8650. */
  8651. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8652. if (array.length === 0) {
  8653. return;
  8654. }
  8655. if (this.length + array.length > this.data.length) {
  8656. this.data.length = (this.length + array.length) * 2;
  8657. }
  8658. for (var index = 0; index < array.length; index++) {
  8659. var item = (array.data || array)[index];
  8660. this.pushNoDuplicate(item);
  8661. }
  8662. };
  8663. return SmartArrayNoDuplicate;
  8664. }(SmartArray));
  8665. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8666. })(BABYLON || (BABYLON = {}));
  8667. //# sourceMappingURL=babylon.smartArray.js.map
  8668. var BABYLON;
  8669. (function (BABYLON) {
  8670. /** Class used to store color4 gradient */
  8671. var ColorGradient = /** @class */ (function () {
  8672. function ColorGradient() {
  8673. }
  8674. /**
  8675. * Will get a color picked randomly between color1 and color2.
  8676. * If color2 is undefined then color1 will be used
  8677. * @param result defines the target Color4 to store the result in
  8678. */
  8679. ColorGradient.prototype.getColorToRef = function (result) {
  8680. if (!this.color2) {
  8681. result.copyFrom(this.color1);
  8682. return;
  8683. }
  8684. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8685. };
  8686. return ColorGradient;
  8687. }());
  8688. BABYLON.ColorGradient = ColorGradient;
  8689. /** Class used to store color 3 gradient */
  8690. var Color3Gradient = /** @class */ (function () {
  8691. function Color3Gradient() {
  8692. }
  8693. return Color3Gradient;
  8694. }());
  8695. BABYLON.Color3Gradient = Color3Gradient;
  8696. /** Class used to store factor gradient */
  8697. var FactorGradient = /** @class */ (function () {
  8698. function FactorGradient() {
  8699. }
  8700. /**
  8701. * Will get a number picked randomly between factor1 and factor2.
  8702. * If factor2 is undefined then factor1 will be used
  8703. * @returns the picked number
  8704. */
  8705. FactorGradient.prototype.getFactor = function () {
  8706. if (this.factor2 === undefined) {
  8707. return this.factor1;
  8708. }
  8709. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8710. };
  8711. return FactorGradient;
  8712. }());
  8713. BABYLON.FactorGradient = FactorGradient;
  8714. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8715. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8716. var LoadFileError = /** @class */ (function (_super) {
  8717. __extends(LoadFileError, _super);
  8718. function LoadFileError(message, request) {
  8719. var _this = _super.call(this, message) || this;
  8720. _this.request = request;
  8721. _this.name = "LoadFileError";
  8722. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8723. return _this;
  8724. }
  8725. // Polyfill for Object.setPrototypeOf if necessary.
  8726. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8727. return LoadFileError;
  8728. }(Error));
  8729. BABYLON.LoadFileError = LoadFileError;
  8730. var RetryStrategy = /** @class */ (function () {
  8731. function RetryStrategy() {
  8732. }
  8733. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8734. if (maxRetries === void 0) { maxRetries = 3; }
  8735. if (baseInterval === void 0) { baseInterval = 500; }
  8736. return function (url, request, retryIndex) {
  8737. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8738. return -1;
  8739. }
  8740. return Math.pow(2, retryIndex) * baseInterval;
  8741. };
  8742. };
  8743. return RetryStrategy;
  8744. }());
  8745. BABYLON.RetryStrategy = RetryStrategy;
  8746. // Screenshots
  8747. var screenshotCanvas;
  8748. var cloneValue = function (source, destinationObject) {
  8749. if (!source)
  8750. return null;
  8751. if (source instanceof BABYLON.Mesh) {
  8752. return null;
  8753. }
  8754. if (source instanceof BABYLON.SubMesh) {
  8755. return source.clone(destinationObject);
  8756. }
  8757. else if (source.clone) {
  8758. return source.clone();
  8759. }
  8760. return null;
  8761. };
  8762. var Tools = /** @class */ (function () {
  8763. function Tools() {
  8764. }
  8765. /**
  8766. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8767. * @param u defines the coordinate on X axis
  8768. * @param v defines the coordinate on Y axis
  8769. * @param width defines the width of the source data
  8770. * @param height defines the height of the source data
  8771. * @param pixels defines the source byte array
  8772. * @param color defines the output color
  8773. */
  8774. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8775. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8776. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8777. var position = (wrappedU + wrappedV * width) * 4;
  8778. color.r = pixels[position] / 255;
  8779. color.g = pixels[position + 1] / 255;
  8780. color.b = pixels[position + 2] / 255;
  8781. color.a = pixels[position + 3] / 255;
  8782. };
  8783. /**
  8784. * Interpolates between a and b via alpha
  8785. * @param a The lower value (returned when alpha = 0)
  8786. * @param b The upper value (returned when alpha = 1)
  8787. * @param alpha The interpolation-factor
  8788. * @return The mixed value
  8789. */
  8790. Tools.Mix = function (a, b, alpha) {
  8791. return a * (1 - alpha) + b * alpha;
  8792. };
  8793. Tools.Instantiate = function (className) {
  8794. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8795. return Tools.RegisteredExternalClasses[className];
  8796. }
  8797. var arr = className.split(".");
  8798. var fn = (window || this);
  8799. for (var i = 0, len = arr.length; i < len; i++) {
  8800. fn = fn[arr[i]];
  8801. }
  8802. if (typeof fn !== "function") {
  8803. return null;
  8804. }
  8805. return fn;
  8806. };
  8807. /**
  8808. * Provides a slice function that will work even on IE
  8809. * @param data defines the array to slice
  8810. * @param start defines the start of the data (optional)
  8811. * @param end defines the end of the data (optional)
  8812. * @returns the new sliced array
  8813. */
  8814. Tools.Slice = function (data, start, end) {
  8815. if (data.slice) {
  8816. return data.slice(start, end);
  8817. }
  8818. return Array.prototype.slice.call(data, start, end);
  8819. };
  8820. Tools.SetImmediate = function (action) {
  8821. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8822. window.setImmediate(action);
  8823. }
  8824. else {
  8825. setTimeout(action, 1);
  8826. }
  8827. };
  8828. Tools.IsExponentOfTwo = function (value) {
  8829. var count = 1;
  8830. do {
  8831. count *= 2;
  8832. } while (count < value);
  8833. return count === value;
  8834. };
  8835. /**
  8836. * Returns the nearest 32-bit single precision float representation of a Number
  8837. * @param value A Number. If the parameter is of a different type, it will get converted
  8838. * to a number or to NaN if it cannot be converted
  8839. * @returns number
  8840. */
  8841. Tools.FloatRound = function (value) {
  8842. if (Math.fround) {
  8843. return Math.fround(value);
  8844. }
  8845. return (Tools._tmpFloatArray[0] = value);
  8846. };
  8847. /**
  8848. * Find the next highest power of two.
  8849. * @param x Number to start search from.
  8850. * @return Next highest power of two.
  8851. */
  8852. Tools.CeilingPOT = function (x) {
  8853. x--;
  8854. x |= x >> 1;
  8855. x |= x >> 2;
  8856. x |= x >> 4;
  8857. x |= x >> 8;
  8858. x |= x >> 16;
  8859. x++;
  8860. return x;
  8861. };
  8862. /**
  8863. * Find the next lowest power of two.
  8864. * @param x Number to start search from.
  8865. * @return Next lowest power of two.
  8866. */
  8867. Tools.FloorPOT = function (x) {
  8868. x = x | (x >> 1);
  8869. x = x | (x >> 2);
  8870. x = x | (x >> 4);
  8871. x = x | (x >> 8);
  8872. x = x | (x >> 16);
  8873. return x - (x >> 1);
  8874. };
  8875. /**
  8876. * Find the nearest power of two.
  8877. * @param x Number to start search from.
  8878. * @return Next nearest power of two.
  8879. */
  8880. Tools.NearestPOT = function (x) {
  8881. var c = Tools.CeilingPOT(x);
  8882. var f = Tools.FloorPOT(x);
  8883. return (c - x) > (x - f) ? f : c;
  8884. };
  8885. Tools.GetExponentOfTwo = function (value, max, mode) {
  8886. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8887. var pot;
  8888. switch (mode) {
  8889. case BABYLON.Engine.SCALEMODE_FLOOR:
  8890. pot = Tools.FloorPOT(value);
  8891. break;
  8892. case BABYLON.Engine.SCALEMODE_NEAREST:
  8893. pot = Tools.NearestPOT(value);
  8894. break;
  8895. case BABYLON.Engine.SCALEMODE_CEILING:
  8896. default:
  8897. pot = Tools.CeilingPOT(value);
  8898. break;
  8899. }
  8900. return Math.min(pot, max);
  8901. };
  8902. Tools.GetFilename = function (path) {
  8903. var index = path.lastIndexOf("/");
  8904. if (index < 0)
  8905. return path;
  8906. return path.substring(index + 1);
  8907. };
  8908. /**
  8909. * Extracts the "folder" part of a path (everything before the filename).
  8910. * @param uri The URI to extract the info from
  8911. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8912. * @returns The "folder" part of the path
  8913. */
  8914. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8915. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8916. var index = uri.lastIndexOf("/");
  8917. if (index < 0) {
  8918. if (returnUnchangedIfNoSlash) {
  8919. return uri;
  8920. }
  8921. return "";
  8922. }
  8923. return uri.substring(0, index + 1);
  8924. };
  8925. Tools.GetDOMTextContent = function (element) {
  8926. var result = "";
  8927. var child = element.firstChild;
  8928. while (child) {
  8929. if (child.nodeType === 3) {
  8930. result += child.textContent;
  8931. }
  8932. child = child.nextSibling;
  8933. }
  8934. return result;
  8935. };
  8936. Tools.ToDegrees = function (angle) {
  8937. return angle * 180 / Math.PI;
  8938. };
  8939. Tools.ToRadians = function (angle) {
  8940. return angle * Math.PI / 180;
  8941. };
  8942. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8943. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8944. var output = "";
  8945. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8946. var i = 0;
  8947. var bytes = new Uint8Array(buffer);
  8948. while (i < bytes.length) {
  8949. chr1 = bytes[i++];
  8950. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8951. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8952. enc1 = chr1 >> 2;
  8953. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8954. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8955. enc4 = chr3 & 63;
  8956. if (isNaN(chr2)) {
  8957. enc3 = enc4 = 64;
  8958. }
  8959. else if (isNaN(chr3)) {
  8960. enc4 = 64;
  8961. }
  8962. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8963. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8964. }
  8965. return "data:image/png;base64," + output;
  8966. };
  8967. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8968. if (bias === void 0) { bias = null; }
  8969. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8970. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8971. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8972. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8973. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8974. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8975. }
  8976. if (bias) {
  8977. minimum.x -= minimum.x * bias.x + bias.y;
  8978. minimum.y -= minimum.y * bias.x + bias.y;
  8979. minimum.z -= minimum.z * bias.x + bias.y;
  8980. maximum.x += maximum.x * bias.x + bias.y;
  8981. maximum.y += maximum.y * bias.x + bias.y;
  8982. maximum.z += maximum.z * bias.x + bias.y;
  8983. }
  8984. return {
  8985. minimum: minimum,
  8986. maximum: maximum
  8987. };
  8988. };
  8989. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8990. if (bias === void 0) { bias = null; }
  8991. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8992. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8993. if (!stride) {
  8994. stride = 3;
  8995. }
  8996. for (var index = start; index < start + count; index++) {
  8997. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8998. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8999. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9000. }
  9001. if (bias) {
  9002. minimum.x -= minimum.x * bias.x + bias.y;
  9003. minimum.y -= minimum.y * bias.x + bias.y;
  9004. minimum.z -= minimum.z * bias.x + bias.y;
  9005. maximum.x += maximum.x * bias.x + bias.y;
  9006. maximum.y += maximum.y * bias.x + bias.y;
  9007. maximum.z += maximum.z * bias.x + bias.y;
  9008. }
  9009. return {
  9010. minimum: minimum,
  9011. maximum: maximum
  9012. };
  9013. };
  9014. Tools.Vector2ArrayFeeder = function (array) {
  9015. return function (index) {
  9016. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  9017. var length = isFloatArray ? array.length / 2 : array.length;
  9018. if (index >= length) {
  9019. return null;
  9020. }
  9021. if (isFloatArray) {
  9022. var fa = array;
  9023. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  9024. }
  9025. var a = array;
  9026. return a[index];
  9027. };
  9028. };
  9029. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9030. if (bias === void 0) { bias = null; }
  9031. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9032. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9033. var i = 0;
  9034. var cur = feeder(i++);
  9035. while (cur) {
  9036. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9037. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9038. cur = feeder(i++);
  9039. }
  9040. if (bias) {
  9041. minimum.x -= minimum.x * bias.x + bias.y;
  9042. minimum.y -= minimum.y * bias.x + bias.y;
  9043. maximum.x += maximum.x * bias.x + bias.y;
  9044. maximum.y += maximum.y * bias.x + bias.y;
  9045. }
  9046. return {
  9047. minimum: minimum,
  9048. maximum: maximum
  9049. };
  9050. };
  9051. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9052. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9053. return null;
  9054. return Array.isArray(obj) ? obj : [obj];
  9055. };
  9056. // Misc.
  9057. Tools.GetPointerPrefix = function () {
  9058. var eventPrefix = "pointer";
  9059. // Check if pointer events are supported
  9060. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9061. eventPrefix = "mouse";
  9062. }
  9063. return eventPrefix;
  9064. };
  9065. /**
  9066. * @param func - the function to be called
  9067. * @param requester - the object that will request the next frame. Falls back to window.
  9068. */
  9069. Tools.QueueNewFrame = function (func, requester) {
  9070. if (!Tools.IsWindowObjectExist()) {
  9071. return setTimeout(func, 16);
  9072. }
  9073. if (!requester) {
  9074. requester = window;
  9075. }
  9076. if (requester.requestAnimationFrame) {
  9077. return requester.requestAnimationFrame(func);
  9078. }
  9079. else if (requester.msRequestAnimationFrame) {
  9080. return requester.msRequestAnimationFrame(func);
  9081. }
  9082. else if (requester.webkitRequestAnimationFrame) {
  9083. return requester.webkitRequestAnimationFrame(func);
  9084. }
  9085. else if (requester.mozRequestAnimationFrame) {
  9086. return requester.mozRequestAnimationFrame(func);
  9087. }
  9088. else if (requester.oRequestAnimationFrame) {
  9089. return requester.oRequestAnimationFrame(func);
  9090. }
  9091. else {
  9092. return window.setTimeout(func, 16);
  9093. }
  9094. };
  9095. Tools.RequestFullscreen = function (element) {
  9096. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9097. if (!requestFunction)
  9098. return;
  9099. requestFunction.call(element);
  9100. };
  9101. Tools.ExitFullscreen = function () {
  9102. if (document.exitFullscreen) {
  9103. document.exitFullscreen();
  9104. }
  9105. else if (document.mozCancelFullScreen) {
  9106. document.mozCancelFullScreen();
  9107. }
  9108. else if (document.webkitCancelFullScreen) {
  9109. document.webkitCancelFullScreen();
  9110. }
  9111. else if (document.msCancelFullScreen) {
  9112. document.msCancelFullScreen();
  9113. }
  9114. };
  9115. Tools.SetCorsBehavior = function (url, element) {
  9116. if (url && url.indexOf("data:") === 0) {
  9117. return;
  9118. }
  9119. if (Tools.CorsBehavior) {
  9120. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9121. element.crossOrigin = Tools.CorsBehavior;
  9122. }
  9123. else {
  9124. var result = Tools.CorsBehavior(url);
  9125. if (result) {
  9126. element.crossOrigin = result;
  9127. }
  9128. }
  9129. }
  9130. };
  9131. // External files
  9132. Tools.CleanUrl = function (url) {
  9133. url = url.replace(/#/mg, "%23");
  9134. return url;
  9135. };
  9136. /**
  9137. * Loads an image as an HTMLImageElement.
  9138. * @param input url string, ArrayBuffer, or Blob to load
  9139. * @param onLoad callback called when the image successfully loads
  9140. * @param onError callback called when the image fails to load
  9141. * @param database database for caching
  9142. * @returns the HTMLImageElement of the loaded image
  9143. */
  9144. Tools.LoadImage = function (input, onLoad, onError, database) {
  9145. var url;
  9146. var usingObjectURL = false;
  9147. if (input instanceof ArrayBuffer) {
  9148. url = URL.createObjectURL(new Blob([input]));
  9149. usingObjectURL = true;
  9150. }
  9151. else if (input instanceof Blob) {
  9152. url = URL.createObjectURL(input);
  9153. usingObjectURL = true;
  9154. }
  9155. else {
  9156. url = Tools.CleanUrl(input);
  9157. url = Tools.PreprocessUrl(input);
  9158. }
  9159. var img = new Image();
  9160. Tools.SetCorsBehavior(url, img);
  9161. var loadHandler = function () {
  9162. if (usingObjectURL && img.src) {
  9163. URL.revokeObjectURL(img.src);
  9164. }
  9165. img.removeEventListener("load", loadHandler);
  9166. img.removeEventListener("error", errorHandler);
  9167. onLoad(img);
  9168. };
  9169. var errorHandler = function (err) {
  9170. if (usingObjectURL && img.src) {
  9171. URL.revokeObjectURL(img.src);
  9172. }
  9173. img.removeEventListener("load", loadHandler);
  9174. img.removeEventListener("error", errorHandler);
  9175. Tools.Error("Error while trying to load image: " + input);
  9176. if (onError) {
  9177. onError("Error while trying to load image: " + input, err);
  9178. }
  9179. };
  9180. img.addEventListener("load", loadHandler);
  9181. img.addEventListener("error", errorHandler);
  9182. var noIndexedDB = function () {
  9183. img.src = url;
  9184. };
  9185. var loadFromIndexedDB = function () {
  9186. if (database) {
  9187. database.loadImageFromDB(url, img);
  9188. }
  9189. };
  9190. //ANY database to do!
  9191. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9192. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9193. }
  9194. else {
  9195. if (url.indexOf("file:") !== -1) {
  9196. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9197. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9198. try {
  9199. var blobURL;
  9200. try {
  9201. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9202. }
  9203. catch (ex) {
  9204. // Chrome doesn't support oneTimeOnly parameter
  9205. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9206. }
  9207. img.src = blobURL;
  9208. usingObjectURL = true;
  9209. }
  9210. catch (e) {
  9211. img.src = "";
  9212. }
  9213. return img;
  9214. }
  9215. }
  9216. noIndexedDB();
  9217. }
  9218. return img;
  9219. };
  9220. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9221. url = Tools.CleanUrl(url);
  9222. url = Tools.PreprocessUrl(url);
  9223. // If file and file input are set
  9224. if (url.indexOf("file:") !== -1) {
  9225. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9226. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9227. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9228. }
  9229. }
  9230. var loadUrl = Tools.BaseUrl + url;
  9231. var aborted = false;
  9232. var fileRequest = {
  9233. onCompleteObservable: new BABYLON.Observable(),
  9234. abort: function () { return aborted = true; },
  9235. };
  9236. var requestFile = function () {
  9237. var request = new XMLHttpRequest();
  9238. var retryHandle = null;
  9239. fileRequest.abort = function () {
  9240. aborted = true;
  9241. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9242. request.abort();
  9243. }
  9244. if (retryHandle !== null) {
  9245. clearTimeout(retryHandle);
  9246. retryHandle = null;
  9247. }
  9248. };
  9249. var retryLoop = function (retryIndex) {
  9250. request.open('GET', loadUrl, true);
  9251. if (useArrayBuffer) {
  9252. request.responseType = "arraybuffer";
  9253. }
  9254. if (onProgress) {
  9255. request.addEventListener("progress", onProgress);
  9256. }
  9257. var onLoadEnd = function () {
  9258. request.removeEventListener("loadend", onLoadEnd);
  9259. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9260. fileRequest.onCompleteObservable.clear();
  9261. };
  9262. request.addEventListener("loadend", onLoadEnd);
  9263. var onReadyStateChange = function () {
  9264. if (aborted) {
  9265. return;
  9266. }
  9267. // In case of undefined state in some browsers.
  9268. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9269. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9270. request.removeEventListener("readystatechange", onReadyStateChange);
  9271. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9272. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9273. return;
  9274. }
  9275. var retryStrategy = Tools.DefaultRetryStrategy;
  9276. if (retryStrategy) {
  9277. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9278. if (waitTime !== -1) {
  9279. // Prevent the request from completing for retry.
  9280. request.removeEventListener("loadend", onLoadEnd);
  9281. request = new XMLHttpRequest();
  9282. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9283. return;
  9284. }
  9285. }
  9286. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9287. if (onError) {
  9288. onError(request, e);
  9289. }
  9290. else {
  9291. throw e;
  9292. }
  9293. }
  9294. };
  9295. request.addEventListener("readystatechange", onReadyStateChange);
  9296. request.send();
  9297. };
  9298. retryLoop(0);
  9299. };
  9300. // Caching all files
  9301. if (database && database.enableSceneOffline) {
  9302. var noIndexedDB_1 = function (request) {
  9303. if (request && request.status > 400) {
  9304. if (onError) {
  9305. onError(request);
  9306. }
  9307. }
  9308. else {
  9309. if (!aborted) {
  9310. requestFile();
  9311. }
  9312. }
  9313. };
  9314. var loadFromIndexedDB = function () {
  9315. // TODO: database needs to support aborting and should return a IFileRequest
  9316. if (aborted) {
  9317. return;
  9318. }
  9319. if (database) {
  9320. database.loadFileFromDB(url, function (data) {
  9321. if (!aborted) {
  9322. onSuccess(data);
  9323. }
  9324. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9325. }, onProgress ? function (event) {
  9326. if (!aborted) {
  9327. onProgress(event);
  9328. }
  9329. } : undefined, noIndexedDB_1, useArrayBuffer);
  9330. }
  9331. };
  9332. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9333. }
  9334. else {
  9335. requestFile();
  9336. }
  9337. return fileRequest;
  9338. };
  9339. /**
  9340. * Load a script (identified by an url). When the url returns, the
  9341. * content of this file is added into a new script element, attached to the DOM (body element)
  9342. */
  9343. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9344. if (!Tools.IsWindowObjectExist()) {
  9345. return;
  9346. }
  9347. var head = document.getElementsByTagName('head')[0];
  9348. var script = document.createElement('script');
  9349. script.type = 'text/javascript';
  9350. script.src = scriptUrl;
  9351. script.onload = function () {
  9352. if (onSuccess) {
  9353. onSuccess();
  9354. }
  9355. };
  9356. script.onerror = function (e) {
  9357. if (onError) {
  9358. onError("Unable to load script '" + scriptUrl + "'", e);
  9359. }
  9360. };
  9361. head.appendChild(script);
  9362. };
  9363. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9364. var reader = new FileReader();
  9365. var request = {
  9366. onCompleteObservable: new BABYLON.Observable(),
  9367. abort: function () { return reader.abort(); },
  9368. };
  9369. reader.onloadend = function (e) {
  9370. request.onCompleteObservable.notifyObservers(request);
  9371. };
  9372. reader.onload = function (e) {
  9373. //target doesn't have result from ts 1.3
  9374. callback(e.target['result']);
  9375. };
  9376. reader.onprogress = progressCallback;
  9377. reader.readAsDataURL(fileToLoad);
  9378. return request;
  9379. };
  9380. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9381. var reader = new FileReader();
  9382. var request = {
  9383. onCompleteObservable: new BABYLON.Observable(),
  9384. abort: function () { return reader.abort(); },
  9385. };
  9386. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9387. reader.onerror = function (e) {
  9388. Tools.Log("Error while reading file: " + fileToLoad.name);
  9389. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9390. };
  9391. reader.onload = function (e) {
  9392. //target doesn't have result from ts 1.3
  9393. callback(e.target['result']);
  9394. };
  9395. if (progressCallBack) {
  9396. reader.onprogress = progressCallBack;
  9397. }
  9398. if (!useArrayBuffer) {
  9399. // Asynchronous read
  9400. reader.readAsText(fileToLoad);
  9401. }
  9402. else {
  9403. reader.readAsArrayBuffer(fileToLoad);
  9404. }
  9405. return request;
  9406. };
  9407. //returns a downloadable url to a file content.
  9408. Tools.FileAsURL = function (content) {
  9409. var fileBlob = new Blob([content]);
  9410. var url = window.URL || window.webkitURL;
  9411. var link = url.createObjectURL(fileBlob);
  9412. return link;
  9413. };
  9414. // Misc.
  9415. Tools.Format = function (value, decimals) {
  9416. if (decimals === void 0) { decimals = 2; }
  9417. return value.toFixed(decimals);
  9418. };
  9419. Tools.CheckExtends = function (v, min, max) {
  9420. if (v.x < min.x)
  9421. min.x = v.x;
  9422. if (v.y < min.y)
  9423. min.y = v.y;
  9424. if (v.z < min.z)
  9425. min.z = v.z;
  9426. if (v.x > max.x)
  9427. max.x = v.x;
  9428. if (v.y > max.y)
  9429. max.y = v.y;
  9430. if (v.z > max.z)
  9431. max.z = v.z;
  9432. };
  9433. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9434. for (var prop in source) {
  9435. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9436. continue;
  9437. }
  9438. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9439. continue;
  9440. }
  9441. var sourceValue = source[prop];
  9442. var typeOfSourceValue = typeof sourceValue;
  9443. if (typeOfSourceValue === "function") {
  9444. continue;
  9445. }
  9446. try {
  9447. if (typeOfSourceValue === "object") {
  9448. if (sourceValue instanceof Array) {
  9449. destination[prop] = [];
  9450. if (sourceValue.length > 0) {
  9451. if (typeof sourceValue[0] == "object") {
  9452. for (var index = 0; index < sourceValue.length; index++) {
  9453. var clonedValue = cloneValue(sourceValue[index], destination);
  9454. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9455. destination[prop].push(clonedValue);
  9456. }
  9457. }
  9458. }
  9459. else {
  9460. destination[prop] = sourceValue.slice(0);
  9461. }
  9462. }
  9463. }
  9464. else {
  9465. destination[prop] = cloneValue(sourceValue, destination);
  9466. }
  9467. }
  9468. else {
  9469. destination[prop] = sourceValue;
  9470. }
  9471. }
  9472. catch (e) {
  9473. // Just ignore error (it could be because of a read-only property)
  9474. }
  9475. }
  9476. };
  9477. Tools.IsEmpty = function (obj) {
  9478. for (var i in obj) {
  9479. if (obj.hasOwnProperty(i)) {
  9480. return false;
  9481. }
  9482. }
  9483. return true;
  9484. };
  9485. Tools.RegisterTopRootEvents = function (events) {
  9486. for (var index = 0; index < events.length; index++) {
  9487. var event = events[index];
  9488. window.addEventListener(event.name, event.handler, false);
  9489. try {
  9490. if (window.parent) {
  9491. window.parent.addEventListener(event.name, event.handler, false);
  9492. }
  9493. }
  9494. catch (e) {
  9495. // Silently fails...
  9496. }
  9497. }
  9498. };
  9499. Tools.UnregisterTopRootEvents = function (events) {
  9500. for (var index = 0; index < events.length; index++) {
  9501. var event = events[index];
  9502. window.removeEventListener(event.name, event.handler);
  9503. try {
  9504. if (window.parent) {
  9505. window.parent.removeEventListener(event.name, event.handler);
  9506. }
  9507. }
  9508. catch (e) {
  9509. // Silently fails...
  9510. }
  9511. }
  9512. };
  9513. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9514. if (mimeType === void 0) { mimeType = "image/png"; }
  9515. // Read the contents of the framebuffer
  9516. var numberOfChannelsByLine = width * 4;
  9517. var halfHeight = height / 2;
  9518. //Reading datas from WebGL
  9519. var data = engine.readPixels(0, 0, width, height);
  9520. //To flip image on Y axis.
  9521. for (var i = 0; i < halfHeight; i++) {
  9522. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9523. var currentCell = j + i * numberOfChannelsByLine;
  9524. var targetLine = height - i - 1;
  9525. var targetCell = j + targetLine * numberOfChannelsByLine;
  9526. var temp = data[currentCell];
  9527. data[currentCell] = data[targetCell];
  9528. data[targetCell] = temp;
  9529. }
  9530. }
  9531. // Create a 2D canvas to store the result
  9532. if (!screenshotCanvas) {
  9533. screenshotCanvas = document.createElement('canvas');
  9534. }
  9535. screenshotCanvas.width = width;
  9536. screenshotCanvas.height = height;
  9537. var context = screenshotCanvas.getContext('2d');
  9538. if (context) {
  9539. // Copy the pixels to a 2D canvas
  9540. var imageData = context.createImageData(width, height);
  9541. var castData = (imageData.data);
  9542. castData.set(data);
  9543. context.putImageData(imageData, 0, 0);
  9544. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9545. }
  9546. };
  9547. /**
  9548. * Converts the canvas data to blob.
  9549. * This acts as a polyfill for browsers not supporting the to blob function.
  9550. * @param canvas Defines the canvas to extract the data from
  9551. * @param successCallback Defines the callback triggered once the data are available
  9552. * @param mimeType Defines the mime type of the result
  9553. */
  9554. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9555. if (mimeType === void 0) { mimeType = "image/png"; }
  9556. // We need HTMLCanvasElement.toBlob for HD screenshots
  9557. if (!canvas.toBlob) {
  9558. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9559. canvas.toBlob = function (callback, type, quality) {
  9560. var _this = this;
  9561. setTimeout(function () {
  9562. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9563. for (var i = 0; i < len; i++) {
  9564. arr[i] = binStr.charCodeAt(i);
  9565. }
  9566. callback(new Blob([arr]));
  9567. });
  9568. };
  9569. }
  9570. canvas.toBlob(function (blob) {
  9571. successCallback(blob);
  9572. }, mimeType);
  9573. };
  9574. /**
  9575. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9576. * @param successCallback Defines the callback triggered once the data are available
  9577. * @param mimeType Defines the mime type of the result
  9578. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9579. */
  9580. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9581. if (mimeType === void 0) { mimeType = "image/png"; }
  9582. if (successCallback) {
  9583. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9584. successCallback(base64Image);
  9585. }
  9586. else {
  9587. this.ToBlob(screenshotCanvas, function (blob) {
  9588. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9589. if (("download" in document.createElement("a"))) {
  9590. if (!fileName) {
  9591. var date = new Date();
  9592. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9593. fileName = "screenshot_" + stringDate + ".png";
  9594. }
  9595. Tools.Download(blob, fileName);
  9596. }
  9597. else {
  9598. var url = URL.createObjectURL(blob);
  9599. var newWindow = window.open("");
  9600. if (!newWindow)
  9601. return;
  9602. var img = newWindow.document.createElement("img");
  9603. img.onload = function () {
  9604. // no longer need to read the blob so it's revoked
  9605. URL.revokeObjectURL(url);
  9606. };
  9607. img.src = url;
  9608. newWindow.document.body.appendChild(img);
  9609. }
  9610. }, mimeType);
  9611. }
  9612. };
  9613. /**
  9614. * Downloads a blob in the browser
  9615. * @param blob defines the blob to download
  9616. * @param fileName defines the name of the downloaded file
  9617. */
  9618. Tools.Download = function (blob, fileName) {
  9619. if (navigator && navigator.msSaveBlob) {
  9620. navigator.msSaveBlob(blob, fileName);
  9621. return;
  9622. }
  9623. var url = window.URL.createObjectURL(blob);
  9624. var a = document.createElement("a");
  9625. document.body.appendChild(a);
  9626. a.style.display = "none";
  9627. a.href = url;
  9628. a.download = fileName;
  9629. a.addEventListener("click", function () {
  9630. if (a.parentElement) {
  9631. a.parentElement.removeChild(a);
  9632. }
  9633. });
  9634. a.click();
  9635. window.URL.revokeObjectURL(url);
  9636. };
  9637. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9638. if (mimeType === void 0) { mimeType = "image/png"; }
  9639. var width;
  9640. var height;
  9641. // If a precision value is specified
  9642. if (size.precision) {
  9643. width = Math.round(engine.getRenderWidth() * size.precision);
  9644. height = Math.round(width / engine.getAspectRatio(camera));
  9645. }
  9646. else if (size.width && size.height) {
  9647. width = size.width;
  9648. height = size.height;
  9649. }
  9650. //If passing only width, computing height to keep display canvas ratio.
  9651. else if (size.width && !size.height) {
  9652. width = size.width;
  9653. height = Math.round(width / engine.getAspectRatio(camera));
  9654. }
  9655. //If passing only height, computing width to keep display canvas ratio.
  9656. else if (size.height && !size.width) {
  9657. height = size.height;
  9658. width = Math.round(height * engine.getAspectRatio(camera));
  9659. }
  9660. //Assuming here that "size" parameter is a number
  9661. else if (!isNaN(size)) {
  9662. height = size;
  9663. width = size;
  9664. }
  9665. else {
  9666. Tools.Error("Invalid 'size' parameter !");
  9667. return;
  9668. }
  9669. if (!screenshotCanvas) {
  9670. screenshotCanvas = document.createElement('canvas');
  9671. }
  9672. screenshotCanvas.width = width;
  9673. screenshotCanvas.height = height;
  9674. var renderContext = screenshotCanvas.getContext("2d");
  9675. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9676. var newWidth = width;
  9677. var newHeight = newWidth / ratio;
  9678. if (newHeight > height) {
  9679. newHeight = height;
  9680. newWidth = newHeight * ratio;
  9681. }
  9682. var offsetX = Math.max(0, width - newWidth) / 2;
  9683. var offsetY = Math.max(0, height - newHeight) / 2;
  9684. var renderingCanvas = engine.getRenderingCanvas();
  9685. if (renderContext && renderingCanvas) {
  9686. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9687. }
  9688. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9689. };
  9690. /**
  9691. * Generates an image screenshot from the specified camera.
  9692. *
  9693. * @param engine The engine to use for rendering
  9694. * @param camera The camera to use for rendering
  9695. * @param size This parameter can be set to a single number or to an object with the
  9696. * following (optional) properties: precision, width, height. If a single number is passed,
  9697. * it will be used for both width and height. If an object is passed, the screenshot size
  9698. * will be derived from the parameters. The precision property is a multiplier allowing
  9699. * rendering at a higher or lower resolution.
  9700. * @param successCallback The callback receives a single parameter which contains the
  9701. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9702. * src parameter of an <img> to display it.
  9703. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9704. * Check your browser for supported MIME types.
  9705. * @param samples Texture samples (default: 1)
  9706. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9707. * @param fileName A name for for the downloaded file.
  9708. * @constructor
  9709. */
  9710. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9711. if (mimeType === void 0) { mimeType = "image/png"; }
  9712. if (samples === void 0) { samples = 1; }
  9713. if (antialiasing === void 0) { antialiasing = false; }
  9714. var width;
  9715. var height;
  9716. //If a precision value is specified
  9717. if (size.precision) {
  9718. width = Math.round(engine.getRenderWidth() * size.precision);
  9719. height = Math.round(width / engine.getAspectRatio(camera));
  9720. size = { width: width, height: height };
  9721. }
  9722. else if (size.width && size.height) {
  9723. width = size.width;
  9724. height = size.height;
  9725. }
  9726. //If passing only width, computing height to keep display canvas ratio.
  9727. else if (size.width && !size.height) {
  9728. width = size.width;
  9729. height = Math.round(width / engine.getAspectRatio(camera));
  9730. size = { width: width, height: height };
  9731. }
  9732. //If passing only height, computing width to keep display canvas ratio.
  9733. else if (size.height && !size.width) {
  9734. height = size.height;
  9735. width = Math.round(height * engine.getAspectRatio(camera));
  9736. size = { width: width, height: height };
  9737. }
  9738. //Assuming here that "size" parameter is a number
  9739. else if (!isNaN(size)) {
  9740. height = size;
  9741. width = size;
  9742. }
  9743. else {
  9744. Tools.Error("Invalid 'size' parameter !");
  9745. return;
  9746. }
  9747. var scene = camera.getScene();
  9748. var previousCamera = null;
  9749. if (scene.activeCamera !== camera) {
  9750. previousCamera = scene.activeCamera;
  9751. scene.activeCamera = camera;
  9752. }
  9753. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9754. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9755. texture.renderList = null;
  9756. texture.samples = samples;
  9757. if (antialiasing) {
  9758. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9759. }
  9760. texture.onAfterRenderObservable.add(function () {
  9761. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9762. });
  9763. scene.incrementRenderId();
  9764. scene.resetCachedMaterial();
  9765. texture.render(true);
  9766. texture.dispose();
  9767. if (previousCamera) {
  9768. scene.activeCamera = previousCamera;
  9769. }
  9770. camera.getProjectionMatrix(true); // Force cache refresh;
  9771. };
  9772. // XHR response validator for local file scenario
  9773. Tools.ValidateXHRData = function (xhr, dataType) {
  9774. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9775. if (dataType === void 0) { dataType = 7; }
  9776. try {
  9777. if (dataType & 1) {
  9778. if (xhr.responseText && xhr.responseText.length > 0) {
  9779. return true;
  9780. }
  9781. else if (dataType === 1) {
  9782. return false;
  9783. }
  9784. }
  9785. if (dataType & 2) {
  9786. // Check header width and height since there is no "TGA" magic number
  9787. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9788. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9789. return true;
  9790. }
  9791. else if (dataType === 2) {
  9792. return false;
  9793. }
  9794. }
  9795. if (dataType & 4) {
  9796. // Check for the "DDS" magic number
  9797. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9798. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9799. return true;
  9800. }
  9801. else {
  9802. return false;
  9803. }
  9804. }
  9805. }
  9806. catch (e) {
  9807. // Global protection
  9808. }
  9809. return false;
  9810. };
  9811. /**
  9812. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9813. * Be aware Math.random() could cause collisions, but:
  9814. * "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"
  9815. */
  9816. Tools.RandomId = function () {
  9817. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9818. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9819. return v.toString(16);
  9820. });
  9821. };
  9822. /**
  9823. * Test if the given uri is a base64 string.
  9824. * @param uri The uri to test
  9825. * @return True if the uri is a base64 string or false otherwise.
  9826. */
  9827. Tools.IsBase64 = function (uri) {
  9828. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9829. };
  9830. /**
  9831. * Decode the given base64 uri.
  9832. * @param uri The uri to decode
  9833. * @return The decoded base64 data.
  9834. */
  9835. Tools.DecodeBase64 = function (uri) {
  9836. var decodedString = atob(uri.split(",")[1]);
  9837. var bufferLength = decodedString.length;
  9838. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9839. for (var i = 0; i < bufferLength; i++) {
  9840. bufferView[i] = decodedString.charCodeAt(i);
  9841. }
  9842. return bufferView.buffer;
  9843. };
  9844. Object.defineProperty(Tools, "NoneLogLevel", {
  9845. get: function () {
  9846. return Tools._NoneLogLevel;
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Object.defineProperty(Tools, "MessageLogLevel", {
  9852. get: function () {
  9853. return Tools._MessageLogLevel;
  9854. },
  9855. enumerable: true,
  9856. configurable: true
  9857. });
  9858. Object.defineProperty(Tools, "WarningLogLevel", {
  9859. get: function () {
  9860. return Tools._WarningLogLevel;
  9861. },
  9862. enumerable: true,
  9863. configurable: true
  9864. });
  9865. Object.defineProperty(Tools, "ErrorLogLevel", {
  9866. get: function () {
  9867. return Tools._ErrorLogLevel;
  9868. },
  9869. enumerable: true,
  9870. configurable: true
  9871. });
  9872. Object.defineProperty(Tools, "AllLogLevel", {
  9873. get: function () {
  9874. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9875. },
  9876. enumerable: true,
  9877. configurable: true
  9878. });
  9879. Tools._AddLogEntry = function (entry) {
  9880. Tools._LogCache = entry + Tools._LogCache;
  9881. if (Tools.OnNewCacheEntry) {
  9882. Tools.OnNewCacheEntry(entry);
  9883. }
  9884. };
  9885. Tools._FormatMessage = function (message) {
  9886. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9887. var date = new Date();
  9888. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9889. };
  9890. Tools._LogDisabled = function (message) {
  9891. // nothing to do
  9892. };
  9893. Tools._LogEnabled = function (message) {
  9894. var formattedMessage = Tools._FormatMessage(message);
  9895. console.log("BJS - " + formattedMessage);
  9896. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9897. Tools._AddLogEntry(entry);
  9898. };
  9899. Tools._WarnDisabled = function (message) {
  9900. // nothing to do
  9901. };
  9902. Tools._WarnEnabled = function (message) {
  9903. var formattedMessage = Tools._FormatMessage(message);
  9904. console.warn("BJS - " + formattedMessage);
  9905. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9906. Tools._AddLogEntry(entry);
  9907. };
  9908. Tools._ErrorDisabled = function (message) {
  9909. // nothing to do
  9910. };
  9911. Tools._ErrorEnabled = function (message) {
  9912. Tools.errorsCount++;
  9913. var formattedMessage = Tools._FormatMessage(message);
  9914. console.error("BJS - " + formattedMessage);
  9915. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9916. Tools._AddLogEntry(entry);
  9917. };
  9918. Object.defineProperty(Tools, "LogCache", {
  9919. get: function () {
  9920. return Tools._LogCache;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Tools.ClearLogCache = function () {
  9926. Tools._LogCache = "";
  9927. Tools.errorsCount = 0;
  9928. };
  9929. Object.defineProperty(Tools, "LogLevels", {
  9930. set: function (level) {
  9931. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9932. Tools.Log = Tools._LogEnabled;
  9933. }
  9934. else {
  9935. Tools.Log = Tools._LogDisabled;
  9936. }
  9937. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9938. Tools.Warn = Tools._WarnEnabled;
  9939. }
  9940. else {
  9941. Tools.Warn = Tools._WarnDisabled;
  9942. }
  9943. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9944. Tools.Error = Tools._ErrorEnabled;
  9945. }
  9946. else {
  9947. Tools.Error = Tools._ErrorDisabled;
  9948. }
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. /**
  9954. * Check if the loaded document was accessed via `file:`-Protocol.
  9955. * @returns boolean
  9956. */
  9957. Tools.IsFileURL = function () {
  9958. return location.protocol === "file:";
  9959. };
  9960. Tools.IsWindowObjectExist = function () {
  9961. return (typeof window) !== "undefined";
  9962. };
  9963. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9964. get: function () {
  9965. return Tools._PerformanceNoneLogLevel;
  9966. },
  9967. enumerable: true,
  9968. configurable: true
  9969. });
  9970. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9971. get: function () {
  9972. return Tools._PerformanceUserMarkLogLevel;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9978. get: function () {
  9979. return Tools._PerformanceConsoleLogLevel;
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9985. set: function (level) {
  9986. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9987. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9988. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9989. return;
  9990. }
  9991. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9992. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9993. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9994. return;
  9995. }
  9996. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9997. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10003. };
  10004. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10005. };
  10006. Tools._StartUserMark = function (counterName, condition) {
  10007. if (condition === void 0) { condition = true; }
  10008. if (!Tools._performance) {
  10009. if (!Tools.IsWindowObjectExist()) {
  10010. return;
  10011. }
  10012. Tools._performance = window.performance;
  10013. }
  10014. if (!condition || !Tools._performance.mark) {
  10015. return;
  10016. }
  10017. Tools._performance.mark(counterName + "-Begin");
  10018. };
  10019. Tools._EndUserMark = function (counterName, condition) {
  10020. if (condition === void 0) { condition = true; }
  10021. if (!condition || !Tools._performance.mark) {
  10022. return;
  10023. }
  10024. Tools._performance.mark(counterName + "-End");
  10025. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10026. };
  10027. Tools._StartPerformanceConsole = function (counterName, condition) {
  10028. if (condition === void 0) { condition = true; }
  10029. if (!condition) {
  10030. return;
  10031. }
  10032. Tools._StartUserMark(counterName, condition);
  10033. if (console.time) {
  10034. console.time(counterName);
  10035. }
  10036. };
  10037. Tools._EndPerformanceConsole = function (counterName, condition) {
  10038. if (condition === void 0) { condition = true; }
  10039. if (!condition) {
  10040. return;
  10041. }
  10042. Tools._EndUserMark(counterName, condition);
  10043. if (console.time) {
  10044. console.timeEnd(counterName);
  10045. }
  10046. };
  10047. Object.defineProperty(Tools, "Now", {
  10048. get: function () {
  10049. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10050. return window.performance.now();
  10051. }
  10052. return Date.now();
  10053. },
  10054. enumerable: true,
  10055. configurable: true
  10056. });
  10057. /**
  10058. * This method will return the name of the class used to create the instance of the given object.
  10059. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10060. * @param object the object to get the class name from
  10061. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10062. */
  10063. Tools.GetClassName = function (object, isType) {
  10064. if (isType === void 0) { isType = false; }
  10065. var name = null;
  10066. if (!isType && object.getClassName) {
  10067. name = object.getClassName();
  10068. }
  10069. else {
  10070. if (object instanceof Object) {
  10071. var classObj = isType ? object : Object.getPrototypeOf(object);
  10072. name = classObj.constructor["__bjsclassName__"];
  10073. }
  10074. if (!name) {
  10075. name = typeof object;
  10076. }
  10077. }
  10078. return name;
  10079. };
  10080. Tools.First = function (array, predicate) {
  10081. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10082. var el = array_1[_i];
  10083. if (predicate(el)) {
  10084. return el;
  10085. }
  10086. }
  10087. return null;
  10088. };
  10089. /**
  10090. * This method will return the name of the full name of the class, including its owning module (if any).
  10091. * 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).
  10092. * @param object the object to get the class name from
  10093. * @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.
  10094. */
  10095. Tools.getFullClassName = function (object, isType) {
  10096. if (isType === void 0) { isType = false; }
  10097. var className = null;
  10098. var moduleName = null;
  10099. if (!isType && object.getClassName) {
  10100. className = object.getClassName();
  10101. }
  10102. else {
  10103. if (object instanceof Object) {
  10104. var classObj = isType ? object : Object.getPrototypeOf(object);
  10105. className = classObj.constructor["__bjsclassName__"];
  10106. moduleName = classObj.constructor["__bjsmoduleName__"];
  10107. }
  10108. if (!className) {
  10109. className = typeof object;
  10110. }
  10111. }
  10112. if (!className) {
  10113. return null;
  10114. }
  10115. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10116. };
  10117. /**
  10118. * 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.
  10119. * @param array
  10120. */
  10121. Tools.arrayOrStringFeeder = function (array) {
  10122. return function (index) {
  10123. if (index >= array.length) {
  10124. return null;
  10125. }
  10126. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10127. if (val && val.getHashCode) {
  10128. val = val.getHashCode();
  10129. }
  10130. if (typeof val === "string") {
  10131. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10132. }
  10133. return val;
  10134. };
  10135. };
  10136. /**
  10137. * Compute the hashCode of a stream of number
  10138. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10139. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10140. * @return the hash code computed
  10141. */
  10142. Tools.hashCodeFromStream = function (feeder) {
  10143. // Based from here: http://stackoverflow.com/a/7616484/802124
  10144. var hash = 0;
  10145. var index = 0;
  10146. var chr = feeder(index++);
  10147. while (chr != null) {
  10148. hash = ((hash << 5) - hash) + chr;
  10149. hash |= 0; // Convert to 32bit integer
  10150. chr = feeder(index++);
  10151. }
  10152. return hash;
  10153. };
  10154. /**
  10155. * Returns a promise that resolves after the given amount of time.
  10156. * @param delay Number of milliseconds to delay
  10157. * @returns Promise that resolves after the given amount of time
  10158. */
  10159. Tools.DelayAsync = function (delay) {
  10160. return new Promise(function (resolve) {
  10161. setTimeout(function () {
  10162. resolve();
  10163. }, delay);
  10164. });
  10165. };
  10166. /**
  10167. * Gets the current gradient from an array of IValueGradient
  10168. * @param ratio defines the current ratio to get
  10169. * @param gradients defines the array of IValueGradient
  10170. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10171. */
  10172. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10173. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10174. var currentGradient = gradients[gradientIndex];
  10175. var nextGradient = gradients[gradientIndex + 1];
  10176. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10177. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10178. updateFunc(currentGradient, nextGradient, scale);
  10179. return;
  10180. }
  10181. }
  10182. // Use last index if over
  10183. var lastIndex = gradients.length - 1;
  10184. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10185. };
  10186. Tools.BaseUrl = "";
  10187. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10188. /**
  10189. * Default behaviour for cors in the application.
  10190. * It can be a string if the expected behavior is identical in the entire app.
  10191. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10192. */
  10193. Tools.CorsBehavior = "anonymous";
  10194. Tools.UseFallbackTexture = true;
  10195. /**
  10196. * Use this object to register external classes like custom textures or material
  10197. * to allow the laoders to instantiate them
  10198. */
  10199. Tools.RegisteredExternalClasses = {};
  10200. // Used in case of a texture loading problem
  10201. 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";
  10202. Tools._tmpFloatArray = new Float32Array(1);
  10203. Tools.PreprocessUrl = function (url) {
  10204. return url;
  10205. };
  10206. // Logs
  10207. Tools._NoneLogLevel = 0;
  10208. Tools._MessageLogLevel = 1;
  10209. Tools._WarningLogLevel = 2;
  10210. Tools._ErrorLogLevel = 4;
  10211. Tools._LogCache = "";
  10212. Tools.errorsCount = 0;
  10213. Tools.Log = Tools._LogEnabled;
  10214. Tools.Warn = Tools._WarnEnabled;
  10215. Tools.Error = Tools._ErrorEnabled;
  10216. // Performances
  10217. Tools._PerformanceNoneLogLevel = 0;
  10218. Tools._PerformanceUserMarkLogLevel = 1;
  10219. Tools._PerformanceConsoleLogLevel = 2;
  10220. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10221. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10222. return Tools;
  10223. }());
  10224. BABYLON.Tools = Tools;
  10225. /**
  10226. * This class is used to track a performance counter which is number based.
  10227. * The user has access to many properties which give statistics of different nature
  10228. *
  10229. * The implementer can track two kinds of Performance Counter: time and count
  10230. * 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.
  10231. * 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.
  10232. */
  10233. var PerfCounter = /** @class */ (function () {
  10234. function PerfCounter() {
  10235. this._startMonitoringTime = 0;
  10236. this._min = 0;
  10237. this._max = 0;
  10238. this._average = 0;
  10239. this._lastSecAverage = 0;
  10240. this._current = 0;
  10241. this._totalValueCount = 0;
  10242. this._totalAccumulated = 0;
  10243. this._lastSecAccumulated = 0;
  10244. this._lastSecTime = 0;
  10245. this._lastSecValueCount = 0;
  10246. }
  10247. Object.defineProperty(PerfCounter.prototype, "min", {
  10248. /**
  10249. * Returns the smallest value ever
  10250. */
  10251. get: function () {
  10252. return this._min;
  10253. },
  10254. enumerable: true,
  10255. configurable: true
  10256. });
  10257. Object.defineProperty(PerfCounter.prototype, "max", {
  10258. /**
  10259. * Returns the biggest value ever
  10260. */
  10261. get: function () {
  10262. return this._max;
  10263. },
  10264. enumerable: true,
  10265. configurable: true
  10266. });
  10267. Object.defineProperty(PerfCounter.prototype, "average", {
  10268. /**
  10269. * Returns the average value since the performance counter is running
  10270. */
  10271. get: function () {
  10272. return this._average;
  10273. },
  10274. enumerable: true,
  10275. configurable: true
  10276. });
  10277. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10278. /**
  10279. * Returns the average value of the last second the counter was monitored
  10280. */
  10281. get: function () {
  10282. return this._lastSecAverage;
  10283. },
  10284. enumerable: true,
  10285. configurable: true
  10286. });
  10287. Object.defineProperty(PerfCounter.prototype, "current", {
  10288. /**
  10289. * Returns the current value
  10290. */
  10291. get: function () {
  10292. return this._current;
  10293. },
  10294. enumerable: true,
  10295. configurable: true
  10296. });
  10297. Object.defineProperty(PerfCounter.prototype, "total", {
  10298. get: function () {
  10299. return this._totalAccumulated;
  10300. },
  10301. enumerable: true,
  10302. configurable: true
  10303. });
  10304. Object.defineProperty(PerfCounter.prototype, "count", {
  10305. get: function () {
  10306. return this._totalValueCount;
  10307. },
  10308. enumerable: true,
  10309. configurable: true
  10310. });
  10311. /**
  10312. * Call this method to start monitoring a new frame.
  10313. * 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.
  10314. */
  10315. PerfCounter.prototype.fetchNewFrame = function () {
  10316. this._totalValueCount++;
  10317. this._current = 0;
  10318. this._lastSecValueCount++;
  10319. };
  10320. /**
  10321. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10322. * @param newCount the count value to add to the monitored count
  10323. * @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.
  10324. */
  10325. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10326. if (!PerfCounter.Enabled) {
  10327. return;
  10328. }
  10329. this._current += newCount;
  10330. if (fetchResult) {
  10331. this._fetchResult();
  10332. }
  10333. };
  10334. /**
  10335. * Start monitoring this performance counter
  10336. */
  10337. PerfCounter.prototype.beginMonitoring = function () {
  10338. if (!PerfCounter.Enabled) {
  10339. return;
  10340. }
  10341. this._startMonitoringTime = Tools.Now;
  10342. };
  10343. /**
  10344. * Compute the time lapsed since the previous beginMonitoring() call.
  10345. * @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
  10346. */
  10347. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10348. if (newFrame === void 0) { newFrame = true; }
  10349. if (!PerfCounter.Enabled) {
  10350. return;
  10351. }
  10352. if (newFrame) {
  10353. this.fetchNewFrame();
  10354. }
  10355. var currentTime = Tools.Now;
  10356. this._current = currentTime - this._startMonitoringTime;
  10357. if (newFrame) {
  10358. this._fetchResult();
  10359. }
  10360. };
  10361. PerfCounter.prototype._fetchResult = function () {
  10362. this._totalAccumulated += this._current;
  10363. this._lastSecAccumulated += this._current;
  10364. // Min/Max update
  10365. this._min = Math.min(this._min, this._current);
  10366. this._max = Math.max(this._max, this._current);
  10367. this._average = this._totalAccumulated / this._totalValueCount;
  10368. // Reset last sec?
  10369. var now = Tools.Now;
  10370. if ((now - this._lastSecTime) > 1000) {
  10371. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10372. this._lastSecTime = now;
  10373. this._lastSecAccumulated = 0;
  10374. this._lastSecValueCount = 0;
  10375. }
  10376. };
  10377. PerfCounter.Enabled = true;
  10378. return PerfCounter;
  10379. }());
  10380. BABYLON.PerfCounter = PerfCounter;
  10381. /**
  10382. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10383. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10384. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10385. * @param name The name of the class, case should be preserved
  10386. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10387. */
  10388. function className(name, module) {
  10389. return function (target) {
  10390. target["__bjsclassName__"] = name;
  10391. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10392. };
  10393. }
  10394. BABYLON.className = className;
  10395. /**
  10396. * An implementation of a loop for asynchronous functions.
  10397. */
  10398. var AsyncLoop = /** @class */ (function () {
  10399. /**
  10400. * Constroctor.
  10401. * @param iterations the number of iterations.
  10402. * @param _fn the function to run each iteration
  10403. * @param _successCallback the callback that will be called upon succesful execution
  10404. * @param offset starting offset.
  10405. */
  10406. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10407. if (offset === void 0) { offset = 0; }
  10408. this.iterations = iterations;
  10409. this._fn = _fn;
  10410. this._successCallback = _successCallback;
  10411. this.index = offset - 1;
  10412. this._done = false;
  10413. }
  10414. /**
  10415. * Execute the next iteration. Must be called after the last iteration was finished.
  10416. */
  10417. AsyncLoop.prototype.executeNext = function () {
  10418. if (!this._done) {
  10419. if (this.index + 1 < this.iterations) {
  10420. ++this.index;
  10421. this._fn(this);
  10422. }
  10423. else {
  10424. this.breakLoop();
  10425. }
  10426. }
  10427. };
  10428. /**
  10429. * Break the loop and run the success callback.
  10430. */
  10431. AsyncLoop.prototype.breakLoop = function () {
  10432. this._done = true;
  10433. this._successCallback();
  10434. };
  10435. /**
  10436. * Helper function
  10437. */
  10438. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10439. if (offset === void 0) { offset = 0; }
  10440. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10441. loop.executeNext();
  10442. return loop;
  10443. };
  10444. /**
  10445. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10446. * @param iterations total number of iterations
  10447. * @param syncedIterations number of synchronous iterations in each async iteration.
  10448. * @param fn the function to call each iteration.
  10449. * @param callback a success call back that will be called when iterating stops.
  10450. * @param breakFunction a break condition (optional)
  10451. * @param timeout timeout settings for the setTimeout function. default - 0.
  10452. * @constructor
  10453. */
  10454. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10455. if (timeout === void 0) { timeout = 0; }
  10456. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10457. if (breakFunction && breakFunction())
  10458. loop.breakLoop();
  10459. else {
  10460. setTimeout(function () {
  10461. for (var i = 0; i < syncedIterations; ++i) {
  10462. var iteration = (loop.index * syncedIterations) + i;
  10463. if (iteration >= iterations)
  10464. break;
  10465. fn(iteration);
  10466. if (breakFunction && breakFunction()) {
  10467. loop.breakLoop();
  10468. break;
  10469. }
  10470. }
  10471. loop.executeNext();
  10472. }, timeout);
  10473. }
  10474. }, callback);
  10475. };
  10476. return AsyncLoop;
  10477. }());
  10478. BABYLON.AsyncLoop = AsyncLoop;
  10479. })(BABYLON || (BABYLON = {}));
  10480. //# sourceMappingURL=babylon.tools.js.map
  10481. var BABYLON;
  10482. (function (BABYLON) {
  10483. var PromiseStates;
  10484. (function (PromiseStates) {
  10485. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10486. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10487. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10488. })(PromiseStates || (PromiseStates = {}));
  10489. var FulFillmentAgregator = /** @class */ (function () {
  10490. function FulFillmentAgregator() {
  10491. this.count = 0;
  10492. this.target = 0;
  10493. this.results = [];
  10494. }
  10495. return FulFillmentAgregator;
  10496. }());
  10497. var InternalPromise = /** @class */ (function () {
  10498. function InternalPromise(resolver) {
  10499. var _this = this;
  10500. this._state = PromiseStates.Pending;
  10501. this._children = new Array();
  10502. this._rejectWasConsumed = false;
  10503. if (!resolver) {
  10504. return;
  10505. }
  10506. try {
  10507. resolver(function (value) {
  10508. _this._resolve(value);
  10509. }, function (reason) {
  10510. _this._reject(reason);
  10511. });
  10512. }
  10513. catch (e) {
  10514. this._reject(e);
  10515. }
  10516. }
  10517. Object.defineProperty(InternalPromise.prototype, "_result", {
  10518. get: function () {
  10519. return this._resultValue;
  10520. },
  10521. set: function (value) {
  10522. this._resultValue = value;
  10523. if (this._parent && this._parent._result === undefined) {
  10524. this._parent._result = value;
  10525. }
  10526. },
  10527. enumerable: true,
  10528. configurable: true
  10529. });
  10530. InternalPromise.prototype.catch = function (onRejected) {
  10531. return this.then(undefined, onRejected);
  10532. };
  10533. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10534. var _this = this;
  10535. var newPromise = new InternalPromise();
  10536. newPromise._onFulfilled = onFulfilled;
  10537. newPromise._onRejected = onRejected;
  10538. // Composition
  10539. this._children.push(newPromise);
  10540. newPromise._parent = this;
  10541. if (this._state !== PromiseStates.Pending) {
  10542. BABYLON.Tools.SetImmediate(function () {
  10543. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10544. var returnedValue = newPromise._resolve(_this._result);
  10545. if (returnedValue !== undefined && returnedValue !== null) {
  10546. if (returnedValue._state !== undefined) {
  10547. var returnedPromise = returnedValue;
  10548. newPromise._children.push(returnedPromise);
  10549. returnedPromise._parent = newPromise;
  10550. newPromise = returnedPromise;
  10551. }
  10552. else {
  10553. newPromise._result = returnedValue;
  10554. }
  10555. }
  10556. }
  10557. else {
  10558. newPromise._reject(_this._reason);
  10559. }
  10560. });
  10561. }
  10562. return newPromise;
  10563. };
  10564. InternalPromise.prototype._moveChildren = function (children) {
  10565. var _this = this;
  10566. var _a;
  10567. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10568. this._children.forEach(function (child) {
  10569. child._parent = _this;
  10570. });
  10571. if (this._state === PromiseStates.Fulfilled) {
  10572. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10573. var child = _b[_i];
  10574. child._resolve(this._result);
  10575. }
  10576. }
  10577. else if (this._state === PromiseStates.Rejected) {
  10578. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10579. var child = _d[_c];
  10580. child._reject(this._reason);
  10581. }
  10582. }
  10583. };
  10584. InternalPromise.prototype._resolve = function (value) {
  10585. try {
  10586. this._state = PromiseStates.Fulfilled;
  10587. var returnedValue = null;
  10588. if (this._onFulfilled) {
  10589. returnedValue = this._onFulfilled(value);
  10590. }
  10591. if (returnedValue !== undefined && returnedValue !== null) {
  10592. if (returnedValue._state !== undefined) {
  10593. // Transmit children
  10594. var returnedPromise = returnedValue;
  10595. returnedPromise._parent = this;
  10596. returnedPromise._moveChildren(this._children);
  10597. value = returnedPromise._result;
  10598. }
  10599. else {
  10600. value = returnedValue;
  10601. }
  10602. }
  10603. this._result = value;
  10604. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10605. var child = _a[_i];
  10606. child._resolve(value);
  10607. }
  10608. this._children.length = 0;
  10609. delete this._onFulfilled;
  10610. delete this._onRejected;
  10611. }
  10612. catch (e) {
  10613. this._reject(e, true);
  10614. }
  10615. };
  10616. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10617. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10618. this._state = PromiseStates.Rejected;
  10619. this._reason = reason;
  10620. if (this._onRejected && !onLocalThrow) {
  10621. try {
  10622. this._onRejected(reason);
  10623. this._rejectWasConsumed = true;
  10624. }
  10625. catch (e) {
  10626. reason = e;
  10627. }
  10628. }
  10629. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10630. var child = _a[_i];
  10631. if (this._rejectWasConsumed) {
  10632. child._resolve(null);
  10633. }
  10634. else {
  10635. child._reject(reason);
  10636. }
  10637. }
  10638. this._children.length = 0;
  10639. delete this._onFulfilled;
  10640. delete this._onRejected;
  10641. };
  10642. InternalPromise.resolve = function (value) {
  10643. var newPromise = new InternalPromise();
  10644. newPromise._resolve(value);
  10645. return newPromise;
  10646. };
  10647. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10648. promise.then(function (value) {
  10649. agregator.results[index] = value;
  10650. agregator.count++;
  10651. if (agregator.count === agregator.target) {
  10652. agregator.rootPromise._resolve(agregator.results);
  10653. }
  10654. return null;
  10655. }, function (reason) {
  10656. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10657. agregator.rootPromise._reject(reason);
  10658. }
  10659. });
  10660. };
  10661. InternalPromise.all = function (promises) {
  10662. var newPromise = new InternalPromise();
  10663. var agregator = new FulFillmentAgregator();
  10664. agregator.target = promises.length;
  10665. agregator.rootPromise = newPromise;
  10666. if (promises.length) {
  10667. for (var index = 0; index < promises.length; index++) {
  10668. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10669. }
  10670. }
  10671. else {
  10672. newPromise._resolve([]);
  10673. }
  10674. return newPromise;
  10675. };
  10676. InternalPromise.race = function (promises) {
  10677. var newPromise = new InternalPromise();
  10678. if (promises.length) {
  10679. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10680. var promise = promises_1[_i];
  10681. promise.then(function (value) {
  10682. if (newPromise) {
  10683. newPromise._resolve(value);
  10684. newPromise = null;
  10685. }
  10686. return null;
  10687. }, function (reason) {
  10688. if (newPromise) {
  10689. newPromise._reject(reason);
  10690. newPromise = null;
  10691. }
  10692. });
  10693. }
  10694. }
  10695. return newPromise;
  10696. };
  10697. return InternalPromise;
  10698. }());
  10699. /**
  10700. * Helper class that provides a small promise polyfill
  10701. */
  10702. var PromisePolyfill = /** @class */ (function () {
  10703. function PromisePolyfill() {
  10704. }
  10705. /**
  10706. * Static function used to check if the polyfill is required
  10707. * If this is the case then the function will inject the polyfill to window.Promise
  10708. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10709. */
  10710. PromisePolyfill.Apply = function (force) {
  10711. if (force === void 0) { force = false; }
  10712. if (force || typeof Promise === 'undefined') {
  10713. var root = window;
  10714. root.Promise = InternalPromise;
  10715. }
  10716. };
  10717. return PromisePolyfill;
  10718. }());
  10719. BABYLON.PromisePolyfill = PromisePolyfill;
  10720. })(BABYLON || (BABYLON = {}));
  10721. //# sourceMappingURL=babylon.promise.js.map
  10722. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10723. var BABYLON;
  10724. (function (BABYLON) {
  10725. /**
  10726. * Helper class to push actions to a pool of workers.
  10727. */
  10728. var WorkerPool = /** @class */ (function () {
  10729. /**
  10730. * Constructor
  10731. * @param workers Array of workers to use for actions
  10732. */
  10733. function WorkerPool(workers) {
  10734. this._pendingActions = new Array();
  10735. this._workerInfos = workers.map(function (worker) { return ({
  10736. worker: worker,
  10737. active: false
  10738. }); });
  10739. }
  10740. /**
  10741. * Terminates all workers and clears any pending actions.
  10742. */
  10743. WorkerPool.prototype.dispose = function () {
  10744. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10745. var workerInfo = _a[_i];
  10746. workerInfo.worker.terminate();
  10747. }
  10748. delete this._workerInfos;
  10749. delete this._pendingActions;
  10750. };
  10751. /**
  10752. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10753. * pended until a worker has completed its action.
  10754. * @param action The action to perform. Call onComplete when the action is complete.
  10755. */
  10756. WorkerPool.prototype.push = function (action) {
  10757. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10758. var workerInfo = _a[_i];
  10759. if (!workerInfo.active) {
  10760. this._execute(workerInfo, action);
  10761. return;
  10762. }
  10763. }
  10764. this._pendingActions.push(action);
  10765. };
  10766. WorkerPool.prototype._execute = function (workerInfo, action) {
  10767. var _this = this;
  10768. workerInfo.active = true;
  10769. action(workerInfo.worker, function () {
  10770. workerInfo.active = false;
  10771. var nextAction = _this._pendingActions.shift();
  10772. if (nextAction) {
  10773. _this._execute(workerInfo, nextAction);
  10774. }
  10775. });
  10776. };
  10777. return WorkerPool;
  10778. }());
  10779. BABYLON.WorkerPool = WorkerPool;
  10780. })(BABYLON || (BABYLON = {}));
  10781. //# sourceMappingURL=babylon.workerPool.js.map
  10782. var BABYLON;
  10783. (function (BABYLON) {
  10784. /**
  10785. * @hidden
  10786. **/
  10787. var _AlphaState = /** @class */ (function () {
  10788. /**
  10789. * Initializes the state.
  10790. */
  10791. function _AlphaState() {
  10792. this._isAlphaBlendDirty = false;
  10793. this._isBlendFunctionParametersDirty = false;
  10794. this._isBlendEquationParametersDirty = false;
  10795. this._isBlendConstantsDirty = false;
  10796. this._alphaBlend = false;
  10797. this._blendFunctionParameters = new Array(4);
  10798. this._blendEquationParameters = new Array(2);
  10799. this._blendConstants = new Array(4);
  10800. this.reset();
  10801. }
  10802. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10803. get: function () {
  10804. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10810. get: function () {
  10811. return this._alphaBlend;
  10812. },
  10813. set: function (value) {
  10814. if (this._alphaBlend === value) {
  10815. return;
  10816. }
  10817. this._alphaBlend = value;
  10818. this._isAlphaBlendDirty = true;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10824. if (this._blendConstants[0] === r &&
  10825. this._blendConstants[1] === g &&
  10826. this._blendConstants[2] === b &&
  10827. this._blendConstants[3] === a) {
  10828. return;
  10829. }
  10830. this._blendConstants[0] = r;
  10831. this._blendConstants[1] = g;
  10832. this._blendConstants[2] = b;
  10833. this._blendConstants[3] = a;
  10834. this._isBlendConstantsDirty = true;
  10835. };
  10836. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10837. if (this._blendFunctionParameters[0] === value0 &&
  10838. this._blendFunctionParameters[1] === value1 &&
  10839. this._blendFunctionParameters[2] === value2 &&
  10840. this._blendFunctionParameters[3] === value3) {
  10841. return;
  10842. }
  10843. this._blendFunctionParameters[0] = value0;
  10844. this._blendFunctionParameters[1] = value1;
  10845. this._blendFunctionParameters[2] = value2;
  10846. this._blendFunctionParameters[3] = value3;
  10847. this._isBlendFunctionParametersDirty = true;
  10848. };
  10849. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10850. if (this._blendEquationParameters[0] === rgb &&
  10851. this._blendEquationParameters[1] === alpha) {
  10852. return;
  10853. }
  10854. this._blendEquationParameters[0] = rgb;
  10855. this._blendEquationParameters[1] = alpha;
  10856. this._isBlendEquationParametersDirty = true;
  10857. };
  10858. _AlphaState.prototype.reset = function () {
  10859. this._alphaBlend = false;
  10860. this._blendFunctionParameters[0] = null;
  10861. this._blendFunctionParameters[1] = null;
  10862. this._blendFunctionParameters[2] = null;
  10863. this._blendFunctionParameters[3] = null;
  10864. this._blendEquationParameters[0] = null;
  10865. this._blendEquationParameters[1] = null;
  10866. this._blendConstants[0] = null;
  10867. this._blendConstants[1] = null;
  10868. this._blendConstants[2] = null;
  10869. this._blendConstants[3] = null;
  10870. this._isAlphaBlendDirty = true;
  10871. this._isBlendFunctionParametersDirty = false;
  10872. this._isBlendEquationParametersDirty = false;
  10873. this._isBlendConstantsDirty = false;
  10874. };
  10875. _AlphaState.prototype.apply = function (gl) {
  10876. if (!this.isDirty) {
  10877. return;
  10878. }
  10879. // Alpha blend
  10880. if (this._isAlphaBlendDirty) {
  10881. if (this._alphaBlend) {
  10882. gl.enable(gl.BLEND);
  10883. }
  10884. else {
  10885. gl.disable(gl.BLEND);
  10886. }
  10887. this._isAlphaBlendDirty = false;
  10888. }
  10889. // Alpha function
  10890. if (this._isBlendFunctionParametersDirty) {
  10891. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10892. this._isBlendFunctionParametersDirty = false;
  10893. }
  10894. // Alpha equation
  10895. if (this._isBlendEquationParametersDirty) {
  10896. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10897. this._isBlendEquationParametersDirty = false;
  10898. }
  10899. // Constants
  10900. if (this._isBlendConstantsDirty) {
  10901. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10902. this._isBlendConstantsDirty = false;
  10903. }
  10904. };
  10905. return _AlphaState;
  10906. }());
  10907. BABYLON._AlphaState = _AlphaState;
  10908. })(BABYLON || (BABYLON = {}));
  10909. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10910. var BABYLON;
  10911. (function (BABYLON) {
  10912. /**
  10913. * @hidden
  10914. **/
  10915. var _DepthCullingState = /** @class */ (function () {
  10916. /**
  10917. * Initializes the state.
  10918. */
  10919. function _DepthCullingState() {
  10920. this._isDepthTestDirty = false;
  10921. this._isDepthMaskDirty = false;
  10922. this._isDepthFuncDirty = false;
  10923. this._isCullFaceDirty = false;
  10924. this._isCullDirty = false;
  10925. this._isZOffsetDirty = false;
  10926. this._isFrontFaceDirty = false;
  10927. this.reset();
  10928. }
  10929. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10930. get: function () {
  10931. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10937. get: function () {
  10938. return this._zOffset;
  10939. },
  10940. set: function (value) {
  10941. if (this._zOffset === value) {
  10942. return;
  10943. }
  10944. this._zOffset = value;
  10945. this._isZOffsetDirty = true;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10951. get: function () {
  10952. return this._cullFace;
  10953. },
  10954. set: function (value) {
  10955. if (this._cullFace === value) {
  10956. return;
  10957. }
  10958. this._cullFace = value;
  10959. this._isCullFaceDirty = true;
  10960. },
  10961. enumerable: true,
  10962. configurable: true
  10963. });
  10964. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10965. get: function () {
  10966. return this._cull;
  10967. },
  10968. set: function (value) {
  10969. if (this._cull === value) {
  10970. return;
  10971. }
  10972. this._cull = value;
  10973. this._isCullDirty = true;
  10974. },
  10975. enumerable: true,
  10976. configurable: true
  10977. });
  10978. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10979. get: function () {
  10980. return this._depthFunc;
  10981. },
  10982. set: function (value) {
  10983. if (this._depthFunc === value) {
  10984. return;
  10985. }
  10986. this._depthFunc = value;
  10987. this._isDepthFuncDirty = true;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10993. get: function () {
  10994. return this._depthMask;
  10995. },
  10996. set: function (value) {
  10997. if (this._depthMask === value) {
  10998. return;
  10999. }
  11000. this._depthMask = value;
  11001. this._isDepthMaskDirty = true;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11007. get: function () {
  11008. return this._depthTest;
  11009. },
  11010. set: function (value) {
  11011. if (this._depthTest === value) {
  11012. return;
  11013. }
  11014. this._depthTest = value;
  11015. this._isDepthTestDirty = true;
  11016. },
  11017. enumerable: true,
  11018. configurable: true
  11019. });
  11020. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11021. get: function () {
  11022. return this._frontFace;
  11023. },
  11024. set: function (value) {
  11025. if (this._frontFace === value) {
  11026. return;
  11027. }
  11028. this._frontFace = value;
  11029. this._isFrontFaceDirty = true;
  11030. },
  11031. enumerable: true,
  11032. configurable: true
  11033. });
  11034. _DepthCullingState.prototype.reset = function () {
  11035. this._depthMask = true;
  11036. this._depthTest = true;
  11037. this._depthFunc = null;
  11038. this._cullFace = null;
  11039. this._cull = null;
  11040. this._zOffset = 0;
  11041. this._frontFace = null;
  11042. this._isDepthTestDirty = true;
  11043. this._isDepthMaskDirty = true;
  11044. this._isDepthFuncDirty = false;
  11045. this._isCullFaceDirty = false;
  11046. this._isCullDirty = false;
  11047. this._isZOffsetDirty = false;
  11048. this._isFrontFaceDirty = false;
  11049. };
  11050. _DepthCullingState.prototype.apply = function (gl) {
  11051. if (!this.isDirty) {
  11052. return;
  11053. }
  11054. // Cull
  11055. if (this._isCullDirty) {
  11056. if (this.cull) {
  11057. gl.enable(gl.CULL_FACE);
  11058. }
  11059. else {
  11060. gl.disable(gl.CULL_FACE);
  11061. }
  11062. this._isCullDirty = false;
  11063. }
  11064. // Cull face
  11065. if (this._isCullFaceDirty) {
  11066. gl.cullFace(this.cullFace);
  11067. this._isCullFaceDirty = false;
  11068. }
  11069. // Depth mask
  11070. if (this._isDepthMaskDirty) {
  11071. gl.depthMask(this.depthMask);
  11072. this._isDepthMaskDirty = false;
  11073. }
  11074. // Depth test
  11075. if (this._isDepthTestDirty) {
  11076. if (this.depthTest) {
  11077. gl.enable(gl.DEPTH_TEST);
  11078. }
  11079. else {
  11080. gl.disable(gl.DEPTH_TEST);
  11081. }
  11082. this._isDepthTestDirty = false;
  11083. }
  11084. // Depth func
  11085. if (this._isDepthFuncDirty) {
  11086. gl.depthFunc(this.depthFunc);
  11087. this._isDepthFuncDirty = false;
  11088. }
  11089. // zOffset
  11090. if (this._isZOffsetDirty) {
  11091. if (this.zOffset) {
  11092. gl.enable(gl.POLYGON_OFFSET_FILL);
  11093. gl.polygonOffset(this.zOffset, 0);
  11094. }
  11095. else {
  11096. gl.disable(gl.POLYGON_OFFSET_FILL);
  11097. }
  11098. this._isZOffsetDirty = false;
  11099. }
  11100. // Front face
  11101. if (this._isFrontFaceDirty) {
  11102. gl.frontFace(this.frontFace);
  11103. this._isFrontFaceDirty = false;
  11104. }
  11105. };
  11106. return _DepthCullingState;
  11107. }());
  11108. BABYLON._DepthCullingState = _DepthCullingState;
  11109. })(BABYLON || (BABYLON = {}));
  11110. //# sourceMappingURL=babylon.depthCullingState.js.map
  11111. var BABYLON;
  11112. (function (BABYLON) {
  11113. /**
  11114. * @hidden
  11115. **/
  11116. var _StencilState = /** @class */ (function () {
  11117. function _StencilState() {
  11118. this._isStencilTestDirty = false;
  11119. this._isStencilMaskDirty = false;
  11120. this._isStencilFuncDirty = false;
  11121. this._isStencilOpDirty = false;
  11122. this.reset();
  11123. }
  11124. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11125. get: function () {
  11126. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11127. },
  11128. enumerable: true,
  11129. configurable: true
  11130. });
  11131. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11132. get: function () {
  11133. return this._stencilFunc;
  11134. },
  11135. set: function (value) {
  11136. if (this._stencilFunc === value) {
  11137. return;
  11138. }
  11139. this._stencilFunc = value;
  11140. this._isStencilFuncDirty = true;
  11141. },
  11142. enumerable: true,
  11143. configurable: true
  11144. });
  11145. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11146. get: function () {
  11147. return this._stencilFuncRef;
  11148. },
  11149. set: function (value) {
  11150. if (this._stencilFuncRef === value) {
  11151. return;
  11152. }
  11153. this._stencilFuncRef = value;
  11154. this._isStencilFuncDirty = true;
  11155. },
  11156. enumerable: true,
  11157. configurable: true
  11158. });
  11159. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11160. get: function () {
  11161. return this._stencilFuncMask;
  11162. },
  11163. set: function (value) {
  11164. if (this._stencilFuncMask === value) {
  11165. return;
  11166. }
  11167. this._stencilFuncMask = value;
  11168. this._isStencilFuncDirty = true;
  11169. },
  11170. enumerable: true,
  11171. configurable: true
  11172. });
  11173. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11174. get: function () {
  11175. return this._stencilOpStencilFail;
  11176. },
  11177. set: function (value) {
  11178. if (this._stencilOpStencilFail === value) {
  11179. return;
  11180. }
  11181. this._stencilOpStencilFail = value;
  11182. this._isStencilOpDirty = true;
  11183. },
  11184. enumerable: true,
  11185. configurable: true
  11186. });
  11187. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11188. get: function () {
  11189. return this._stencilOpDepthFail;
  11190. },
  11191. set: function (value) {
  11192. if (this._stencilOpDepthFail === value) {
  11193. return;
  11194. }
  11195. this._stencilOpDepthFail = value;
  11196. this._isStencilOpDirty = true;
  11197. },
  11198. enumerable: true,
  11199. configurable: true
  11200. });
  11201. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11202. get: function () {
  11203. return this._stencilOpStencilDepthPass;
  11204. },
  11205. set: function (value) {
  11206. if (this._stencilOpStencilDepthPass === value) {
  11207. return;
  11208. }
  11209. this._stencilOpStencilDepthPass = value;
  11210. this._isStencilOpDirty = true;
  11211. },
  11212. enumerable: true,
  11213. configurable: true
  11214. });
  11215. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11216. get: function () {
  11217. return this._stencilMask;
  11218. },
  11219. set: function (value) {
  11220. if (this._stencilMask === value) {
  11221. return;
  11222. }
  11223. this._stencilMask = value;
  11224. this._isStencilMaskDirty = true;
  11225. },
  11226. enumerable: true,
  11227. configurable: true
  11228. });
  11229. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11230. get: function () {
  11231. return this._stencilTest;
  11232. },
  11233. set: function (value) {
  11234. if (this._stencilTest === value) {
  11235. return;
  11236. }
  11237. this._stencilTest = value;
  11238. this._isStencilTestDirty = true;
  11239. },
  11240. enumerable: true,
  11241. configurable: true
  11242. });
  11243. _StencilState.prototype.reset = function () {
  11244. this._stencilTest = false;
  11245. this._stencilMask = 0xFF;
  11246. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11247. this._stencilFuncRef = 1;
  11248. this._stencilFuncMask = 0xFF;
  11249. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11250. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11251. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11252. this._isStencilTestDirty = true;
  11253. this._isStencilMaskDirty = true;
  11254. this._isStencilFuncDirty = true;
  11255. this._isStencilOpDirty = true;
  11256. };
  11257. _StencilState.prototype.apply = function (gl) {
  11258. if (!this.isDirty) {
  11259. return;
  11260. }
  11261. // Stencil test
  11262. if (this._isStencilTestDirty) {
  11263. if (this.stencilTest) {
  11264. gl.enable(gl.STENCIL_TEST);
  11265. }
  11266. else {
  11267. gl.disable(gl.STENCIL_TEST);
  11268. }
  11269. this._isStencilTestDirty = false;
  11270. }
  11271. // Stencil mask
  11272. if (this._isStencilMaskDirty) {
  11273. gl.stencilMask(this.stencilMask);
  11274. this._isStencilMaskDirty = false;
  11275. }
  11276. // Stencil func
  11277. if (this._isStencilFuncDirty) {
  11278. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11279. this._isStencilFuncDirty = false;
  11280. }
  11281. // Stencil op
  11282. if (this._isStencilOpDirty) {
  11283. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11284. this._isStencilOpDirty = false;
  11285. }
  11286. };
  11287. return _StencilState;
  11288. }());
  11289. BABYLON._StencilState = _StencilState;
  11290. })(BABYLON || (BABYLON = {}));
  11291. //# sourceMappingURL=babylon.stencilState.js.map
  11292. var __assign = (this && this.__assign) || function () {
  11293. __assign = Object.assign || function(t) {
  11294. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11295. s = arguments[i];
  11296. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11297. t[p] = s[p];
  11298. }
  11299. return t;
  11300. };
  11301. return __assign.apply(this, arguments);
  11302. };
  11303. var BABYLON;
  11304. (function (BABYLON) {
  11305. /**
  11306. * Keeps track of all the buffer info used in engine.
  11307. */
  11308. var BufferPointer = /** @class */ (function () {
  11309. function BufferPointer() {
  11310. }
  11311. return BufferPointer;
  11312. }());
  11313. /**
  11314. * Interface for attribute information associated with buffer instanciation
  11315. */
  11316. var InstancingAttributeInfo = /** @class */ (function () {
  11317. function InstancingAttributeInfo() {
  11318. }
  11319. return InstancingAttributeInfo;
  11320. }());
  11321. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11322. /**
  11323. * Define options used to create a render target texture
  11324. */
  11325. var RenderTargetCreationOptions = /** @class */ (function () {
  11326. function RenderTargetCreationOptions() {
  11327. }
  11328. return RenderTargetCreationOptions;
  11329. }());
  11330. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11331. /**
  11332. * Define options used to create a depth texture
  11333. */
  11334. var DepthTextureCreationOptions = /** @class */ (function () {
  11335. function DepthTextureCreationOptions() {
  11336. }
  11337. return DepthTextureCreationOptions;
  11338. }());
  11339. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11340. /**
  11341. * Class used to describe the capabilities of the engine relatively to the current browser
  11342. */
  11343. var EngineCapabilities = /** @class */ (function () {
  11344. function EngineCapabilities() {
  11345. }
  11346. return EngineCapabilities;
  11347. }());
  11348. BABYLON.EngineCapabilities = EngineCapabilities;
  11349. /**
  11350. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11351. */
  11352. var Engine = /** @class */ (function () {
  11353. /**
  11354. * Creates a new engine
  11355. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11356. * @param antialias defines enable antialiasing (default: false)
  11357. * @param options defines further options to be sent to the getContext() function
  11358. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11359. */
  11360. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11361. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11362. var _this = this;
  11363. // Public members
  11364. /**
  11365. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11366. */
  11367. this.forcePOTTextures = false;
  11368. /**
  11369. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11370. */
  11371. this.isFullscreen = false;
  11372. /**
  11373. * Gets a boolean indicating if the pointer is currently locked
  11374. */
  11375. this.isPointerLock = false;
  11376. /**
  11377. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11378. */
  11379. this.cullBackFaces = true;
  11380. /**
  11381. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11382. */
  11383. this.renderEvenInBackground = true;
  11384. /**
  11385. * Gets or sets a boolean indicating that cache can be kept between frames
  11386. */
  11387. this.preventCacheWipeBetweenFrames = false;
  11388. /**
  11389. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11390. **/
  11391. this.enableOfflineSupport = false;
  11392. /**
  11393. * 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)
  11394. **/
  11395. this.disableManifestCheck = false;
  11396. /**
  11397. * Gets the list of created scenes
  11398. */
  11399. this.scenes = new Array();
  11400. /**
  11401. * Gets the list of created postprocesses
  11402. */
  11403. this.postProcesses = new Array();
  11404. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11405. this.validateShaderPrograms = false;
  11406. // Observables
  11407. /**
  11408. * Observable event triggered each time the rendering canvas is resized
  11409. */
  11410. this.onResizeObservable = new BABYLON.Observable();
  11411. /**
  11412. * Observable event triggered each time the canvas loses focus
  11413. */
  11414. this.onCanvasBlurObservable = new BABYLON.Observable();
  11415. /**
  11416. * Observable event triggered each time the canvas gains focus
  11417. */
  11418. this.onCanvasFocusObservable = new BABYLON.Observable();
  11419. /**
  11420. * Observable event triggered each time the canvas receives pointerout event
  11421. */
  11422. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11423. /**
  11424. * Observable event triggered before each texture is initialized
  11425. */
  11426. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11427. //WebVR
  11428. this._vrDisplay = undefined;
  11429. this._vrSupported = false;
  11430. this._vrExclusivePointerMode = false;
  11431. // Uniform buffers list
  11432. /**
  11433. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11434. */
  11435. this.disableUniformBuffers = false;
  11436. /** @hidden */
  11437. this._uniformBuffers = new Array();
  11438. // Observables
  11439. /**
  11440. * Observable raised when the engine begins a new frame
  11441. */
  11442. this.onBeginFrameObservable = new BABYLON.Observable();
  11443. /**
  11444. * Observable raised when the engine ends the current frame
  11445. */
  11446. this.onEndFrameObservable = new BABYLON.Observable();
  11447. /**
  11448. * Observable raised when the engine is about to compile a shader
  11449. */
  11450. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11451. /**
  11452. * Observable raised when the engine has jsut compiled a shader
  11453. */
  11454. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11455. this._windowIsBackground = false;
  11456. this._webGLVersion = 1.0;
  11457. /** @hidden */
  11458. this._badOS = false;
  11459. /** @hidden */
  11460. this._badDesktopOS = false;
  11461. /**
  11462. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11463. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11464. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11465. */
  11466. this.disableTextureBindingOptimization = false;
  11467. /**
  11468. * Observable signaled when VR display mode changes
  11469. */
  11470. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11471. /**
  11472. * Observable signaled when VR request present is complete
  11473. */
  11474. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11475. /**
  11476. * Observable signaled when VR request present starts
  11477. */
  11478. this.onVRRequestPresentStart = new BABYLON.Observable();
  11479. this._colorWrite = true;
  11480. /** @hidden */
  11481. this._drawCalls = new BABYLON.PerfCounter();
  11482. /** @hidden */
  11483. this._textureCollisions = new BABYLON.PerfCounter();
  11484. this._renderingQueueLaunched = false;
  11485. this._activeRenderLoops = new Array();
  11486. // Deterministic lockstepMaxSteps
  11487. this._deterministicLockstep = false;
  11488. this._lockstepMaxSteps = 4;
  11489. // Lost context
  11490. /**
  11491. * Observable signaled when a context lost event is raised
  11492. */
  11493. this.onContextLostObservable = new BABYLON.Observable();
  11494. /**
  11495. * Observable signaled when a context restored event is raised
  11496. */
  11497. this.onContextRestoredObservable = new BABYLON.Observable();
  11498. this._contextWasLost = false;
  11499. this._doNotHandleContextLost = false;
  11500. // FPS
  11501. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11502. this._fps = 60;
  11503. this._deltaTime = 0;
  11504. /**
  11505. * Turn this value on if you want to pause FPS computation when in background
  11506. */
  11507. this.disablePerformanceMonitorInBackground = false;
  11508. // States
  11509. /** @hidden */
  11510. this._depthCullingState = new BABYLON._DepthCullingState();
  11511. /** @hidden */
  11512. this._stencilState = new BABYLON._StencilState();
  11513. /** @hidden */
  11514. this._alphaState = new BABYLON._AlphaState();
  11515. /** @hidden */
  11516. this._alphaMode = Engine.ALPHA_DISABLE;
  11517. // Cache
  11518. this._internalTexturesCache = new Array();
  11519. /** @hidden */
  11520. this._activeChannel = 0;
  11521. this._currentTextureChannel = -1;
  11522. /** @hidden */
  11523. this._boundTexturesCache = {};
  11524. this._compiledEffects = {};
  11525. this._vertexAttribArraysEnabled = [];
  11526. this._uintIndicesCurrentlySet = false;
  11527. this._currentBoundBuffer = new Array();
  11528. /** @hidden */
  11529. this._currentFramebuffer = null;
  11530. this._currentBufferPointers = new Array();
  11531. this._currentInstanceLocations = new Array();
  11532. this._currentInstanceBuffers = new Array();
  11533. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11534. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11535. this._vaoRecordInProgress = false;
  11536. this._mustWipeVertexAttributes = false;
  11537. this._nextFreeTextureSlots = new Array();
  11538. this._maxSimultaneousTextures = 0;
  11539. this._activeRequests = new Array();
  11540. // Hardware supported Compressed Textures
  11541. this._texturesSupported = new Array();
  11542. /**
  11543. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11544. */
  11545. this.premultipliedAlpha = true;
  11546. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11547. this._onVRFullScreenTriggered = function () {
  11548. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11549. //get the old size before we change
  11550. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11551. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11552. //get the width and height, change the render size
  11553. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11554. _this.setHardwareScalingLevel(1);
  11555. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11556. }
  11557. else {
  11558. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11559. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11560. }
  11561. };
  11562. this._unpackFlipYCached = null;
  11563. /**
  11564. * In case you are sharing the context with other applications, it might
  11565. * be interested to not cache the unpack flip y state to ensure a consistent
  11566. * value would be set.
  11567. */
  11568. this.enableUnpackFlipYCached = true;
  11569. this._boundUniforms = {};
  11570. // Register promises
  11571. BABYLON.PromisePolyfill.Apply();
  11572. var canvas = null;
  11573. Engine.Instances.push(this);
  11574. if (!canvasOrContext) {
  11575. return;
  11576. }
  11577. options = options || {};
  11578. if (canvasOrContext.getContext) {
  11579. canvas = canvasOrContext;
  11580. this._renderingCanvas = canvas;
  11581. if (antialias != null) {
  11582. options.antialias = antialias;
  11583. }
  11584. if (options.deterministicLockstep === undefined) {
  11585. options.deterministicLockstep = false;
  11586. }
  11587. if (options.lockstepMaxSteps === undefined) {
  11588. options.lockstepMaxSteps = 4;
  11589. }
  11590. if (options.preserveDrawingBuffer === undefined) {
  11591. options.preserveDrawingBuffer = false;
  11592. }
  11593. if (options.audioEngine === undefined) {
  11594. options.audioEngine = true;
  11595. }
  11596. if (options.stencil === undefined) {
  11597. options.stencil = true;
  11598. }
  11599. if (options.premultipliedAlpha === false) {
  11600. this.premultipliedAlpha = false;
  11601. }
  11602. this._deterministicLockstep = options.deterministicLockstep;
  11603. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11604. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11605. // Exceptions
  11606. if (navigator && navigator.userAgent) {
  11607. var ua = navigator.userAgent;
  11608. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11609. var exception = _a[_i];
  11610. var key = exception.key;
  11611. var targets = exception.targets;
  11612. if (ua.indexOf(key) > -1) {
  11613. if (exception.capture && exception.captureConstraint) {
  11614. var capture = exception.capture;
  11615. var constraint = exception.captureConstraint;
  11616. var regex = new RegExp(capture);
  11617. var matches = regex.exec(ua);
  11618. if (matches && matches.length > 0) {
  11619. var capturedValue = parseInt(matches[matches.length - 1]);
  11620. if (capturedValue >= constraint) {
  11621. continue;
  11622. }
  11623. }
  11624. }
  11625. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11626. var target = targets_1[_b];
  11627. switch (target) {
  11628. case "uniformBuffer":
  11629. this.disableUniformBuffers = true;
  11630. break;
  11631. case "textureBindingOptimization":
  11632. this.disableTextureBindingOptimization = true;
  11633. break;
  11634. }
  11635. }
  11636. }
  11637. }
  11638. }
  11639. // GL
  11640. if (!options.disableWebGL2Support) {
  11641. try {
  11642. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11643. if (this._gl) {
  11644. this._webGLVersion = 2.0;
  11645. }
  11646. }
  11647. catch (e) {
  11648. // Do nothing
  11649. }
  11650. }
  11651. if (!this._gl) {
  11652. if (!canvas) {
  11653. throw new Error("The provided canvas is null or undefined.");
  11654. }
  11655. try {
  11656. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11657. }
  11658. catch (e) {
  11659. throw new Error("WebGL not supported");
  11660. }
  11661. }
  11662. if (!this._gl) {
  11663. throw new Error("WebGL not supported");
  11664. }
  11665. this._onCanvasFocus = function () {
  11666. _this.onCanvasFocusObservable.notifyObservers(_this);
  11667. };
  11668. this._onCanvasBlur = function () {
  11669. _this.onCanvasBlurObservable.notifyObservers(_this);
  11670. };
  11671. canvas.addEventListener("focus", this._onCanvasFocus);
  11672. canvas.addEventListener("blur", this._onCanvasBlur);
  11673. this._onBlur = function () {
  11674. if (_this.disablePerformanceMonitorInBackground) {
  11675. _this._performanceMonitor.disable();
  11676. }
  11677. _this._windowIsBackground = true;
  11678. };
  11679. this._onFocus = function () {
  11680. if (_this.disablePerformanceMonitorInBackground) {
  11681. _this._performanceMonitor.enable();
  11682. }
  11683. _this._windowIsBackground = false;
  11684. };
  11685. this._onCanvasPointerOut = function (ev) {
  11686. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11687. };
  11688. window.addEventListener("blur", this._onBlur);
  11689. window.addEventListener("focus", this._onFocus);
  11690. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11691. // Context lost
  11692. if (!this._doNotHandleContextLost) {
  11693. this._onContextLost = function (evt) {
  11694. evt.preventDefault();
  11695. _this._contextWasLost = true;
  11696. BABYLON.Tools.Warn("WebGL context lost.");
  11697. _this.onContextLostObservable.notifyObservers(_this);
  11698. };
  11699. this._onContextRestored = function (evt) {
  11700. // Adding a timeout to avoid race condition at browser level
  11701. setTimeout(function () {
  11702. // Rebuild gl context
  11703. _this._initGLContext();
  11704. // Rebuild effects
  11705. _this._rebuildEffects();
  11706. // Rebuild textures
  11707. _this._rebuildInternalTextures();
  11708. // Rebuild buffers
  11709. _this._rebuildBuffers();
  11710. // Cache
  11711. _this.wipeCaches(true);
  11712. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11713. _this.onContextRestoredObservable.notifyObservers(_this);
  11714. _this._contextWasLost = false;
  11715. }, 0);
  11716. };
  11717. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11718. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11719. }
  11720. }
  11721. else {
  11722. this._gl = canvasOrContext;
  11723. this._renderingCanvas = this._gl.canvas;
  11724. if (this._gl.renderbufferStorageMultisample) {
  11725. this._webGLVersion = 2.0;
  11726. }
  11727. options.stencil = this._gl.getContextAttributes().stencil;
  11728. }
  11729. // Viewport
  11730. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11731. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11732. this.resize();
  11733. this._isStencilEnable = options.stencil ? true : false;
  11734. this._initGLContext();
  11735. if (canvas) {
  11736. // Fullscreen
  11737. this._onFullscreenChange = function () {
  11738. if (document.fullscreen !== undefined) {
  11739. _this.isFullscreen = document.fullscreen;
  11740. }
  11741. else if (document.mozFullScreen !== undefined) {
  11742. _this.isFullscreen = document.mozFullScreen;
  11743. }
  11744. else if (document.webkitIsFullScreen !== undefined) {
  11745. _this.isFullscreen = document.webkitIsFullScreen;
  11746. }
  11747. else if (document.msIsFullScreen !== undefined) {
  11748. _this.isFullscreen = document.msIsFullScreen;
  11749. }
  11750. // Pointer lock
  11751. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11752. canvas.requestPointerLock = canvas.requestPointerLock ||
  11753. canvas.msRequestPointerLock ||
  11754. canvas.mozRequestPointerLock ||
  11755. canvas.webkitRequestPointerLock;
  11756. if (canvas.requestPointerLock) {
  11757. canvas.requestPointerLock();
  11758. }
  11759. }
  11760. };
  11761. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11762. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11763. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11764. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11765. // Pointer lock
  11766. this._onPointerLockChange = function () {
  11767. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11768. document.webkitPointerLockElement === canvas ||
  11769. document.msPointerLockElement === canvas ||
  11770. document.pointerLockElement === canvas);
  11771. };
  11772. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11773. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11774. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11775. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11776. this._onVRDisplayPointerRestricted = function () {
  11777. if (canvas) {
  11778. canvas.requestPointerLock();
  11779. }
  11780. };
  11781. this._onVRDisplayPointerUnrestricted = function () {
  11782. document.exitPointerLock();
  11783. };
  11784. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11785. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11786. }
  11787. // Create Audio Engine if needed.
  11788. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11789. Engine.audioEngine = Engine.AudioEngineFactory();
  11790. }
  11791. // Prepare buffer pointers
  11792. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11793. this._currentBufferPointers[i] = new BufferPointer();
  11794. }
  11795. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11796. // Load WebVR Devices
  11797. if (options.autoEnableWebVR) {
  11798. this.initWebVR();
  11799. }
  11800. // Detect if we are running on a faulty buggy OS.
  11801. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11802. // Detect if we are running on a faulty buggy desktop OS.
  11803. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11804. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11805. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11806. }
  11807. Object.defineProperty(Engine, "LastCreatedEngine", {
  11808. /**
  11809. * Gets the latest created engine
  11810. */
  11811. get: function () {
  11812. if (Engine.Instances.length === 0) {
  11813. return null;
  11814. }
  11815. return Engine.Instances[Engine.Instances.length - 1];
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine, "LastCreatedScene", {
  11821. /**
  11822. * Gets the latest created scene
  11823. */
  11824. get: function () {
  11825. var lastCreatedEngine = Engine.LastCreatedEngine;
  11826. if (!lastCreatedEngine) {
  11827. return null;
  11828. }
  11829. if (lastCreatedEngine.scenes.length === 0) {
  11830. return null;
  11831. }
  11832. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. /**
  11838. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11839. * @param flag defines which part of the materials must be marked as dirty
  11840. * @param predicate defines a predicate used to filter which materials should be affected
  11841. */
  11842. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11843. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11844. var engine = Engine.Instances[engineIndex];
  11845. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11846. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11847. }
  11848. }
  11849. };
  11850. Object.defineProperty(Engine, "Version", {
  11851. /**
  11852. * Returns the current version of the framework
  11853. */
  11854. get: function () {
  11855. return "3.3.0-beta.5";
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11861. /**
  11862. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11863. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11864. */
  11865. get: function () {
  11866. return this._vrExclusivePointerMode;
  11867. },
  11868. enumerable: true,
  11869. configurable: true
  11870. });
  11871. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11872. /**
  11873. * Gets a boolean indicating that the engine supports uniform buffers
  11874. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11875. */
  11876. get: function () {
  11877. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11883. /**
  11884. * Gets a boolean indicating that only power of 2 textures are supported
  11885. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11886. */
  11887. get: function () {
  11888. return this._webGLVersion < 2 || this.forcePOTTextures;
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11894. /**
  11895. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11896. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11897. */
  11898. get: function () {
  11899. return this._doNotHandleContextLost;
  11900. },
  11901. set: function (value) {
  11902. this._doNotHandleContextLost = value;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11908. /**
  11909. * Gets the performance monitor attached to this engine
  11910. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11911. */
  11912. get: function () {
  11913. return this._performanceMonitor;
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11919. /**
  11920. * Gets the list of texture formats supported
  11921. */
  11922. get: function () {
  11923. return this._texturesSupported;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11929. /**
  11930. * Gets the list of texture formats in use
  11931. */
  11932. get: function () {
  11933. return this._textureFormatInUse;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine.prototype, "currentViewport", {
  11939. /**
  11940. * Gets the current viewport
  11941. */
  11942. get: function () {
  11943. return this._cachedViewport;
  11944. },
  11945. enumerable: true,
  11946. configurable: true
  11947. });
  11948. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11949. /**
  11950. * Gets the default empty texture
  11951. */
  11952. get: function () {
  11953. if (!this._emptyTexture) {
  11954. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11955. }
  11956. return this._emptyTexture;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11962. /**
  11963. * Gets the default empty 3D texture
  11964. */
  11965. get: function () {
  11966. if (!this._emptyTexture3D) {
  11967. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11968. }
  11969. return this._emptyTexture3D;
  11970. },
  11971. enumerable: true,
  11972. configurable: true
  11973. });
  11974. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11975. /**
  11976. * Gets the default empty cube texture
  11977. */
  11978. get: function () {
  11979. if (!this._emptyCubeTexture) {
  11980. var faceData = new Uint8Array(4);
  11981. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11982. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11983. }
  11984. return this._emptyCubeTexture;
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Engine.prototype._rebuildInternalTextures = function () {
  11990. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11991. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11992. var internalTexture = currentState_1[_i];
  11993. internalTexture._rebuild();
  11994. }
  11995. };
  11996. Engine.prototype._rebuildEffects = function () {
  11997. for (var key in this._compiledEffects) {
  11998. var effect = this._compiledEffects[key];
  11999. effect._prepareEffect();
  12000. }
  12001. BABYLON.Effect.ResetCache();
  12002. };
  12003. Engine.prototype._rebuildBuffers = function () {
  12004. // Index / Vertex
  12005. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12006. var scene = _a[_i];
  12007. scene.resetCachedMaterial();
  12008. scene._rebuildGeometries();
  12009. scene._rebuildTextures();
  12010. }
  12011. // Uniforms
  12012. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12013. var uniformBuffer = _c[_b];
  12014. uniformBuffer._rebuild();
  12015. }
  12016. };
  12017. Engine.prototype._initGLContext = function () {
  12018. // Caps
  12019. this._caps = new EngineCapabilities();
  12020. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12021. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12022. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12023. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12024. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12025. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12026. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12027. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12028. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12029. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12030. // Infos
  12031. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12032. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12033. if (rendererInfo != null) {
  12034. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12035. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12036. }
  12037. if (!this._glVendor) {
  12038. this._glVendor = "Unknown vendor";
  12039. }
  12040. if (!this._glRenderer) {
  12041. this._glRenderer = "Unknown renderer";
  12042. }
  12043. // Constants
  12044. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12045. if (this._gl.RGBA16F !== 0x881A) {
  12046. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12047. }
  12048. if (this._gl.RGBA32F !== 0x8814) {
  12049. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12050. }
  12051. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12052. this._gl.DEPTH24_STENCIL8 = 35056;
  12053. }
  12054. // Extensions
  12055. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12056. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12057. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12058. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12059. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12060. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12061. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12062. 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');
  12063. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12064. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12065. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12066. this._caps.highPrecisionShaderSupported = true;
  12067. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12068. if (this._caps.timerQuery) {
  12069. if (this._webGLVersion === 1) {
  12070. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12071. }
  12072. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12073. }
  12074. // Checks if some of the format renders first to allow the use of webgl inspector.
  12075. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12076. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12077. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12078. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12079. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12080. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12081. if (this._webGLVersion > 1) {
  12082. this._gl.HALF_FLOAT_OES = 0x140B;
  12083. }
  12084. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12085. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12086. // Draw buffers
  12087. if (this._webGLVersion > 1) {
  12088. this._caps.drawBuffersExtension = true;
  12089. }
  12090. else {
  12091. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12092. if (drawBuffersExtension !== null) {
  12093. this._caps.drawBuffersExtension = true;
  12094. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12095. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12096. for (var i = 0; i < 16; i++) {
  12097. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12098. }
  12099. }
  12100. else {
  12101. this._caps.drawBuffersExtension = false;
  12102. }
  12103. }
  12104. // Depth Texture
  12105. if (this._webGLVersion > 1) {
  12106. this._caps.depthTextureExtension = true;
  12107. }
  12108. else {
  12109. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12110. if (depthTextureExtension != null) {
  12111. this._caps.depthTextureExtension = true;
  12112. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12113. }
  12114. }
  12115. // Vertex array object
  12116. if (this._webGLVersion > 1) {
  12117. this._caps.vertexArrayObject = true;
  12118. }
  12119. else {
  12120. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12121. if (vertexArrayObjectExtension != null) {
  12122. this._caps.vertexArrayObject = true;
  12123. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12124. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12125. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12126. }
  12127. else {
  12128. this._caps.vertexArrayObject = false;
  12129. }
  12130. }
  12131. // Instances count
  12132. if (this._webGLVersion > 1) {
  12133. this._caps.instancedArrays = true;
  12134. }
  12135. else {
  12136. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12137. if (instanceExtension != null) {
  12138. this._caps.instancedArrays = true;
  12139. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12140. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12141. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12142. }
  12143. else {
  12144. this._caps.instancedArrays = false;
  12145. }
  12146. }
  12147. // Intelligently add supported compressed formats in order to check for.
  12148. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12149. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12150. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12151. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12152. if (this._caps.astc)
  12153. this.texturesSupported.push('-astc.ktx');
  12154. if (this._caps.s3tc)
  12155. this.texturesSupported.push('-dxt.ktx');
  12156. if (this._caps.pvrtc)
  12157. this.texturesSupported.push('-pvrtc.ktx');
  12158. if (this._caps.etc2)
  12159. this.texturesSupported.push('-etc2.ktx');
  12160. if (this._caps.etc1)
  12161. this.texturesSupported.push('-etc1.ktx');
  12162. if (this._gl.getShaderPrecisionFormat) {
  12163. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12164. if (highp) {
  12165. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12166. }
  12167. }
  12168. // Depth buffer
  12169. this.setDepthBuffer(true);
  12170. this.setDepthFunctionToLessOrEqual();
  12171. this.setDepthWrite(true);
  12172. // Texture maps
  12173. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12174. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12175. this._nextFreeTextureSlots.push(slot);
  12176. }
  12177. };
  12178. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12179. /**
  12180. * Gets version of the current webGL context
  12181. */
  12182. get: function () {
  12183. return this._webGLVersion;
  12184. },
  12185. enumerable: true,
  12186. configurable: true
  12187. });
  12188. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12189. /**
  12190. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12191. */
  12192. get: function () {
  12193. return this._isStencilEnable;
  12194. },
  12195. enumerable: true,
  12196. configurable: true
  12197. });
  12198. Engine.prototype._prepareWorkingCanvas = function () {
  12199. if (this._workingCanvas) {
  12200. return;
  12201. }
  12202. this._workingCanvas = document.createElement("canvas");
  12203. var context = this._workingCanvas.getContext("2d");
  12204. if (context) {
  12205. this._workingContext = context;
  12206. }
  12207. };
  12208. /**
  12209. * Reset the texture cache to empty state
  12210. */
  12211. Engine.prototype.resetTextureCache = function () {
  12212. for (var key in this._boundTexturesCache) {
  12213. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12214. continue;
  12215. }
  12216. var boundTexture = this._boundTexturesCache[key];
  12217. if (boundTexture) {
  12218. this._removeDesignatedSlot(boundTexture);
  12219. }
  12220. this._boundTexturesCache[key] = null;
  12221. }
  12222. if (!this.disableTextureBindingOptimization) {
  12223. this._nextFreeTextureSlots = [];
  12224. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12225. this._nextFreeTextureSlots.push(slot);
  12226. }
  12227. }
  12228. this._currentTextureChannel = -1;
  12229. };
  12230. /**
  12231. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12232. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12233. * @returns true if engine is in deterministic lock step mode
  12234. */
  12235. Engine.prototype.isDeterministicLockStep = function () {
  12236. return this._deterministicLockstep;
  12237. };
  12238. /**
  12239. * Gets the max steps when engine is running in deterministic lock step
  12240. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12241. * @returns the max steps
  12242. */
  12243. Engine.prototype.getLockstepMaxSteps = function () {
  12244. return this._lockstepMaxSteps;
  12245. };
  12246. /**
  12247. * Gets an object containing information about the current webGL context
  12248. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12249. */
  12250. Engine.prototype.getGlInfo = function () {
  12251. return {
  12252. vendor: this._glVendor,
  12253. renderer: this._glRenderer,
  12254. version: this._glVersion
  12255. };
  12256. };
  12257. /**
  12258. * Gets current aspect ratio
  12259. * @param camera defines the camera to use to get the aspect ratio
  12260. * @param useScreen defines if screen size must be used (or the current render target if any)
  12261. * @returns a number defining the aspect ratio
  12262. */
  12263. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12264. if (useScreen === void 0) { useScreen = false; }
  12265. var viewport = camera.viewport;
  12266. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12267. };
  12268. /**
  12269. * Gets current screen aspect ratio
  12270. * @returns a number defining the aspect ratio
  12271. */
  12272. Engine.prototype.getScreenAspectRatio = function () {
  12273. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12274. };
  12275. /**
  12276. * Gets the current render width
  12277. * @param useScreen defines if screen size must be used (or the current render target if any)
  12278. * @returns a number defining the current render width
  12279. */
  12280. Engine.prototype.getRenderWidth = function (useScreen) {
  12281. if (useScreen === void 0) { useScreen = false; }
  12282. if (!useScreen && this._currentRenderTarget) {
  12283. return this._currentRenderTarget.width;
  12284. }
  12285. return this._gl.drawingBufferWidth;
  12286. };
  12287. /**
  12288. * Gets the current render height
  12289. * @param useScreen defines if screen size must be used (or the current render target if any)
  12290. * @returns a number defining the current render height
  12291. */
  12292. Engine.prototype.getRenderHeight = function (useScreen) {
  12293. if (useScreen === void 0) { useScreen = false; }
  12294. if (!useScreen && this._currentRenderTarget) {
  12295. return this._currentRenderTarget.height;
  12296. }
  12297. return this._gl.drawingBufferHeight;
  12298. };
  12299. /**
  12300. * Gets the HTML canvas attached with the current webGL context
  12301. * @returns a HTML canvas
  12302. */
  12303. Engine.prototype.getRenderingCanvas = function () {
  12304. return this._renderingCanvas;
  12305. };
  12306. /**
  12307. * Gets the client rect of the HTML canvas attached with the current webGL context
  12308. * @returns a client rectanglee
  12309. */
  12310. Engine.prototype.getRenderingCanvasClientRect = function () {
  12311. if (!this._renderingCanvas) {
  12312. return null;
  12313. }
  12314. return this._renderingCanvas.getBoundingClientRect();
  12315. };
  12316. /**
  12317. * Defines the hardware scaling level.
  12318. * By default the hardware scaling level is computed from the window device ratio.
  12319. * 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.
  12320. * @param level defines the level to use
  12321. */
  12322. Engine.prototype.setHardwareScalingLevel = function (level) {
  12323. this._hardwareScalingLevel = level;
  12324. this.resize();
  12325. };
  12326. /**
  12327. * Gets the current hardware scaling level.
  12328. * By default the hardware scaling level is computed from the window device ratio.
  12329. * 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.
  12330. * @returns a number indicating the current hardware scaling level
  12331. */
  12332. Engine.prototype.getHardwareScalingLevel = function () {
  12333. return this._hardwareScalingLevel;
  12334. };
  12335. /**
  12336. * Gets the list of loaded textures
  12337. * @returns an array containing all loaded textures
  12338. */
  12339. Engine.prototype.getLoadedTexturesCache = function () {
  12340. return this._internalTexturesCache;
  12341. };
  12342. /**
  12343. * Gets the object containing all engine capabilities
  12344. * @returns the EngineCapabilities object
  12345. */
  12346. Engine.prototype.getCaps = function () {
  12347. return this._caps;
  12348. };
  12349. Object.defineProperty(Engine.prototype, "drawCalls", {
  12350. /** @hidden */
  12351. get: function () {
  12352. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12353. return 0;
  12354. },
  12355. enumerable: true,
  12356. configurable: true
  12357. });
  12358. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12359. /** @hidden */
  12360. get: function () {
  12361. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12362. return null;
  12363. },
  12364. enumerable: true,
  12365. configurable: true
  12366. });
  12367. /**
  12368. * Gets the current depth function
  12369. * @returns a number defining the depth function
  12370. */
  12371. Engine.prototype.getDepthFunction = function () {
  12372. return this._depthCullingState.depthFunc;
  12373. };
  12374. /**
  12375. * Sets the current depth function
  12376. * @param depthFunc defines the function to use
  12377. */
  12378. Engine.prototype.setDepthFunction = function (depthFunc) {
  12379. this._depthCullingState.depthFunc = depthFunc;
  12380. };
  12381. /**
  12382. * Sets the current depth function to GREATER
  12383. */
  12384. Engine.prototype.setDepthFunctionToGreater = function () {
  12385. this._depthCullingState.depthFunc = this._gl.GREATER;
  12386. };
  12387. /**
  12388. * Sets the current depth function to GEQUAL
  12389. */
  12390. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12391. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12392. };
  12393. /**
  12394. * Sets the current depth function to LESS
  12395. */
  12396. Engine.prototype.setDepthFunctionToLess = function () {
  12397. this._depthCullingState.depthFunc = this._gl.LESS;
  12398. };
  12399. /**
  12400. * Sets the current depth function to LEQUAL
  12401. */
  12402. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12403. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12404. };
  12405. /**
  12406. * Gets a boolean indicating if stencil buffer is enabled
  12407. * @returns the current stencil buffer state
  12408. */
  12409. Engine.prototype.getStencilBuffer = function () {
  12410. return this._stencilState.stencilTest;
  12411. };
  12412. /**
  12413. * Enable or disable the stencil buffer
  12414. * @param enable defines if the stencil buffer must be enabled or disabled
  12415. */
  12416. Engine.prototype.setStencilBuffer = function (enable) {
  12417. this._stencilState.stencilTest = enable;
  12418. };
  12419. /**
  12420. * Gets the current stencil mask
  12421. * @returns a number defining the new stencil mask to use
  12422. */
  12423. Engine.prototype.getStencilMask = function () {
  12424. return this._stencilState.stencilMask;
  12425. };
  12426. /**
  12427. * Sets the current stencil mask
  12428. * @param mask defines the new stencil mask to use
  12429. */
  12430. Engine.prototype.setStencilMask = function (mask) {
  12431. this._stencilState.stencilMask = mask;
  12432. };
  12433. /**
  12434. * Gets the current stencil function
  12435. * @returns a number defining the stencil function to use
  12436. */
  12437. Engine.prototype.getStencilFunction = function () {
  12438. return this._stencilState.stencilFunc;
  12439. };
  12440. /**
  12441. * Gets the current stencil reference value
  12442. * @returns a number defining the stencil reference value to use
  12443. */
  12444. Engine.prototype.getStencilFunctionReference = function () {
  12445. return this._stencilState.stencilFuncRef;
  12446. };
  12447. /**
  12448. * Gets the current stencil mask
  12449. * @returns a number defining the stencil mask to use
  12450. */
  12451. Engine.prototype.getStencilFunctionMask = function () {
  12452. return this._stencilState.stencilFuncMask;
  12453. };
  12454. /**
  12455. * Sets the current stencil function
  12456. * @param stencilFunc defines the new stencil function to use
  12457. */
  12458. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12459. this._stencilState.stencilFunc = stencilFunc;
  12460. };
  12461. /**
  12462. * Sets the current stencil reference
  12463. * @param reference defines the new stencil reference to use
  12464. */
  12465. Engine.prototype.setStencilFunctionReference = function (reference) {
  12466. this._stencilState.stencilFuncRef = reference;
  12467. };
  12468. /**
  12469. * Sets the current stencil mask
  12470. * @param mask defines the new stencil mask to use
  12471. */
  12472. Engine.prototype.setStencilFunctionMask = function (mask) {
  12473. this._stencilState.stencilFuncMask = mask;
  12474. };
  12475. /**
  12476. * Gets the current stencil operation when stencil fails
  12477. * @returns a number defining stencil operation to use when stencil fails
  12478. */
  12479. Engine.prototype.getStencilOperationFail = function () {
  12480. return this._stencilState.stencilOpStencilFail;
  12481. };
  12482. /**
  12483. * Gets the current stencil operation when depth fails
  12484. * @returns a number defining stencil operation to use when depth fails
  12485. */
  12486. Engine.prototype.getStencilOperationDepthFail = function () {
  12487. return this._stencilState.stencilOpDepthFail;
  12488. };
  12489. /**
  12490. * Gets the current stencil operation when stencil passes
  12491. * @returns a number defining stencil operation to use when stencil passes
  12492. */
  12493. Engine.prototype.getStencilOperationPass = function () {
  12494. return this._stencilState.stencilOpStencilDepthPass;
  12495. };
  12496. /**
  12497. * Sets the stencil operation to use when stencil fails
  12498. * @param operation defines the stencil operation to use when stencil fails
  12499. */
  12500. Engine.prototype.setStencilOperationFail = function (operation) {
  12501. this._stencilState.stencilOpStencilFail = operation;
  12502. };
  12503. /**
  12504. * Sets the stencil operation to use when depth fails
  12505. * @param operation defines the stencil operation to use when depth fails
  12506. */
  12507. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12508. this._stencilState.stencilOpDepthFail = operation;
  12509. };
  12510. /**
  12511. * Sets the stencil operation to use when stencil passes
  12512. * @param operation defines the stencil operation to use when stencil passes
  12513. */
  12514. Engine.prototype.setStencilOperationPass = function (operation) {
  12515. this._stencilState.stencilOpStencilDepthPass = operation;
  12516. };
  12517. /**
  12518. * Sets a boolean indicating if the dithering state is enabled or disabled
  12519. * @param value defines the dithering state
  12520. */
  12521. Engine.prototype.setDitheringState = function (value) {
  12522. if (value) {
  12523. this._gl.enable(this._gl.DITHER);
  12524. }
  12525. else {
  12526. this._gl.disable(this._gl.DITHER);
  12527. }
  12528. };
  12529. /**
  12530. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12531. * @param value defines the rasterizer state
  12532. */
  12533. Engine.prototype.setRasterizerState = function (value) {
  12534. if (value) {
  12535. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12536. }
  12537. else {
  12538. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12539. }
  12540. };
  12541. /**
  12542. * stop executing a render loop function and remove it from the execution array
  12543. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12544. */
  12545. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12546. if (!renderFunction) {
  12547. this._activeRenderLoops = [];
  12548. return;
  12549. }
  12550. var index = this._activeRenderLoops.indexOf(renderFunction);
  12551. if (index >= 0) {
  12552. this._activeRenderLoops.splice(index, 1);
  12553. }
  12554. };
  12555. /** @hidden */
  12556. Engine.prototype._renderLoop = function () {
  12557. if (!this._contextWasLost) {
  12558. var shouldRender = true;
  12559. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12560. shouldRender = false;
  12561. }
  12562. if (shouldRender) {
  12563. // Start new frame
  12564. this.beginFrame();
  12565. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12566. var renderFunction = this._activeRenderLoops[index];
  12567. renderFunction();
  12568. }
  12569. // Present
  12570. this.endFrame();
  12571. }
  12572. }
  12573. if (this._activeRenderLoops.length > 0) {
  12574. // Register new frame
  12575. var requester = null;
  12576. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12577. requester = this._vrDisplay;
  12578. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12579. }
  12580. else {
  12581. this._renderingQueueLaunched = false;
  12582. }
  12583. };
  12584. /**
  12585. * Register and execute a render loop. The engine can have more than one render function
  12586. * @param renderFunction defines the function to continuously execute
  12587. */
  12588. Engine.prototype.runRenderLoop = function (renderFunction) {
  12589. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12590. return;
  12591. }
  12592. this._activeRenderLoops.push(renderFunction);
  12593. if (!this._renderingQueueLaunched) {
  12594. this._renderingQueueLaunched = true;
  12595. this._bindedRenderFunction = this._renderLoop.bind(this);
  12596. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12597. }
  12598. };
  12599. /**
  12600. * Toggle full screen mode
  12601. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12602. * @param options defines an option object to be sent to the requestFullscreen function
  12603. */
  12604. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12605. if (this.isFullscreen) {
  12606. BABYLON.Tools.ExitFullscreen();
  12607. }
  12608. else {
  12609. this._pointerLockRequested = requestPointerLock;
  12610. if (this._renderingCanvas) {
  12611. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12612. }
  12613. }
  12614. };
  12615. /**
  12616. * Clear the current render buffer or the current render target (if any is set up)
  12617. * @param color defines the color to use
  12618. * @param backBuffer defines if the back buffer must be cleared
  12619. * @param depth defines if the depth buffer must be cleared
  12620. * @param stencil defines if the stencil buffer must be cleared
  12621. */
  12622. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12623. if (stencil === void 0) { stencil = false; }
  12624. this.applyStates();
  12625. var mode = 0;
  12626. if (backBuffer && color) {
  12627. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12628. mode |= this._gl.COLOR_BUFFER_BIT;
  12629. }
  12630. if (depth) {
  12631. this._gl.clearDepth(1.0);
  12632. mode |= this._gl.DEPTH_BUFFER_BIT;
  12633. }
  12634. if (stencil) {
  12635. this._gl.clearStencil(0);
  12636. mode |= this._gl.STENCIL_BUFFER_BIT;
  12637. }
  12638. this._gl.clear(mode);
  12639. };
  12640. /**
  12641. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12642. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12643. * @param y defines the y-coordinate of the corner of the clear rectangle
  12644. * @param width defines the width of the clear rectangle
  12645. * @param height defines the height of the clear rectangle
  12646. * @param clearColor defines the clear color
  12647. */
  12648. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12649. var gl = this._gl;
  12650. // Save state
  12651. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12652. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12653. // Change state
  12654. gl.enable(gl.SCISSOR_TEST);
  12655. gl.scissor(x, y, width, height);
  12656. // Clear
  12657. this.clear(clearColor, true, true, true);
  12658. // Restore state
  12659. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12660. if (curScissor === true) {
  12661. gl.enable(gl.SCISSOR_TEST);
  12662. }
  12663. else {
  12664. gl.disable(gl.SCISSOR_TEST);
  12665. }
  12666. };
  12667. /** @hidden */
  12668. Engine.prototype._viewport = function (x, y, width, height) {
  12669. if (x !== this._viewportCached.x ||
  12670. y !== this._viewportCached.y ||
  12671. width !== this._viewportCached.z ||
  12672. height !== this._viewportCached.w) {
  12673. this._viewportCached.x = x;
  12674. this._viewportCached.y = y;
  12675. this._viewportCached.z = width;
  12676. this._viewportCached.w = height;
  12677. this._gl.viewport(x, y, width, height);
  12678. }
  12679. };
  12680. /**
  12681. * Set the WebGL's viewport
  12682. * @param viewport defines the viewport element to be used
  12683. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12684. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12685. */
  12686. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12687. var width = requiredWidth || this.getRenderWidth();
  12688. var height = requiredHeight || this.getRenderHeight();
  12689. var x = viewport.x || 0;
  12690. var y = viewport.y || 0;
  12691. this._cachedViewport = viewport;
  12692. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12693. };
  12694. /**
  12695. * Directly set the WebGL Viewport
  12696. * @param x defines the x coordinate of the viewport (in screen space)
  12697. * @param y defines the y coordinate of the viewport (in screen space)
  12698. * @param width defines the width of the viewport (in screen space)
  12699. * @param height defines the height of the viewport (in screen space)
  12700. * @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
  12701. */
  12702. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12703. var currentViewport = this._cachedViewport;
  12704. this._cachedViewport = null;
  12705. this._viewport(x, y, width, height);
  12706. return currentViewport;
  12707. };
  12708. /**
  12709. * Begin a new frame
  12710. */
  12711. Engine.prototype.beginFrame = function () {
  12712. this.onBeginFrameObservable.notifyObservers(this);
  12713. this._measureFps();
  12714. };
  12715. /**
  12716. * Enf the current frame
  12717. */
  12718. Engine.prototype.endFrame = function () {
  12719. // Force a flush in case we are using a bad OS.
  12720. if (this._badOS) {
  12721. this.flushFramebuffer();
  12722. }
  12723. // Submit frame to the vr device, if enabled
  12724. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12725. // TODO: We should only submit the frame if we read frameData successfully.
  12726. this._vrDisplay.submitFrame();
  12727. }
  12728. this.onEndFrameObservable.notifyObservers(this);
  12729. };
  12730. /**
  12731. * Resize the view according to the canvas' size
  12732. */
  12733. Engine.prototype.resize = function () {
  12734. // We're not resizing the size of the canvas while in VR mode & presenting
  12735. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12736. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12737. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12738. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12739. }
  12740. };
  12741. /**
  12742. * Force a specific size of the canvas
  12743. * @param width defines the new canvas' width
  12744. * @param height defines the new canvas' height
  12745. */
  12746. Engine.prototype.setSize = function (width, height) {
  12747. if (!this._renderingCanvas) {
  12748. return;
  12749. }
  12750. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12751. return;
  12752. }
  12753. this._renderingCanvas.width = width;
  12754. this._renderingCanvas.height = height;
  12755. for (var index = 0; index < this.scenes.length; index++) {
  12756. var scene = this.scenes[index];
  12757. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12758. var cam = scene.cameras[camIndex];
  12759. cam._currentRenderId = 0;
  12760. }
  12761. }
  12762. if (this.onResizeObservable.hasObservers) {
  12763. this.onResizeObservable.notifyObservers(this);
  12764. }
  12765. };
  12766. // WebVR functions
  12767. /**
  12768. * Gets a boolean indicating if a webVR device was detected
  12769. * @returns true if a webVR device was detected
  12770. */
  12771. Engine.prototype.isVRDevicePresent = function () {
  12772. return !!this._vrDisplay;
  12773. };
  12774. /**
  12775. * Gets the current webVR device
  12776. * @returns the current webVR device (or null)
  12777. */
  12778. Engine.prototype.getVRDevice = function () {
  12779. return this._vrDisplay;
  12780. };
  12781. /**
  12782. * Initializes a webVR display and starts listening to display change events
  12783. * The onVRDisplayChangedObservable will be notified upon these changes
  12784. * @returns The onVRDisplayChangedObservable
  12785. */
  12786. Engine.prototype.initWebVR = function () {
  12787. this.initWebVRAsync();
  12788. return this.onVRDisplayChangedObservable;
  12789. };
  12790. /**
  12791. * Initializes a webVR display and starts listening to display change events
  12792. * The onVRDisplayChangedObservable will be notified upon these changes
  12793. * @returns A promise containing a VRDisplay and if vr is supported
  12794. */
  12795. Engine.prototype.initWebVRAsync = function () {
  12796. var _this = this;
  12797. var notifyObservers = function () {
  12798. var eventArgs = {
  12799. vrDisplay: _this._vrDisplay,
  12800. vrSupported: _this._vrSupported
  12801. };
  12802. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12803. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12804. };
  12805. if (!this._onVrDisplayConnect) {
  12806. this._onVrDisplayConnect = function (event) {
  12807. _this._vrDisplay = event.display;
  12808. notifyObservers();
  12809. };
  12810. this._onVrDisplayDisconnect = function () {
  12811. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12812. _this._vrDisplay = undefined;
  12813. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12814. notifyObservers();
  12815. };
  12816. this._onVrDisplayPresentChange = function () {
  12817. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12818. };
  12819. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12820. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12821. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12822. }
  12823. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12824. this._webVRInitPromise.then(notifyObservers);
  12825. return this._webVRInitPromise;
  12826. };
  12827. /**
  12828. * Call this function to switch to webVR mode
  12829. * Will do nothing if webVR is not supported or if there is no webVR device
  12830. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12831. */
  12832. Engine.prototype.enableVR = function () {
  12833. var _this = this;
  12834. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12835. var onResolved = function () {
  12836. _this.onVRRequestPresentComplete.notifyObservers(true);
  12837. _this._onVRFullScreenTriggered();
  12838. };
  12839. var onRejected = function () {
  12840. _this.onVRRequestPresentComplete.notifyObservers(false);
  12841. };
  12842. this.onVRRequestPresentStart.notifyObservers(this);
  12843. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12844. }
  12845. };
  12846. /**
  12847. * Call this function to leave webVR mode
  12848. * Will do nothing if webVR is not supported or if there is no webVR device
  12849. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12850. */
  12851. Engine.prototype.disableVR = function () {
  12852. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12853. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12854. }
  12855. };
  12856. Engine.prototype._getVRDisplaysAsync = function () {
  12857. var _this = this;
  12858. return new Promise(function (res, rej) {
  12859. if (navigator.getVRDisplays) {
  12860. navigator.getVRDisplays().then(function (devices) {
  12861. _this._vrSupported = true;
  12862. // note that devices may actually be an empty array. This is fine;
  12863. // we expect this._vrDisplay to be undefined in this case.
  12864. _this._vrDisplay = devices[0];
  12865. res({
  12866. vrDisplay: _this._vrDisplay,
  12867. vrSupported: _this._vrSupported
  12868. });
  12869. });
  12870. }
  12871. else {
  12872. _this._vrDisplay = undefined;
  12873. _this._vrSupported = false;
  12874. res({
  12875. vrDisplay: _this._vrDisplay,
  12876. vrSupported: _this._vrSupported
  12877. });
  12878. }
  12879. });
  12880. };
  12881. /**
  12882. * Binds the frame buffer to the specified texture.
  12883. * @param texture The texture to render to or null for the default canvas
  12884. * @param faceIndex The face of the texture to render to in case of cube texture
  12885. * @param requiredWidth The width of the target to render to
  12886. * @param requiredHeight The height of the target to render to
  12887. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12888. * @param depthStencilTexture The depth stencil texture to use to render
  12889. * @param lodLevel defines le lod level to bind to the frame buffer
  12890. */
  12891. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12892. if (lodLevel === void 0) { lodLevel = 0; }
  12893. if (this._currentRenderTarget) {
  12894. this.unBindFramebuffer(this._currentRenderTarget);
  12895. }
  12896. this._currentRenderTarget = texture;
  12897. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12898. var gl = this._gl;
  12899. if (texture.isCube) {
  12900. if (faceIndex === undefined) {
  12901. faceIndex = 0;
  12902. }
  12903. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12904. if (depthStencilTexture) {
  12905. if (depthStencilTexture._generateStencilBuffer) {
  12906. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12907. }
  12908. else {
  12909. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12910. }
  12911. }
  12912. }
  12913. if (this._cachedViewport && !forceFullscreenViewport) {
  12914. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12915. }
  12916. else {
  12917. if (!requiredWidth) {
  12918. requiredWidth = texture.width;
  12919. if (lodLevel) {
  12920. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12921. }
  12922. }
  12923. if (!requiredHeight) {
  12924. requiredHeight = texture.height;
  12925. if (lodLevel) {
  12926. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12927. }
  12928. }
  12929. this._viewport(0, 0, requiredWidth, requiredHeight);
  12930. }
  12931. this.wipeCaches();
  12932. };
  12933. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12934. if (this._currentFramebuffer !== framebuffer) {
  12935. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12936. this._currentFramebuffer = framebuffer;
  12937. }
  12938. };
  12939. /**
  12940. * Unbind the current render target texture from the webGL context
  12941. * @param texture defines the render target texture to unbind
  12942. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12943. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12944. */
  12945. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12946. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12947. this._currentRenderTarget = null;
  12948. // If MSAA, we need to bitblt back to main texture
  12949. var gl = this._gl;
  12950. if (texture._MSAAFramebuffer) {
  12951. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12952. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12953. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12954. }
  12955. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12956. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12957. gl.generateMipmap(gl.TEXTURE_2D);
  12958. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12959. }
  12960. if (onBeforeUnbind) {
  12961. if (texture._MSAAFramebuffer) {
  12962. // Bind the correct framebuffer
  12963. this.bindUnboundFramebuffer(texture._framebuffer);
  12964. }
  12965. onBeforeUnbind();
  12966. }
  12967. this.bindUnboundFramebuffer(null);
  12968. };
  12969. /**
  12970. * Unbind a list of render target textures from the webGL context
  12971. * This is used only when drawBuffer extension or webGL2 are active
  12972. * @param textures defines the render target textures to unbind
  12973. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12974. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12975. */
  12976. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12977. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12978. this._currentRenderTarget = null;
  12979. // If MSAA, we need to bitblt back to main texture
  12980. var gl = this._gl;
  12981. if (textures[0]._MSAAFramebuffer) {
  12982. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12983. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12984. var attachments = textures[0]._attachments;
  12985. if (!attachments) {
  12986. attachments = new Array(textures.length);
  12987. textures[0]._attachments = attachments;
  12988. }
  12989. for (var i = 0; i < textures.length; i++) {
  12990. var texture = textures[i];
  12991. for (var j = 0; j < attachments.length; j++) {
  12992. attachments[j] = gl.NONE;
  12993. }
  12994. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12995. gl.readBuffer(attachments[i]);
  12996. gl.drawBuffers(attachments);
  12997. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12998. }
  12999. for (var i = 0; i < attachments.length; i++) {
  13000. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13001. }
  13002. gl.drawBuffers(attachments);
  13003. }
  13004. for (var i = 0; i < textures.length; i++) {
  13005. var texture = textures[i];
  13006. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13007. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13008. gl.generateMipmap(gl.TEXTURE_2D);
  13009. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13010. }
  13011. }
  13012. if (onBeforeUnbind) {
  13013. if (textures[0]._MSAAFramebuffer) {
  13014. // Bind the correct framebuffer
  13015. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13016. }
  13017. onBeforeUnbind();
  13018. }
  13019. this.bindUnboundFramebuffer(null);
  13020. };
  13021. /**
  13022. * Force the mipmap generation for the given render target texture
  13023. * @param texture defines the render target texture to use
  13024. */
  13025. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13026. if (texture.generateMipMaps) {
  13027. var gl = this._gl;
  13028. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13029. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13030. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13031. }
  13032. };
  13033. /**
  13034. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13035. */
  13036. Engine.prototype.flushFramebuffer = function () {
  13037. this._gl.flush();
  13038. };
  13039. /**
  13040. * Unbind the current render target and bind the default framebuffer
  13041. */
  13042. Engine.prototype.restoreDefaultFramebuffer = function () {
  13043. if (this._currentRenderTarget) {
  13044. this.unBindFramebuffer(this._currentRenderTarget);
  13045. }
  13046. else {
  13047. this.bindUnboundFramebuffer(null);
  13048. }
  13049. if (this._cachedViewport) {
  13050. this.setViewport(this._cachedViewport);
  13051. }
  13052. this.wipeCaches();
  13053. };
  13054. // UBOs
  13055. /**
  13056. * Create an uniform buffer
  13057. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13058. * @param elements defines the content of the uniform buffer
  13059. * @returns the webGL uniform buffer
  13060. */
  13061. Engine.prototype.createUniformBuffer = function (elements) {
  13062. var ubo = this._gl.createBuffer();
  13063. if (!ubo) {
  13064. throw new Error("Unable to create uniform buffer");
  13065. }
  13066. this.bindUniformBuffer(ubo);
  13067. if (elements instanceof Float32Array) {
  13068. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13069. }
  13070. else {
  13071. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13072. }
  13073. this.bindUniformBuffer(null);
  13074. ubo.references = 1;
  13075. return ubo;
  13076. };
  13077. /**
  13078. * Create a dynamic uniform buffer
  13079. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13080. * @param elements defines the content of the uniform buffer
  13081. * @returns the webGL uniform buffer
  13082. */
  13083. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13084. var ubo = this._gl.createBuffer();
  13085. if (!ubo) {
  13086. throw new Error("Unable to create dynamic uniform buffer");
  13087. }
  13088. this.bindUniformBuffer(ubo);
  13089. if (elements instanceof Float32Array) {
  13090. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13091. }
  13092. else {
  13093. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13094. }
  13095. this.bindUniformBuffer(null);
  13096. ubo.references = 1;
  13097. return ubo;
  13098. };
  13099. /**
  13100. * Update an existing uniform buffer
  13101. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13102. * @param uniformBuffer defines the target uniform buffer
  13103. * @param elements defines the content to update
  13104. * @param offset defines the offset in the uniform buffer where update should start
  13105. * @param count defines the size of the data to update
  13106. */
  13107. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13108. this.bindUniformBuffer(uniformBuffer);
  13109. if (offset === undefined) {
  13110. offset = 0;
  13111. }
  13112. if (count === undefined) {
  13113. if (elements instanceof Float32Array) {
  13114. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13115. }
  13116. else {
  13117. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13118. }
  13119. }
  13120. else {
  13121. if (elements instanceof Float32Array) {
  13122. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13123. }
  13124. else {
  13125. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13126. }
  13127. }
  13128. this.bindUniformBuffer(null);
  13129. };
  13130. // VBOs
  13131. Engine.prototype._resetVertexBufferBinding = function () {
  13132. this.bindArrayBuffer(null);
  13133. this._cachedVertexBuffers = null;
  13134. };
  13135. /**
  13136. * Creates a vertex buffer
  13137. * @param data the data for the vertex buffer
  13138. * @returns the new WebGL static buffer
  13139. */
  13140. Engine.prototype.createVertexBuffer = function (data) {
  13141. var vbo = this._gl.createBuffer();
  13142. if (!vbo) {
  13143. throw new Error("Unable to create vertex buffer");
  13144. }
  13145. this.bindArrayBuffer(vbo);
  13146. if (data instanceof Array) {
  13147. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13148. }
  13149. else {
  13150. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13151. }
  13152. this._resetVertexBufferBinding();
  13153. vbo.references = 1;
  13154. return vbo;
  13155. };
  13156. /**
  13157. * Creates a dynamic vertex buffer
  13158. * @param data the data for the dynamic vertex buffer
  13159. * @returns the new WebGL dynamic buffer
  13160. */
  13161. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13162. var vbo = this._gl.createBuffer();
  13163. if (!vbo) {
  13164. throw new Error("Unable to create dynamic vertex buffer");
  13165. }
  13166. this.bindArrayBuffer(vbo);
  13167. if (data instanceof Array) {
  13168. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13169. }
  13170. else {
  13171. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13172. }
  13173. this._resetVertexBufferBinding();
  13174. vbo.references = 1;
  13175. return vbo;
  13176. };
  13177. /**
  13178. * Update a dynamic index buffer
  13179. * @param indexBuffer defines the target index buffer
  13180. * @param indices defines the data to update
  13181. * @param offset defines the offset in the target index buffer where update should start
  13182. */
  13183. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13184. if (offset === void 0) { offset = 0; }
  13185. // Force cache update
  13186. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13187. this.bindIndexBuffer(indexBuffer);
  13188. var arrayBuffer;
  13189. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13190. arrayBuffer = indices;
  13191. }
  13192. else {
  13193. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13194. }
  13195. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13196. this._resetIndexBufferBinding();
  13197. };
  13198. /**
  13199. * Updates a dynamic vertex buffer.
  13200. * @param vertexBuffer the vertex buffer to update
  13201. * @param data the data used to update the vertex buffer
  13202. * @param byteOffset the byte offset of the data
  13203. * @param byteLength the byte length of the data
  13204. */
  13205. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13206. this.bindArrayBuffer(vertexBuffer);
  13207. if (byteOffset === undefined) {
  13208. byteOffset = 0;
  13209. }
  13210. if (byteLength === undefined) {
  13211. if (data instanceof Array) {
  13212. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13213. }
  13214. else {
  13215. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13216. }
  13217. }
  13218. else {
  13219. if (data instanceof Array) {
  13220. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13221. }
  13222. else {
  13223. if (data instanceof ArrayBuffer) {
  13224. data = new Uint8Array(data, byteOffset, byteLength);
  13225. }
  13226. else {
  13227. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13228. }
  13229. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13230. }
  13231. }
  13232. this._resetVertexBufferBinding();
  13233. };
  13234. Engine.prototype._resetIndexBufferBinding = function () {
  13235. this.bindIndexBuffer(null);
  13236. this._cachedIndexBuffer = null;
  13237. };
  13238. /**
  13239. * Creates a new index buffer
  13240. * @param indices defines the content of the index buffer
  13241. * @param updatable defines if the index buffer must be updatable
  13242. * @returns a new webGL buffer
  13243. */
  13244. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13245. var vbo = this._gl.createBuffer();
  13246. if (!vbo) {
  13247. throw new Error("Unable to create index buffer");
  13248. }
  13249. this.bindIndexBuffer(vbo);
  13250. // Check for 32 bits indices
  13251. var arrayBuffer;
  13252. var need32Bits = false;
  13253. if (indices instanceof Uint16Array) {
  13254. arrayBuffer = indices;
  13255. }
  13256. else {
  13257. //check 32 bit support
  13258. if (this._caps.uintIndices) {
  13259. if (indices instanceof Uint32Array) {
  13260. arrayBuffer = indices;
  13261. need32Bits = true;
  13262. }
  13263. else {
  13264. //number[] or Int32Array, check if 32 bit is necessary
  13265. for (var index = 0; index < indices.length; index++) {
  13266. if (indices[index] > 65535) {
  13267. need32Bits = true;
  13268. break;
  13269. }
  13270. }
  13271. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13272. }
  13273. }
  13274. else {
  13275. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13276. arrayBuffer = new Uint16Array(indices);
  13277. }
  13278. }
  13279. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13280. this._resetIndexBufferBinding();
  13281. vbo.references = 1;
  13282. vbo.is32Bits = need32Bits;
  13283. return vbo;
  13284. };
  13285. /**
  13286. * Bind a webGL buffer to the webGL context
  13287. * @param buffer defines the buffer to bind
  13288. */
  13289. Engine.prototype.bindArrayBuffer = function (buffer) {
  13290. if (!this._vaoRecordInProgress) {
  13291. this._unbindVertexArrayObject();
  13292. }
  13293. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13294. };
  13295. /**
  13296. * Bind an uniform buffer to the current webGL context
  13297. * @param buffer defines the buffer to bind
  13298. */
  13299. Engine.prototype.bindUniformBuffer = function (buffer) {
  13300. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13301. };
  13302. /**
  13303. * Bind a buffer to the current webGL context at a given location
  13304. * @param buffer defines the buffer to bind
  13305. * @param location defines the index where to bind the buffer
  13306. */
  13307. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13308. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13309. };
  13310. /**
  13311. * Bind a specific block at a given index in a specific shader program
  13312. * @param shaderProgram defines the shader program
  13313. * @param blockName defines the block name
  13314. * @param index defines the index where to bind the block
  13315. */
  13316. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13317. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13318. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13319. };
  13320. ;
  13321. Engine.prototype.bindIndexBuffer = function (buffer) {
  13322. if (!this._vaoRecordInProgress) {
  13323. this._unbindVertexArrayObject();
  13324. }
  13325. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13326. };
  13327. Engine.prototype.bindBuffer = function (buffer, target) {
  13328. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13329. this._gl.bindBuffer(target, buffer);
  13330. this._currentBoundBuffer[target] = buffer;
  13331. }
  13332. };
  13333. /**
  13334. * update the bound buffer with the given data
  13335. * @param data defines the data to update
  13336. */
  13337. Engine.prototype.updateArrayBuffer = function (data) {
  13338. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13339. };
  13340. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13341. var pointer = this._currentBufferPointers[indx];
  13342. var changed = false;
  13343. if (!pointer.active) {
  13344. changed = true;
  13345. pointer.active = true;
  13346. pointer.index = indx;
  13347. pointer.size = size;
  13348. pointer.type = type;
  13349. pointer.normalized = normalized;
  13350. pointer.stride = stride;
  13351. pointer.offset = offset;
  13352. pointer.buffer = buffer;
  13353. }
  13354. else {
  13355. if (pointer.buffer !== buffer) {
  13356. pointer.buffer = buffer;
  13357. changed = true;
  13358. }
  13359. if (pointer.size !== size) {
  13360. pointer.size = size;
  13361. changed = true;
  13362. }
  13363. if (pointer.type !== type) {
  13364. pointer.type = type;
  13365. changed = true;
  13366. }
  13367. if (pointer.normalized !== normalized) {
  13368. pointer.normalized = normalized;
  13369. changed = true;
  13370. }
  13371. if (pointer.stride !== stride) {
  13372. pointer.stride = stride;
  13373. changed = true;
  13374. }
  13375. if (pointer.offset !== offset) {
  13376. pointer.offset = offset;
  13377. changed = true;
  13378. }
  13379. }
  13380. if (changed || this._vaoRecordInProgress) {
  13381. this.bindArrayBuffer(buffer);
  13382. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13383. }
  13384. };
  13385. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13386. if (indexBuffer == null) {
  13387. return;
  13388. }
  13389. if (this._cachedIndexBuffer !== indexBuffer) {
  13390. this._cachedIndexBuffer = indexBuffer;
  13391. this.bindIndexBuffer(indexBuffer);
  13392. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13393. }
  13394. };
  13395. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13396. var attributes = effect.getAttributesNames();
  13397. if (!this._vaoRecordInProgress) {
  13398. this._unbindVertexArrayObject();
  13399. }
  13400. this.unbindAllAttributes();
  13401. for (var index = 0; index < attributes.length; index++) {
  13402. var order = effect.getAttributeLocation(index);
  13403. if (order >= 0) {
  13404. var vertexBuffer = vertexBuffers[attributes[index]];
  13405. if (!vertexBuffer) {
  13406. continue;
  13407. }
  13408. this._gl.enableVertexAttribArray(order);
  13409. if (!this._vaoRecordInProgress) {
  13410. this._vertexAttribArraysEnabled[order] = true;
  13411. }
  13412. var buffer = vertexBuffer.getBuffer();
  13413. if (buffer) {
  13414. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13415. if (vertexBuffer.getIsInstanced()) {
  13416. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13417. if (!this._vaoRecordInProgress) {
  13418. this._currentInstanceLocations.push(order);
  13419. this._currentInstanceBuffers.push(buffer);
  13420. }
  13421. }
  13422. }
  13423. }
  13424. }
  13425. };
  13426. /**
  13427. * Records a vertex array object
  13428. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13429. * @param vertexBuffers defines the list of vertex buffers to store
  13430. * @param indexBuffer defines the index buffer to store
  13431. * @param effect defines the effect to store
  13432. * @returns the new vertex array object
  13433. */
  13434. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13435. var vao = this._gl.createVertexArray();
  13436. this._vaoRecordInProgress = true;
  13437. this._gl.bindVertexArray(vao);
  13438. this._mustWipeVertexAttributes = true;
  13439. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13440. this.bindIndexBuffer(indexBuffer);
  13441. this._vaoRecordInProgress = false;
  13442. this._gl.bindVertexArray(null);
  13443. return vao;
  13444. };
  13445. /**
  13446. * Bind a specific vertex array object
  13447. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13448. * @param vertexArrayObject defines the vertex array object to bind
  13449. * @param indexBuffer defines the index buffer to bind
  13450. */
  13451. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13452. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13453. this._cachedVertexArrayObject = vertexArrayObject;
  13454. this._gl.bindVertexArray(vertexArrayObject);
  13455. this._cachedVertexBuffers = null;
  13456. this._cachedIndexBuffer = null;
  13457. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13458. this._mustWipeVertexAttributes = true;
  13459. }
  13460. };
  13461. /**
  13462. * Bind webGl buffers directly to the webGL context
  13463. * @param vertexBuffer defines the vertex buffer to bind
  13464. * @param indexBuffer defines the index buffer to bind
  13465. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13466. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13467. * @param effect defines the effect associated with the vertex buffer
  13468. */
  13469. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13470. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13471. this._cachedVertexBuffers = vertexBuffer;
  13472. this._cachedEffectForVertexBuffers = effect;
  13473. var attributesCount = effect.getAttributesCount();
  13474. this._unbindVertexArrayObject();
  13475. this.unbindAllAttributes();
  13476. var offset = 0;
  13477. for (var index = 0; index < attributesCount; index++) {
  13478. if (index < vertexDeclaration.length) {
  13479. var order = effect.getAttributeLocation(index);
  13480. if (order >= 0) {
  13481. this._gl.enableVertexAttribArray(order);
  13482. this._vertexAttribArraysEnabled[order] = true;
  13483. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13484. }
  13485. offset += vertexDeclaration[index] * 4;
  13486. }
  13487. }
  13488. }
  13489. this._bindIndexBufferWithCache(indexBuffer);
  13490. };
  13491. Engine.prototype._unbindVertexArrayObject = function () {
  13492. if (!this._cachedVertexArrayObject) {
  13493. return;
  13494. }
  13495. this._cachedVertexArrayObject = null;
  13496. this._gl.bindVertexArray(null);
  13497. };
  13498. /**
  13499. * Bind a list of vertex buffers to the webGL context
  13500. * @param vertexBuffers defines the list of vertex buffers to bind
  13501. * @param indexBuffer defines the index buffer to bind
  13502. * @param effect defines the effect associated with the vertex buffers
  13503. */
  13504. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13505. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13506. this._cachedVertexBuffers = vertexBuffers;
  13507. this._cachedEffectForVertexBuffers = effect;
  13508. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13509. }
  13510. this._bindIndexBufferWithCache(indexBuffer);
  13511. };
  13512. /**
  13513. * Unbind all instance attributes
  13514. */
  13515. Engine.prototype.unbindInstanceAttributes = function () {
  13516. var boundBuffer;
  13517. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13518. var instancesBuffer = this._currentInstanceBuffers[i];
  13519. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13520. boundBuffer = instancesBuffer;
  13521. this.bindArrayBuffer(instancesBuffer);
  13522. }
  13523. var offsetLocation = this._currentInstanceLocations[i];
  13524. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13525. }
  13526. this._currentInstanceBuffers.length = 0;
  13527. this._currentInstanceLocations.length = 0;
  13528. };
  13529. /**
  13530. * Release and free the memory of a vertex array object
  13531. * @param vao defines the vertex array object to delete
  13532. */
  13533. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13534. this._gl.deleteVertexArray(vao);
  13535. };
  13536. /** @hidden */
  13537. Engine.prototype._releaseBuffer = function (buffer) {
  13538. buffer.references--;
  13539. if (buffer.references === 0) {
  13540. this._gl.deleteBuffer(buffer);
  13541. return true;
  13542. }
  13543. return false;
  13544. };
  13545. /**
  13546. * Creates a webGL buffer to use with instanciation
  13547. * @param capacity defines the size of the buffer
  13548. * @returns the webGL buffer
  13549. */
  13550. Engine.prototype.createInstancesBuffer = function (capacity) {
  13551. var buffer = this._gl.createBuffer();
  13552. if (!buffer) {
  13553. throw new Error("Unable to create instance buffer");
  13554. }
  13555. buffer.capacity = capacity;
  13556. this.bindArrayBuffer(buffer);
  13557. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13558. return buffer;
  13559. };
  13560. /**
  13561. * Delete a webGL buffer used with instanciation
  13562. * @param buffer defines the webGL buffer to delete
  13563. */
  13564. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13565. this._gl.deleteBuffer(buffer);
  13566. };
  13567. /**
  13568. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13569. * @param instancesBuffer defines the webGL buffer to update and bind
  13570. * @param data defines the data to store in the buffer
  13571. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13572. */
  13573. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13574. this.bindArrayBuffer(instancesBuffer);
  13575. if (data) {
  13576. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13577. }
  13578. if (offsetLocations[0].index !== undefined) {
  13579. var stride = 0;
  13580. for (var i = 0; i < offsetLocations.length; i++) {
  13581. var ai = offsetLocations[i];
  13582. stride += ai.attributeSize * 4;
  13583. }
  13584. for (var i = 0; i < offsetLocations.length; i++) {
  13585. var ai = offsetLocations[i];
  13586. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13587. this._gl.enableVertexAttribArray(ai.index);
  13588. this._vertexAttribArraysEnabled[ai.index] = true;
  13589. }
  13590. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13591. this._gl.vertexAttribDivisor(ai.index, 1);
  13592. this._currentInstanceLocations.push(ai.index);
  13593. this._currentInstanceBuffers.push(instancesBuffer);
  13594. }
  13595. }
  13596. else {
  13597. for (var index = 0; index < 4; index++) {
  13598. var offsetLocation = offsetLocations[index];
  13599. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13600. this._gl.enableVertexAttribArray(offsetLocation);
  13601. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13602. }
  13603. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13604. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13605. this._currentInstanceLocations.push(offsetLocation);
  13606. this._currentInstanceBuffers.push(instancesBuffer);
  13607. }
  13608. }
  13609. };
  13610. /**
  13611. * Apply all cached states (depth, culling, stencil and alpha)
  13612. */
  13613. Engine.prototype.applyStates = function () {
  13614. this._depthCullingState.apply(this._gl);
  13615. this._stencilState.apply(this._gl);
  13616. this._alphaState.apply(this._gl);
  13617. };
  13618. /**
  13619. * Send a draw order
  13620. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13621. * @param indexStart defines the starting index
  13622. * @param indexCount defines the number of index to draw
  13623. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13624. */
  13625. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13626. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13627. };
  13628. /**
  13629. * Draw a list of points
  13630. * @param verticesStart defines the index of first vertex to draw
  13631. * @param verticesCount defines the count of vertices to draw
  13632. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13633. */
  13634. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13635. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13636. };
  13637. /**
  13638. * Draw a list of unindexed primitives
  13639. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13640. * @param verticesStart defines the index of first vertex to draw
  13641. * @param verticesCount defines the count of vertices to draw
  13642. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13643. */
  13644. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13645. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13646. };
  13647. /**
  13648. * Draw a list of indexed primitives
  13649. * @param fillMode defines the primitive to use
  13650. * @param indexStart defines the starting index
  13651. * @param indexCount defines the number of index to draw
  13652. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13653. */
  13654. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13655. // Apply states
  13656. this.applyStates();
  13657. this._drawCalls.addCount(1, false);
  13658. // Render
  13659. var drawMode = this._drawMode(fillMode);
  13660. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13661. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13662. if (instancesCount) {
  13663. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13664. }
  13665. else {
  13666. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13667. }
  13668. };
  13669. /**
  13670. * Draw a list of unindexed primitives
  13671. * @param fillMode defines the primitive to use
  13672. * @param verticesStart defines the index of first vertex to draw
  13673. * @param verticesCount defines the count of vertices to draw
  13674. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13675. */
  13676. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13677. // Apply states
  13678. this.applyStates();
  13679. this._drawCalls.addCount(1, false);
  13680. var drawMode = this._drawMode(fillMode);
  13681. if (instancesCount) {
  13682. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13683. }
  13684. else {
  13685. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13686. }
  13687. };
  13688. Engine.prototype._drawMode = function (fillMode) {
  13689. switch (fillMode) {
  13690. // Triangle views
  13691. case BABYLON.Material.TriangleFillMode:
  13692. return this._gl.TRIANGLES;
  13693. case BABYLON.Material.PointFillMode:
  13694. return this._gl.POINTS;
  13695. case BABYLON.Material.WireFrameFillMode:
  13696. return this._gl.LINES;
  13697. // Draw modes
  13698. case BABYLON.Material.PointListDrawMode:
  13699. return this._gl.POINTS;
  13700. case BABYLON.Material.LineListDrawMode:
  13701. return this._gl.LINES;
  13702. case BABYLON.Material.LineLoopDrawMode:
  13703. return this._gl.LINE_LOOP;
  13704. case BABYLON.Material.LineStripDrawMode:
  13705. return this._gl.LINE_STRIP;
  13706. case BABYLON.Material.TriangleStripDrawMode:
  13707. return this._gl.TRIANGLE_STRIP;
  13708. case BABYLON.Material.TriangleFanDrawMode:
  13709. return this._gl.TRIANGLE_FAN;
  13710. default:
  13711. return this._gl.TRIANGLES;
  13712. }
  13713. };
  13714. // Shaders
  13715. /** @hidden */
  13716. Engine.prototype._releaseEffect = function (effect) {
  13717. if (this._compiledEffects[effect._key]) {
  13718. delete this._compiledEffects[effect._key];
  13719. this._deleteProgram(effect.getProgram());
  13720. }
  13721. };
  13722. /** @hidden */
  13723. Engine.prototype._deleteProgram = function (program) {
  13724. if (program) {
  13725. program.__SPECTOR_rebuildProgram = null;
  13726. if (program.transformFeedback) {
  13727. this.deleteTransformFeedback(program.transformFeedback);
  13728. program.transformFeedback = null;
  13729. }
  13730. this._gl.deleteProgram(program);
  13731. }
  13732. };
  13733. /**
  13734. * Create a new effect (used to store vertex/fragment shaders)
  13735. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13736. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13737. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13738. * @param samplers defines an array of string used to represent textures
  13739. * @param defines defines the string containing the defines to use to compile the shaders
  13740. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13741. * @param onCompiled defines a function to call when the effect creation is successful
  13742. * @param onError defines a function to call when the effect creation has failed
  13743. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13744. * @returns the new Effect
  13745. */
  13746. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13747. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13748. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13749. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13750. if (this._compiledEffects[name]) {
  13751. var compiledEffect = this._compiledEffects[name];
  13752. if (onCompiled && compiledEffect.isReady()) {
  13753. onCompiled(compiledEffect);
  13754. }
  13755. return compiledEffect;
  13756. }
  13757. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13758. effect._key = name;
  13759. this._compiledEffects[name] = effect;
  13760. return effect;
  13761. };
  13762. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13763. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13764. };
  13765. ;
  13766. Engine.prototype._compileRawShader = function (source, type) {
  13767. var gl = this._gl;
  13768. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13769. gl.shaderSource(shader, source);
  13770. gl.compileShader(shader);
  13771. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13772. var log = gl.getShaderInfoLog(shader);
  13773. if (log) {
  13774. throw new Error(log);
  13775. }
  13776. }
  13777. if (!shader) {
  13778. throw new Error("Something went wrong while compile the shader.");
  13779. }
  13780. return shader;
  13781. };
  13782. ;
  13783. /**
  13784. * Directly creates a webGL program
  13785. * @param vertexCode defines the vertex shader code to use
  13786. * @param fragmentCode defines the fragment shader code to use
  13787. * @param context defines the webGL context to use (if not set, the current one will be used)
  13788. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13789. * @returns the new webGL program
  13790. */
  13791. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13792. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13793. context = context || this._gl;
  13794. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13795. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13796. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13797. };
  13798. /**
  13799. * Creates a webGL program
  13800. * @param vertexCode defines the vertex shader code to use
  13801. * @param fragmentCode defines the fragment shader code to use
  13802. * @param defines defines the string containing the defines to use to compile the shaders
  13803. * @param context defines the webGL context to use (if not set, the current one will be used)
  13804. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13805. * @returns the new webGL program
  13806. */
  13807. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13808. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13809. context = context || this._gl;
  13810. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13811. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13812. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13813. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13814. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13815. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13816. return program;
  13817. };
  13818. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13819. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13820. var shaderProgram = context.createProgram();
  13821. if (!shaderProgram) {
  13822. throw new Error("Unable to create program");
  13823. }
  13824. context.attachShader(shaderProgram, vertexShader);
  13825. context.attachShader(shaderProgram, fragmentShader);
  13826. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13827. var transformFeedback = this.createTransformFeedback();
  13828. this.bindTransformFeedback(transformFeedback);
  13829. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13830. shaderProgram.transformFeedback = transformFeedback;
  13831. }
  13832. context.linkProgram(shaderProgram);
  13833. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13834. this.bindTransformFeedback(null);
  13835. }
  13836. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13837. if (!linked) {
  13838. var error = context.getProgramInfoLog(shaderProgram);
  13839. if (error) {
  13840. throw new Error(error);
  13841. }
  13842. }
  13843. if (this.validateShaderPrograms) {
  13844. context.validateProgram(shaderProgram);
  13845. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13846. if (!validated) {
  13847. var error = context.getProgramInfoLog(shaderProgram);
  13848. if (error) {
  13849. throw new Error(error);
  13850. }
  13851. }
  13852. }
  13853. context.deleteShader(vertexShader);
  13854. context.deleteShader(fragmentShader);
  13855. return shaderProgram;
  13856. };
  13857. /**
  13858. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13859. * @param shaderProgram defines the webGL program to use
  13860. * @param uniformsNames defines the list of uniform names
  13861. * @returns an array of webGL uniform locations
  13862. */
  13863. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13864. var results = new Array();
  13865. for (var index = 0; index < uniformsNames.length; index++) {
  13866. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13867. }
  13868. return results;
  13869. };
  13870. /**
  13871. * Gets the lsit of active attributes for a given webGL program
  13872. * @param shaderProgram defines the webGL program to use
  13873. * @param attributesNames defines the list of attribute names to get
  13874. * @returns an array of indices indicating the offset of each attribute
  13875. */
  13876. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13877. var results = [];
  13878. for (var index = 0; index < attributesNames.length; index++) {
  13879. try {
  13880. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13881. }
  13882. catch (e) {
  13883. results.push(-1);
  13884. }
  13885. }
  13886. return results;
  13887. };
  13888. /**
  13889. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13890. * @param effect defines the effect to activate
  13891. */
  13892. Engine.prototype.enableEffect = function (effect) {
  13893. if (!effect || effect === this._currentEffect) {
  13894. return;
  13895. }
  13896. // Use program
  13897. this.bindSamplers(effect);
  13898. this._currentEffect = effect;
  13899. if (effect.onBind) {
  13900. effect.onBind(effect);
  13901. }
  13902. if (effect._onBindObservable) {
  13903. effect._onBindObservable.notifyObservers(effect);
  13904. }
  13905. };
  13906. /**
  13907. * Set the value of an uniform to an array of int32
  13908. * @param uniform defines the webGL uniform location where to store the value
  13909. * @param array defines the array of int32 to store
  13910. */
  13911. Engine.prototype.setIntArray = function (uniform, array) {
  13912. if (!uniform)
  13913. return;
  13914. this._gl.uniform1iv(uniform, array);
  13915. };
  13916. /**
  13917. * Set the value of an uniform to an array of int32 (stored as vec2)
  13918. * @param uniform defines the webGL uniform location where to store the value
  13919. * @param array defines the array of int32 to store
  13920. */
  13921. Engine.prototype.setIntArray2 = function (uniform, array) {
  13922. if (!uniform || array.length % 2 !== 0)
  13923. return;
  13924. this._gl.uniform2iv(uniform, array);
  13925. };
  13926. /**
  13927. * Set the value of an uniform to an array of int32 (stored as vec3)
  13928. * @param uniform defines the webGL uniform location where to store the value
  13929. * @param array defines the array of int32 to store
  13930. */
  13931. Engine.prototype.setIntArray3 = function (uniform, array) {
  13932. if (!uniform || array.length % 3 !== 0)
  13933. return;
  13934. this._gl.uniform3iv(uniform, array);
  13935. };
  13936. /**
  13937. * Set the value of an uniform to an array of int32 (stored as vec4)
  13938. * @param uniform defines the webGL uniform location where to store the value
  13939. * @param array defines the array of int32 to store
  13940. */
  13941. Engine.prototype.setIntArray4 = function (uniform, array) {
  13942. if (!uniform || array.length % 4 !== 0)
  13943. return;
  13944. this._gl.uniform4iv(uniform, array);
  13945. };
  13946. /**
  13947. * Set the value of an uniform to an array of float32
  13948. * @param uniform defines the webGL uniform location where to store the value
  13949. * @param array defines the array of float32 to store
  13950. */
  13951. Engine.prototype.setFloatArray = function (uniform, array) {
  13952. if (!uniform)
  13953. return;
  13954. this._gl.uniform1fv(uniform, array);
  13955. };
  13956. /**
  13957. * Set the value of an uniform to an array of float32 (stored as vec2)
  13958. * @param uniform defines the webGL uniform location where to store the value
  13959. * @param array defines the array of float32 to store
  13960. */
  13961. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13962. if (!uniform || array.length % 2 !== 0)
  13963. return;
  13964. this._gl.uniform2fv(uniform, array);
  13965. };
  13966. /**
  13967. * Set the value of an uniform to an array of float32 (stored as vec3)
  13968. * @param uniform defines the webGL uniform location where to store the value
  13969. * @param array defines the array of float32 to store
  13970. */
  13971. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13972. if (!uniform || array.length % 3 !== 0)
  13973. return;
  13974. this._gl.uniform3fv(uniform, array);
  13975. };
  13976. /**
  13977. * Set the value of an uniform to an array of float32 (stored as vec4)
  13978. * @param uniform defines the webGL uniform location where to store the value
  13979. * @param array defines the array of float32 to store
  13980. */
  13981. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13982. if (!uniform || array.length % 4 !== 0)
  13983. return;
  13984. this._gl.uniform4fv(uniform, array);
  13985. };
  13986. /**
  13987. * Set the value of an uniform to an array of number
  13988. * @param uniform defines the webGL uniform location where to store the value
  13989. * @param array defines the array of number to store
  13990. */
  13991. Engine.prototype.setArray = function (uniform, array) {
  13992. if (!uniform)
  13993. return;
  13994. this._gl.uniform1fv(uniform, array);
  13995. };
  13996. /**
  13997. * Set the value of an uniform to an array of number (stored as vec2)
  13998. * @param uniform defines the webGL uniform location where to store the value
  13999. * @param array defines the array of number to store
  14000. */
  14001. Engine.prototype.setArray2 = function (uniform, array) {
  14002. if (!uniform || array.length % 2 !== 0)
  14003. return;
  14004. this._gl.uniform2fv(uniform, array);
  14005. };
  14006. /**
  14007. * Set the value of an uniform to an array of number (stored as vec3)
  14008. * @param uniform defines the webGL uniform location where to store the value
  14009. * @param array defines the array of number to store
  14010. */
  14011. Engine.prototype.setArray3 = function (uniform, array) {
  14012. if (!uniform || array.length % 3 !== 0)
  14013. return;
  14014. this._gl.uniform3fv(uniform, array);
  14015. };
  14016. /**
  14017. * Set the value of an uniform to an array of number (stored as vec4)
  14018. * @param uniform defines the webGL uniform location where to store the value
  14019. * @param array defines the array of number to store
  14020. */
  14021. Engine.prototype.setArray4 = function (uniform, array) {
  14022. if (!uniform || array.length % 4 !== 0)
  14023. return;
  14024. this._gl.uniform4fv(uniform, array);
  14025. };
  14026. /**
  14027. * Set the value of an uniform to an array of float32 (stored as matrices)
  14028. * @param uniform defines the webGL uniform location where to store the value
  14029. * @param matrices defines the array of float32 to store
  14030. */
  14031. Engine.prototype.setMatrices = function (uniform, matrices) {
  14032. if (!uniform)
  14033. return;
  14034. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14035. };
  14036. /**
  14037. * Set the value of an uniform to a matrix
  14038. * @param uniform defines the webGL uniform location where to store the value
  14039. * @param matrix defines the matrix to store
  14040. */
  14041. Engine.prototype.setMatrix = function (uniform, matrix) {
  14042. if (!uniform)
  14043. return;
  14044. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14045. };
  14046. /**
  14047. * Set the value of an uniform to a matrix (3x3)
  14048. * @param uniform defines the webGL uniform location where to store the value
  14049. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14050. */
  14051. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14052. if (!uniform)
  14053. return;
  14054. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14055. };
  14056. /**
  14057. * Set the value of an uniform to a matrix (2x2)
  14058. * @param uniform defines the webGL uniform location where to store the value
  14059. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14060. */
  14061. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14062. if (!uniform)
  14063. return;
  14064. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14065. };
  14066. /**
  14067. * Set the value of an uniform to a number (int)
  14068. * @param uniform defines the webGL uniform location where to store the value
  14069. * @param value defines the int number to store
  14070. */
  14071. Engine.prototype.setInt = function (uniform, value) {
  14072. if (!uniform)
  14073. return;
  14074. this._gl.uniform1i(uniform, value);
  14075. };
  14076. /**
  14077. * Set the value of an uniform to a number (float)
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param value defines the float number to store
  14080. */
  14081. Engine.prototype.setFloat = function (uniform, value) {
  14082. if (!uniform)
  14083. return;
  14084. this._gl.uniform1f(uniform, value);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to a vec2
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param x defines the 1st component of the value
  14090. * @param y defines the 2nd component of the value
  14091. */
  14092. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14093. if (!uniform)
  14094. return;
  14095. this._gl.uniform2f(uniform, x, y);
  14096. };
  14097. /**
  14098. * Set the value of an uniform to a vec3
  14099. * @param uniform defines the webGL uniform location where to store the value
  14100. * @param x defines the 1st component of the value
  14101. * @param y defines the 2nd component of the value
  14102. * @param z defines the 3rd component of the value
  14103. */
  14104. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14105. if (!uniform)
  14106. return;
  14107. this._gl.uniform3f(uniform, x, y, z);
  14108. };
  14109. /**
  14110. * Set the value of an uniform to a boolean
  14111. * @param uniform defines the webGL uniform location where to store the value
  14112. * @param bool defines the boolean to store
  14113. */
  14114. Engine.prototype.setBool = function (uniform, bool) {
  14115. if (!uniform)
  14116. return;
  14117. this._gl.uniform1i(uniform, bool);
  14118. };
  14119. /**
  14120. * Set the value of an uniform to a vec4
  14121. * @param uniform defines the webGL uniform location where to store the value
  14122. * @param x defines the 1st component of the value
  14123. * @param y defines the 2nd component of the value
  14124. * @param z defines the 3rd component of the value
  14125. * @param w defines the 4th component of the value
  14126. */
  14127. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14128. if (!uniform)
  14129. return;
  14130. this._gl.uniform4f(uniform, x, y, z, w);
  14131. };
  14132. /**
  14133. * Set the value of an uniform to a Color3
  14134. * @param uniform defines the webGL uniform location where to store the value
  14135. * @param color3 defines the color to store
  14136. */
  14137. Engine.prototype.setColor3 = function (uniform, color3) {
  14138. if (!uniform)
  14139. return;
  14140. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14141. };
  14142. /**
  14143. * Set the value of an uniform to a Color3 and an alpha value
  14144. * @param uniform defines the webGL uniform location where to store the value
  14145. * @param color3 defines the color to store
  14146. * @param alpha defines the alpha component to store
  14147. */
  14148. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14149. if (!uniform)
  14150. return;
  14151. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14152. };
  14153. /**
  14154. * Sets a Color4 on a uniform variable
  14155. * @param uniform defines the uniform location
  14156. * @param color4 defines the value to be set
  14157. */
  14158. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14159. if (!uniform)
  14160. return;
  14161. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14162. };
  14163. // States
  14164. /**
  14165. * Set various states to the webGL context
  14166. * @param culling defines backface culling state
  14167. * @param zOffset defines the value to apply to zOffset (0 by default)
  14168. * @param force defines if states must be applied even if cache is up to date
  14169. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14170. */
  14171. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14172. if (zOffset === void 0) { zOffset = 0; }
  14173. if (reverseSide === void 0) { reverseSide = false; }
  14174. // Culling
  14175. if (this._depthCullingState.cull !== culling || force) {
  14176. this._depthCullingState.cull = culling;
  14177. }
  14178. // Cull face
  14179. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14180. if (this._depthCullingState.cullFace !== cullFace || force) {
  14181. this._depthCullingState.cullFace = cullFace;
  14182. }
  14183. // Z offset
  14184. this.setZOffset(zOffset);
  14185. // Front face
  14186. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14187. if (this._depthCullingState.frontFace !== frontFace || force) {
  14188. this._depthCullingState.frontFace = frontFace;
  14189. }
  14190. };
  14191. /**
  14192. * Set the z offset to apply to current rendering
  14193. * @param value defines the offset to apply
  14194. */
  14195. Engine.prototype.setZOffset = function (value) {
  14196. this._depthCullingState.zOffset = value;
  14197. };
  14198. /**
  14199. * Gets the current value of the zOffset
  14200. * @returns the current zOffset state
  14201. */
  14202. Engine.prototype.getZOffset = function () {
  14203. return this._depthCullingState.zOffset;
  14204. };
  14205. /**
  14206. * Enable or disable depth buffering
  14207. * @param enable defines the state to set
  14208. */
  14209. Engine.prototype.setDepthBuffer = function (enable) {
  14210. this._depthCullingState.depthTest = enable;
  14211. };
  14212. /**
  14213. * Gets a boolean indicating if depth writing is enabled
  14214. * @returns the current depth writing state
  14215. */
  14216. Engine.prototype.getDepthWrite = function () {
  14217. return this._depthCullingState.depthMask;
  14218. };
  14219. /**
  14220. * Enable or disable depth writing
  14221. * @param enable defines the state to set
  14222. */
  14223. Engine.prototype.setDepthWrite = function (enable) {
  14224. this._depthCullingState.depthMask = enable;
  14225. };
  14226. /**
  14227. * Enable or disable color writing
  14228. * @param enable defines the state to set
  14229. */
  14230. Engine.prototype.setColorWrite = function (enable) {
  14231. this._gl.colorMask(enable, enable, enable, enable);
  14232. this._colorWrite = enable;
  14233. };
  14234. /**
  14235. * Gets a boolean indicating if color writing is enabled
  14236. * @returns the current color writing state
  14237. */
  14238. Engine.prototype.getColorWrite = function () {
  14239. return this._colorWrite;
  14240. };
  14241. /**
  14242. * Sets alpha constants used by some alpha blending modes
  14243. * @param r defines the red component
  14244. * @param g defines the green component
  14245. * @param b defines the blue component
  14246. * @param a defines the alpha component
  14247. */
  14248. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14249. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14250. };
  14251. /**
  14252. * Sets the current alpha mode
  14253. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14254. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14255. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14256. */
  14257. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14258. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14259. if (this._alphaMode === mode) {
  14260. return;
  14261. }
  14262. switch (mode) {
  14263. case Engine.ALPHA_DISABLE:
  14264. this._alphaState.alphaBlend = false;
  14265. break;
  14266. case Engine.ALPHA_PREMULTIPLIED:
  14267. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14268. this._alphaState.alphaBlend = true;
  14269. break;
  14270. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14271. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14272. this._alphaState.alphaBlend = true;
  14273. break;
  14274. case Engine.ALPHA_COMBINE:
  14275. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14276. this._alphaState.alphaBlend = true;
  14277. break;
  14278. case Engine.ALPHA_ONEONE:
  14279. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14280. this._alphaState.alphaBlend = true;
  14281. break;
  14282. case Engine.ALPHA_ADD:
  14283. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14284. this._alphaState.alphaBlend = true;
  14285. break;
  14286. case Engine.ALPHA_SUBTRACT:
  14287. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14288. this._alphaState.alphaBlend = true;
  14289. break;
  14290. case Engine.ALPHA_MULTIPLY:
  14291. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14292. this._alphaState.alphaBlend = true;
  14293. break;
  14294. case Engine.ALPHA_MAXIMIZED:
  14295. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14296. this._alphaState.alphaBlend = true;
  14297. break;
  14298. case Engine.ALPHA_INTERPOLATE:
  14299. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14300. this._alphaState.alphaBlend = true;
  14301. break;
  14302. case Engine.ALPHA_SCREENMODE:
  14303. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14304. this._alphaState.alphaBlend = true;
  14305. break;
  14306. }
  14307. if (!noDepthWriteChange) {
  14308. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14309. }
  14310. this._alphaMode = mode;
  14311. };
  14312. /**
  14313. * Gets the current alpha mode
  14314. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14315. * @returns the current alpha mode
  14316. */
  14317. Engine.prototype.getAlphaMode = function () {
  14318. return this._alphaMode;
  14319. };
  14320. // Textures
  14321. /**
  14322. * Clears the list of texture accessible through engine.
  14323. * This can help preventing texture load conflict due to name collision.
  14324. */
  14325. Engine.prototype.clearInternalTexturesCache = function () {
  14326. this._internalTexturesCache = [];
  14327. };
  14328. /**
  14329. * Force the entire cache to be cleared
  14330. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14331. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14332. */
  14333. Engine.prototype.wipeCaches = function (bruteForce) {
  14334. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14335. return;
  14336. }
  14337. this._currentEffect = null;
  14338. this._viewportCached.x = 0;
  14339. this._viewportCached.y = 0;
  14340. this._viewportCached.z = 0;
  14341. this._viewportCached.w = 0;
  14342. if (bruteForce) {
  14343. this.resetTextureCache();
  14344. this._currentProgram = null;
  14345. this._stencilState.reset();
  14346. this._depthCullingState.reset();
  14347. this.setDepthFunctionToLessOrEqual();
  14348. this._alphaState.reset();
  14349. this._unpackFlipYCached = null;
  14350. }
  14351. this._resetVertexBufferBinding();
  14352. this._cachedIndexBuffer = null;
  14353. this._cachedEffectForVertexBuffers = null;
  14354. this._unbindVertexArrayObject();
  14355. this.bindIndexBuffer(null);
  14356. };
  14357. /**
  14358. * Set the compressed texture format to use, based on the formats you have, and the formats
  14359. * supported by the hardware / browser.
  14360. *
  14361. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14362. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14363. * to API arguments needed to compressed textures. This puts the burden on the container
  14364. * generator to house the arcane code for determining these for current & future formats.
  14365. *
  14366. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14367. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14368. *
  14369. * Note: The result of this call is not taken into account when a texture is base64.
  14370. *
  14371. * @param formatsAvailable defines the list of those format families you have created
  14372. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14373. *
  14374. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14375. * @returns The extension selected.
  14376. */
  14377. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14378. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14379. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14380. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14381. return this._textureFormatInUse = this._texturesSupported[i];
  14382. }
  14383. }
  14384. }
  14385. // actively set format to nothing, to allow this to be called more than once
  14386. // and possibly fail the 2nd time
  14387. this._textureFormatInUse = null;
  14388. return null;
  14389. };
  14390. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14391. var gl = this._gl;
  14392. var magFilter = gl.NEAREST;
  14393. var minFilter = gl.NEAREST;
  14394. switch (samplingMode) {
  14395. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14396. magFilter = gl.LINEAR;
  14397. if (generateMipMaps) {
  14398. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14399. }
  14400. else {
  14401. minFilter = gl.LINEAR;
  14402. }
  14403. break;
  14404. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14405. magFilter = gl.LINEAR;
  14406. if (generateMipMaps) {
  14407. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14408. }
  14409. else {
  14410. minFilter = gl.LINEAR;
  14411. }
  14412. break;
  14413. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14414. magFilter = gl.NEAREST;
  14415. if (generateMipMaps) {
  14416. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14417. }
  14418. else {
  14419. minFilter = gl.NEAREST;
  14420. }
  14421. break;
  14422. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14423. magFilter = gl.NEAREST;
  14424. if (generateMipMaps) {
  14425. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14426. }
  14427. else {
  14428. minFilter = gl.NEAREST;
  14429. }
  14430. break;
  14431. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14432. magFilter = gl.NEAREST;
  14433. if (generateMipMaps) {
  14434. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14435. }
  14436. else {
  14437. minFilter = gl.LINEAR;
  14438. }
  14439. break;
  14440. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14441. magFilter = gl.NEAREST;
  14442. if (generateMipMaps) {
  14443. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14444. }
  14445. else {
  14446. minFilter = gl.LINEAR;
  14447. }
  14448. break;
  14449. case Engine.TEXTURE_NEAREST_LINEAR:
  14450. magFilter = gl.NEAREST;
  14451. minFilter = gl.LINEAR;
  14452. break;
  14453. case Engine.TEXTURE_NEAREST_NEAREST:
  14454. magFilter = gl.NEAREST;
  14455. minFilter = gl.NEAREST;
  14456. break;
  14457. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14458. magFilter = gl.LINEAR;
  14459. if (generateMipMaps) {
  14460. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14461. }
  14462. else {
  14463. minFilter = gl.NEAREST;
  14464. }
  14465. break;
  14466. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14467. magFilter = gl.LINEAR;
  14468. if (generateMipMaps) {
  14469. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14470. }
  14471. else {
  14472. minFilter = gl.NEAREST;
  14473. }
  14474. break;
  14475. case Engine.TEXTURE_LINEAR_LINEAR:
  14476. magFilter = gl.LINEAR;
  14477. minFilter = gl.LINEAR;
  14478. break;
  14479. case Engine.TEXTURE_LINEAR_NEAREST:
  14480. magFilter = gl.LINEAR;
  14481. minFilter = gl.NEAREST;
  14482. break;
  14483. }
  14484. return {
  14485. min: minFilter,
  14486. mag: magFilter
  14487. };
  14488. };
  14489. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14490. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14491. var img;
  14492. var onload = function () {
  14493. loadedImages[index] = img;
  14494. loadedImages._internalCount++;
  14495. if (scene) {
  14496. scene._removePendingData(img);
  14497. }
  14498. if (loadedImages._internalCount === 6) {
  14499. onfinish(loadedImages);
  14500. }
  14501. };
  14502. var onerror = function (message, exception) {
  14503. if (scene) {
  14504. scene._removePendingData(img);
  14505. }
  14506. if (onErrorCallBack) {
  14507. onErrorCallBack(message, exception);
  14508. }
  14509. };
  14510. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14511. if (scene) {
  14512. scene._addPendingData(img);
  14513. }
  14514. };
  14515. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14516. if (onError === void 0) { onError = null; }
  14517. var loadedImages = [];
  14518. loadedImages._internalCount = 0;
  14519. for (var index = 0; index < 6; index++) {
  14520. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14521. }
  14522. };
  14523. ;
  14524. /** @hidden */
  14525. Engine.prototype._createTexture = function () {
  14526. var texture = this._gl.createTexture();
  14527. if (!texture) {
  14528. throw new Error("Unable to create texture");
  14529. }
  14530. return texture;
  14531. };
  14532. /**
  14533. * Usually called from BABYLON.Texture.ts.
  14534. * Passed information to create a WebGLTexture
  14535. * @param urlArg defines a value which contains one of the following:
  14536. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14537. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14538. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14539. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14540. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14541. * @param scene needed for loading to the correct scene
  14542. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14543. * @param onLoad optional callback to be called upon successful completion
  14544. * @param onError optional callback to be called upon failure
  14545. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14546. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14547. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14548. * @param forcedExtension defines the extension to use to pick the right loader
  14549. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14550. */
  14551. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14552. var _this = this;
  14553. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14554. if (onLoad === void 0) { onLoad = null; }
  14555. if (onError === void 0) { onError = null; }
  14556. if (buffer === void 0) { buffer = null; }
  14557. if (fallback === void 0) { fallback = null; }
  14558. if (format === void 0) { format = null; }
  14559. if (forcedExtension === void 0) { forcedExtension = null; }
  14560. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14561. var fromData = url.substr(0, 5) === "data:";
  14562. var fromBlob = url.substr(0, 5) === "blob:";
  14563. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14564. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14565. // establish the file extension, if possible
  14566. var lastDot = url.lastIndexOf('.');
  14567. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14568. var loader = null;
  14569. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14570. var availableLoader = _a[_i];
  14571. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14572. loader = availableLoader;
  14573. break;
  14574. }
  14575. }
  14576. if (loader) {
  14577. url = loader.transformUrl(url, this._textureFormatInUse);
  14578. }
  14579. if (scene) {
  14580. scene._addPendingData(texture);
  14581. }
  14582. texture.url = url;
  14583. texture.generateMipMaps = !noMipmap;
  14584. texture.samplingMode = samplingMode;
  14585. texture.invertY = invertY;
  14586. if (!this._doNotHandleContextLost) {
  14587. // Keep a link to the buffer only if we plan to handle context lost
  14588. texture._buffer = buffer;
  14589. }
  14590. var onLoadObserver = null;
  14591. if (onLoad && !fallback) {
  14592. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14593. }
  14594. if (!fallback)
  14595. this._internalTexturesCache.push(texture);
  14596. var onInternalError = function (message, exception) {
  14597. if (scene) {
  14598. scene._removePendingData(texture);
  14599. }
  14600. var customFallback = false;
  14601. if (loader) {
  14602. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14603. if (fallbackUrl) {
  14604. // Add Back
  14605. customFallback = true;
  14606. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14607. }
  14608. }
  14609. if (!customFallback) {
  14610. if (onLoadObserver) {
  14611. texture.onLoadedObservable.remove(onLoadObserver);
  14612. }
  14613. if (BABYLON.Tools.UseFallbackTexture) {
  14614. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14615. }
  14616. }
  14617. if (onError) {
  14618. onError(message || "Unknown error", exception);
  14619. }
  14620. };
  14621. // processing for non-image formats
  14622. if (loader) {
  14623. var callback = function (data) {
  14624. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14625. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14626. done();
  14627. return false;
  14628. }, samplingMode);
  14629. });
  14630. };
  14631. if (!buffer) {
  14632. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14633. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14634. });
  14635. }
  14636. else {
  14637. callback(buffer);
  14638. }
  14639. }
  14640. else {
  14641. var onload = function (img) {
  14642. if (fromBlob && !_this._doNotHandleContextLost) {
  14643. // We need to store the image if we need to rebuild the texture
  14644. // in case of a webgl context lost
  14645. texture._buffer = img;
  14646. }
  14647. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14648. var gl = _this._gl;
  14649. var isPot = (img.width === potWidth && img.height === potHeight);
  14650. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14651. if (isPot) {
  14652. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14653. return false;
  14654. }
  14655. var maxTextureSize = _this._caps.maxTextureSize;
  14656. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14657. _this._prepareWorkingCanvas();
  14658. if (!_this._workingCanvas || !_this._workingContext) {
  14659. return false;
  14660. }
  14661. _this._workingCanvas.width = potWidth;
  14662. _this._workingCanvas.height = potHeight;
  14663. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14664. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14665. texture.width = potWidth;
  14666. texture.height = potHeight;
  14667. return false;
  14668. }
  14669. else {
  14670. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14671. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14672. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14673. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14674. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14675. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14678. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14679. _this._releaseTexture(source_1);
  14680. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14681. continuationCallback();
  14682. });
  14683. }
  14684. return true;
  14685. }, samplingMode);
  14686. };
  14687. if (!fromData || isBase64) {
  14688. if (buffer instanceof HTMLImageElement) {
  14689. onload(buffer);
  14690. }
  14691. else {
  14692. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14693. }
  14694. }
  14695. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14696. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14697. }
  14698. else {
  14699. onload(buffer);
  14700. }
  14701. }
  14702. return texture;
  14703. };
  14704. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14705. var _this = this;
  14706. var rtt = this.createRenderTargetTexture({
  14707. width: destination.width,
  14708. height: destination.height,
  14709. }, {
  14710. generateMipMaps: false,
  14711. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14712. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14713. generateDepthBuffer: false,
  14714. generateStencilBuffer: false
  14715. });
  14716. if (!this._rescalePostProcess) {
  14717. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14718. }
  14719. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14720. _this._rescalePostProcess.onApply = function (effect) {
  14721. effect._bindTexture("textureSampler", source);
  14722. };
  14723. var hostingScene = scene;
  14724. if (!hostingScene) {
  14725. hostingScene = _this.scenes[_this.scenes.length - 1];
  14726. }
  14727. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14728. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14729. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14730. _this.unBindFramebuffer(rtt);
  14731. _this._releaseTexture(rtt);
  14732. if (onComplete) {
  14733. onComplete();
  14734. }
  14735. });
  14736. };
  14737. /**
  14738. * Update a raw texture
  14739. * @param texture defines the texture to update
  14740. * @param data defines the data to store in the texture
  14741. * @param format defines the format of the data
  14742. * @param invertY defines if data must be stored with Y axis inverted
  14743. * @param compression defines the compression used (null by default)
  14744. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14745. */
  14746. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14747. if (compression === void 0) { compression = null; }
  14748. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14749. if (!texture) {
  14750. return;
  14751. }
  14752. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14753. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14754. // babylon's internalFormat but gl's texImage2D format
  14755. var internalFormat = this._getInternalFormat(format);
  14756. var textureType = this._getWebGLTextureType(type);
  14757. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14758. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14759. if (!this._doNotHandleContextLost) {
  14760. texture._bufferView = data;
  14761. texture.format = format;
  14762. texture.type = type;
  14763. texture.invertY = invertY;
  14764. texture._compression = compression;
  14765. }
  14766. if (texture.width % 4 !== 0) {
  14767. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14768. }
  14769. if (compression && data) {
  14770. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14771. }
  14772. else {
  14773. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14774. }
  14775. if (texture.generateMipMaps) {
  14776. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14777. }
  14778. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14779. // this.resetTextureCache();
  14780. texture.isReady = true;
  14781. };
  14782. /**
  14783. * Creates a raw texture
  14784. * @param data defines the data to store in the texture
  14785. * @param width defines the width of the texture
  14786. * @param height defines the height of the texture
  14787. * @param format defines the format of the data
  14788. * @param generateMipMaps defines if the engine should generate the mip levels
  14789. * @param invertY defines if data must be stored with Y axis inverted
  14790. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14791. * @param compression defines the compression used (null by default)
  14792. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14793. * @returns the raw texture inside an InternalTexture
  14794. */
  14795. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14796. if (compression === void 0) { compression = null; }
  14797. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14798. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14799. texture.baseWidth = width;
  14800. texture.baseHeight = height;
  14801. texture.width = width;
  14802. texture.height = height;
  14803. texture.format = format;
  14804. texture.generateMipMaps = generateMipMaps;
  14805. texture.samplingMode = samplingMode;
  14806. texture.invertY = invertY;
  14807. texture._compression = compression;
  14808. texture.type = type;
  14809. if (!this._doNotHandleContextLost) {
  14810. texture._bufferView = data;
  14811. }
  14812. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14813. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14814. // Filters
  14815. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14816. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14817. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14818. if (generateMipMaps) {
  14819. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14820. }
  14821. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14822. this._internalTexturesCache.push(texture);
  14823. return texture;
  14824. };
  14825. /** @hidden */
  14826. Engine.prototype._unpackFlipY = function (value) {
  14827. if (this._unpackFlipYCached !== value) {
  14828. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14829. if (this.enableUnpackFlipYCached) {
  14830. this._unpackFlipYCached = value;
  14831. }
  14832. }
  14833. };
  14834. /** @hidden */
  14835. Engine.prototype._getUnpackAlignement = function () {
  14836. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14837. };
  14838. /**
  14839. * Creates a dynamic texture
  14840. * @param width defines the width of the texture
  14841. * @param height defines the height of the texture
  14842. * @param generateMipMaps defines if the engine should generate the mip levels
  14843. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14844. * @returns the dynamic texture inside an InternalTexture
  14845. */
  14846. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14847. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14848. texture.baseWidth = width;
  14849. texture.baseHeight = height;
  14850. if (generateMipMaps) {
  14851. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14852. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14853. }
  14854. // this.resetTextureCache();
  14855. texture.width = width;
  14856. texture.height = height;
  14857. texture.isReady = false;
  14858. texture.generateMipMaps = generateMipMaps;
  14859. texture.samplingMode = samplingMode;
  14860. this.updateTextureSamplingMode(samplingMode, texture);
  14861. this._internalTexturesCache.push(texture);
  14862. return texture;
  14863. };
  14864. /**
  14865. * Update the sampling mode of a given texture
  14866. * @param samplingMode defines the required sampling mode
  14867. * @param texture defines the texture to update
  14868. */
  14869. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14870. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14871. if (texture.isCube) {
  14872. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14873. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14874. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14875. }
  14876. else if (texture.is3D) {
  14877. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14878. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14879. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14880. }
  14881. else {
  14882. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14883. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14884. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14885. }
  14886. texture.samplingMode = samplingMode;
  14887. };
  14888. /**
  14889. * Update the content of a dynamic texture
  14890. * @param texture defines the texture to update
  14891. * @param canvas defines the canvas containing the source
  14892. * @param invertY defines if data must be stored with Y axis inverted
  14893. * @param premulAlpha defines if alpha is stored as premultiplied
  14894. * @param format defines the format of the data
  14895. */
  14896. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14897. if (premulAlpha === void 0) { premulAlpha = false; }
  14898. if (!texture) {
  14899. return;
  14900. }
  14901. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14902. this._unpackFlipY(invertY);
  14903. if (premulAlpha) {
  14904. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14905. }
  14906. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14907. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14908. if (texture.generateMipMaps) {
  14909. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14910. }
  14911. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14912. if (premulAlpha) {
  14913. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14914. }
  14915. texture.isReady = true;
  14916. };
  14917. /**
  14918. * Update a video texture
  14919. * @param texture defines the texture to update
  14920. * @param video defines the video element to use
  14921. * @param invertY defines if data must be stored with Y axis inverted
  14922. */
  14923. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14924. if (!texture || texture._isDisabled) {
  14925. return;
  14926. }
  14927. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14928. this._unpackFlipY(!invertY); // Video are upside down by default
  14929. try {
  14930. // Testing video texture support
  14931. if (this._videoTextureSupported === undefined) {
  14932. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14933. if (this._gl.getError() !== 0) {
  14934. this._videoTextureSupported = false;
  14935. }
  14936. else {
  14937. this._videoTextureSupported = true;
  14938. }
  14939. }
  14940. // Copy video through the current working canvas if video texture is not supported
  14941. if (!this._videoTextureSupported) {
  14942. if (!texture._workingCanvas) {
  14943. texture._workingCanvas = document.createElement("canvas");
  14944. var context = texture._workingCanvas.getContext("2d");
  14945. if (!context) {
  14946. throw new Error("Unable to get 2d context");
  14947. }
  14948. texture._workingContext = context;
  14949. texture._workingCanvas.width = texture.width;
  14950. texture._workingCanvas.height = texture.height;
  14951. }
  14952. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14953. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14954. }
  14955. else {
  14956. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14957. }
  14958. if (texture.generateMipMaps) {
  14959. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14960. }
  14961. if (!wasPreviouslyBound) {
  14962. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14963. }
  14964. // this.resetTextureCache();
  14965. texture.isReady = true;
  14966. }
  14967. catch (ex) {
  14968. // Something unexpected
  14969. // Let's disable the texture
  14970. texture._isDisabled = true;
  14971. }
  14972. };
  14973. /**
  14974. * Updates a depth texture Comparison Mode and Function.
  14975. * If the comparison Function is equal to 0, the mode will be set to none.
  14976. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14977. * @param texture The texture to set the comparison function for
  14978. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14979. */
  14980. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14981. if (this.webGLVersion === 1) {
  14982. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14983. return;
  14984. }
  14985. var gl = this._gl;
  14986. if (texture.isCube) {
  14987. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14988. if (comparisonFunction === 0) {
  14989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14990. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14991. }
  14992. else {
  14993. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14994. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14995. }
  14996. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14997. }
  14998. else {
  14999. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15000. if (comparisonFunction === 0) {
  15001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15003. }
  15004. else {
  15005. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15007. }
  15008. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15009. }
  15010. texture._comparisonFunction = comparisonFunction;
  15011. };
  15012. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15013. var width = size.width || size;
  15014. var height = size.height || size;
  15015. internalTexture.baseWidth = width;
  15016. internalTexture.baseHeight = height;
  15017. internalTexture.width = width;
  15018. internalTexture.height = height;
  15019. internalTexture.isReady = true;
  15020. internalTexture.samples = 1;
  15021. internalTexture.generateMipMaps = false;
  15022. internalTexture._generateDepthBuffer = true;
  15023. internalTexture._generateStencilBuffer = generateStencil;
  15024. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15025. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15026. internalTexture._comparisonFunction = comparisonFunction;
  15027. var gl = this._gl;
  15028. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15029. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15030. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15031. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15032. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15033. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15034. if (comparisonFunction === 0) {
  15035. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15036. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15037. }
  15038. else {
  15039. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15040. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15041. }
  15042. };
  15043. /**
  15044. * Creates a depth stencil texture.
  15045. * This is only available in WebGL 2 or with the depth texture extension available.
  15046. * @param size The size of face edge in the texture.
  15047. * @param options The options defining the texture.
  15048. * @returns The texture
  15049. */
  15050. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15051. if (options.isCube) {
  15052. var width = size.width || size;
  15053. return this._createDepthStencilCubeTexture(width, options);
  15054. }
  15055. else {
  15056. return this._createDepthStencilTexture(size, options);
  15057. }
  15058. };
  15059. /**
  15060. * Creates a depth stencil texture.
  15061. * This is only available in WebGL 2 or with the depth texture extension available.
  15062. * @param size The size of face edge in the texture.
  15063. * @param options The options defining the texture.
  15064. * @returns The texture
  15065. */
  15066. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15067. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15068. if (!this._caps.depthTextureExtension) {
  15069. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15070. return internalTexture;
  15071. }
  15072. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15073. var gl = this._gl;
  15074. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15075. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15076. if (this.webGLVersion > 1) {
  15077. if (internalOptions.generateStencil) {
  15078. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15079. }
  15080. else {
  15081. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15082. }
  15083. }
  15084. else {
  15085. if (internalOptions.generateStencil) {
  15086. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15087. }
  15088. else {
  15089. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15090. }
  15091. }
  15092. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15093. return internalTexture;
  15094. };
  15095. /**
  15096. * Creates a depth stencil cube texture.
  15097. * This is only available in WebGL 2.
  15098. * @param size The size of face edge in the cube texture.
  15099. * @param options The options defining the cube texture.
  15100. * @returns The cube texture
  15101. */
  15102. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15103. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15104. internalTexture.isCube = true;
  15105. if (this.webGLVersion === 1) {
  15106. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15107. return internalTexture;
  15108. }
  15109. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15110. var gl = this._gl;
  15111. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15112. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15113. // Create the depth/stencil buffer
  15114. for (var face = 0; face < 6; face++) {
  15115. if (internalOptions.generateStencil) {
  15116. 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);
  15117. }
  15118. else {
  15119. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15120. }
  15121. }
  15122. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15123. return internalTexture;
  15124. };
  15125. /**
  15126. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15127. * @param renderTarget The render target to set the frame buffer for
  15128. */
  15129. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15130. // Create the framebuffer
  15131. var internalTexture = renderTarget.getInternalTexture();
  15132. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15133. return;
  15134. }
  15135. var gl = this._gl;
  15136. var depthStencilTexture = renderTarget.depthStencilTexture;
  15137. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15138. if (depthStencilTexture.isCube) {
  15139. if (depthStencilTexture._generateStencilBuffer) {
  15140. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15141. }
  15142. else {
  15143. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15144. }
  15145. }
  15146. else {
  15147. if (depthStencilTexture._generateStencilBuffer) {
  15148. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15149. }
  15150. else {
  15151. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15152. }
  15153. }
  15154. this.bindUnboundFramebuffer(null);
  15155. };
  15156. /**
  15157. * Creates a new render target texture
  15158. * @param size defines the size of the texture
  15159. * @param options defines the options used to create the texture
  15160. * @returns a new render target texture stored in an InternalTexture
  15161. */
  15162. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15163. var fullOptions = new RenderTargetCreationOptions();
  15164. if (options !== undefined && typeof options === "object") {
  15165. fullOptions.generateMipMaps = options.generateMipMaps;
  15166. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15167. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15168. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15169. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15170. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15171. }
  15172. else {
  15173. fullOptions.generateMipMaps = options;
  15174. fullOptions.generateDepthBuffer = true;
  15175. fullOptions.generateStencilBuffer = false;
  15176. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15177. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15178. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15179. }
  15180. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15181. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15182. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15183. }
  15184. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15185. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15186. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15187. }
  15188. var gl = this._gl;
  15189. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15190. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15191. var width = size.width || size;
  15192. var height = size.height || size;
  15193. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15194. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15195. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15196. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15197. }
  15198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15202. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15203. // Create the framebuffer
  15204. var currentFrameBuffer = this._currentFramebuffer;
  15205. var framebuffer = gl.createFramebuffer();
  15206. this.bindUnboundFramebuffer(framebuffer);
  15207. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15208. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15209. if (fullOptions.generateMipMaps) {
  15210. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15211. }
  15212. // Unbind
  15213. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15214. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15215. this.bindUnboundFramebuffer(currentFrameBuffer);
  15216. texture._framebuffer = framebuffer;
  15217. texture.baseWidth = width;
  15218. texture.baseHeight = height;
  15219. texture.width = width;
  15220. texture.height = height;
  15221. texture.isReady = true;
  15222. texture.samples = 1;
  15223. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15224. texture.samplingMode = fullOptions.samplingMode;
  15225. texture.type = fullOptions.type;
  15226. texture.format = fullOptions.format;
  15227. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15228. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15229. // this.resetTextureCache();
  15230. this._internalTexturesCache.push(texture);
  15231. return texture;
  15232. };
  15233. /**
  15234. * Create a multi render target texture
  15235. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15236. * @param size defines the size of the texture
  15237. * @param options defines the creation options
  15238. * @returns the cube texture as an InternalTexture
  15239. */
  15240. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15241. var generateMipMaps = false;
  15242. var generateDepthBuffer = true;
  15243. var generateStencilBuffer = false;
  15244. var generateDepthTexture = false;
  15245. var textureCount = 1;
  15246. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15247. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15248. var types = new Array();
  15249. var samplingModes = new Array();
  15250. if (options !== undefined) {
  15251. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15252. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15253. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15254. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15255. textureCount = options.textureCount || 1;
  15256. if (options.types) {
  15257. types = options.types;
  15258. }
  15259. if (options.samplingModes) {
  15260. samplingModes = options.samplingModes;
  15261. }
  15262. }
  15263. var gl = this._gl;
  15264. // Create the framebuffer
  15265. var framebuffer = gl.createFramebuffer();
  15266. this.bindUnboundFramebuffer(framebuffer);
  15267. var width = size.width || size;
  15268. var height = size.height || size;
  15269. var textures = [];
  15270. var attachments = [];
  15271. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15272. for (var i = 0; i < textureCount; i++) {
  15273. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15274. var type = types[i] || defaultType;
  15275. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15276. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15277. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15278. }
  15279. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15280. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15281. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15282. }
  15283. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15284. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15285. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15286. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15287. }
  15288. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15289. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15290. textures.push(texture);
  15291. attachments.push(attachment);
  15292. gl.activeTexture(gl["TEXTURE" + i]);
  15293. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15297. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15298. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15299. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15300. if (generateMipMaps) {
  15301. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15302. }
  15303. // Unbind
  15304. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15305. texture._framebuffer = framebuffer;
  15306. texture._depthStencilBuffer = depthStencilBuffer;
  15307. texture.baseWidth = width;
  15308. texture.baseHeight = height;
  15309. texture.width = width;
  15310. texture.height = height;
  15311. texture.isReady = true;
  15312. texture.samples = 1;
  15313. texture.generateMipMaps = generateMipMaps;
  15314. texture.samplingMode = samplingMode;
  15315. texture.type = type;
  15316. texture._generateDepthBuffer = generateDepthBuffer;
  15317. texture._generateStencilBuffer = generateStencilBuffer;
  15318. texture._attachments = attachments;
  15319. this._internalTexturesCache.push(texture);
  15320. }
  15321. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15322. // Depth texture
  15323. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15324. gl.activeTexture(gl.TEXTURE0);
  15325. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15326. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15327. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15328. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15329. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15330. 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);
  15331. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15332. depthTexture._framebuffer = framebuffer;
  15333. depthTexture.baseWidth = width;
  15334. depthTexture.baseHeight = height;
  15335. depthTexture.width = width;
  15336. depthTexture.height = height;
  15337. depthTexture.isReady = true;
  15338. depthTexture.samples = 1;
  15339. depthTexture.generateMipMaps = generateMipMaps;
  15340. depthTexture.samplingMode = gl.NEAREST;
  15341. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15342. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15343. textures.push(depthTexture);
  15344. this._internalTexturesCache.push(depthTexture);
  15345. }
  15346. gl.drawBuffers(attachments);
  15347. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15348. this.bindUnboundFramebuffer(null);
  15349. this.resetTextureCache();
  15350. return textures;
  15351. };
  15352. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15353. if (samples === void 0) { samples = 1; }
  15354. var depthStencilBuffer = null;
  15355. var gl = this._gl;
  15356. // Create the depth/stencil buffer
  15357. if (generateStencilBuffer) {
  15358. depthStencilBuffer = gl.createRenderbuffer();
  15359. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15360. if (samples > 1) {
  15361. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15362. }
  15363. else {
  15364. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15365. }
  15366. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15367. }
  15368. else if (generateDepthBuffer) {
  15369. depthStencilBuffer = gl.createRenderbuffer();
  15370. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15371. if (samples > 1) {
  15372. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15373. }
  15374. else {
  15375. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15376. }
  15377. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15378. }
  15379. return depthStencilBuffer;
  15380. };
  15381. /**
  15382. * Updates the sample count of a render target texture
  15383. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15384. * @param texture defines the texture to update
  15385. * @param samples defines the sample count to set
  15386. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15387. */
  15388. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15389. if (this.webGLVersion < 2 || !texture) {
  15390. return 1;
  15391. }
  15392. if (texture.samples === samples) {
  15393. return samples;
  15394. }
  15395. var gl = this._gl;
  15396. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15397. // Dispose previous render buffers
  15398. if (texture._depthStencilBuffer) {
  15399. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15400. texture._depthStencilBuffer = null;
  15401. }
  15402. if (texture._MSAAFramebuffer) {
  15403. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15404. texture._MSAAFramebuffer = null;
  15405. }
  15406. if (texture._MSAARenderBuffer) {
  15407. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15408. texture._MSAARenderBuffer = null;
  15409. }
  15410. if (samples > 1) {
  15411. var framebuffer = gl.createFramebuffer();
  15412. if (!framebuffer) {
  15413. throw new Error("Unable to create multi sampled framebuffer");
  15414. }
  15415. texture._MSAAFramebuffer = framebuffer;
  15416. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15417. var colorRenderbuffer = gl.createRenderbuffer();
  15418. if (!colorRenderbuffer) {
  15419. throw new Error("Unable to create multi sampled framebuffer");
  15420. }
  15421. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15422. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15423. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15424. texture._MSAARenderBuffer = colorRenderbuffer;
  15425. }
  15426. else {
  15427. this.bindUnboundFramebuffer(texture._framebuffer);
  15428. }
  15429. texture.samples = samples;
  15430. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15431. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15432. this.bindUnboundFramebuffer(null);
  15433. return samples;
  15434. };
  15435. /**
  15436. * Update the sample count for a given multiple render target texture
  15437. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15438. * @param textures defines the textures to update
  15439. * @param samples defines the sample count to set
  15440. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15441. */
  15442. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15443. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15444. return 1;
  15445. }
  15446. if (textures[0].samples === samples) {
  15447. return samples;
  15448. }
  15449. var gl = this._gl;
  15450. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15451. // Dispose previous render buffers
  15452. if (textures[0]._depthStencilBuffer) {
  15453. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15454. textures[0]._depthStencilBuffer = null;
  15455. }
  15456. if (textures[0]._MSAAFramebuffer) {
  15457. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15458. textures[0]._MSAAFramebuffer = null;
  15459. }
  15460. for (var i = 0; i < textures.length; i++) {
  15461. if (textures[i]._MSAARenderBuffer) {
  15462. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15463. textures[i]._MSAARenderBuffer = null;
  15464. }
  15465. }
  15466. if (samples > 1) {
  15467. var framebuffer = gl.createFramebuffer();
  15468. if (!framebuffer) {
  15469. throw new Error("Unable to create multi sampled framebuffer");
  15470. }
  15471. this.bindUnboundFramebuffer(framebuffer);
  15472. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15473. var attachments = [];
  15474. for (var i = 0; i < textures.length; i++) {
  15475. var texture = textures[i];
  15476. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15477. var colorRenderbuffer = gl.createRenderbuffer();
  15478. if (!colorRenderbuffer) {
  15479. throw new Error("Unable to create multi sampled framebuffer");
  15480. }
  15481. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15482. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15483. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15484. texture._MSAAFramebuffer = framebuffer;
  15485. texture._MSAARenderBuffer = colorRenderbuffer;
  15486. texture.samples = samples;
  15487. texture._depthStencilBuffer = depthStencilBuffer;
  15488. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15489. attachments.push(attachment);
  15490. }
  15491. gl.drawBuffers(attachments);
  15492. }
  15493. else {
  15494. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15495. }
  15496. this.bindUnboundFramebuffer(null);
  15497. return samples;
  15498. };
  15499. /** @hidden */
  15500. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15501. if (faceIndex === void 0) { faceIndex = 0; }
  15502. if (lod === void 0) { lod = 0; }
  15503. var gl = this._gl;
  15504. var target = gl.TEXTURE_2D;
  15505. if (texture.isCube) {
  15506. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15507. }
  15508. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15509. };
  15510. /** @hidden */
  15511. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15512. if (faceIndex === void 0) { faceIndex = 0; }
  15513. if (lod === void 0) { lod = 0; }
  15514. var gl = this._gl;
  15515. var textureType = this._getWebGLTextureType(texture.type);
  15516. var format = this._getInternalFormat(texture.format);
  15517. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15518. this._unpackFlipY(texture.invertY);
  15519. var target = gl.TEXTURE_2D;
  15520. if (texture.isCube) {
  15521. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15522. }
  15523. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15524. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15525. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15526. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15527. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15528. };
  15529. /** @hidden */
  15530. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15531. if (faceIndex === void 0) { faceIndex = 0; }
  15532. if (lod === void 0) { lod = 0; }
  15533. var gl = this._gl;
  15534. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15535. this._bindTextureDirectly(bindTarget, texture, true);
  15536. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15537. this._bindTextureDirectly(bindTarget, null, true);
  15538. };
  15539. /** @hidden */
  15540. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15541. if (faceIndex === void 0) { faceIndex = 0; }
  15542. if (lod === void 0) { lod = 0; }
  15543. var gl = this._gl;
  15544. var textureType = this._getWebGLTextureType(texture.type);
  15545. var format = this._getInternalFormat(texture.format);
  15546. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15547. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15548. this._bindTextureDirectly(bindTarget, texture, true);
  15549. this._unpackFlipY(texture.invertY);
  15550. var target = gl.TEXTURE_2D;
  15551. if (texture.isCube) {
  15552. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15553. }
  15554. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15555. this._bindTextureDirectly(bindTarget, null, true);
  15556. };
  15557. /**
  15558. * Creates a new render target cube texture
  15559. * @param size defines the size of the texture
  15560. * @param options defines the options used to create the texture
  15561. * @returns a new render target cube texture stored in an InternalTexture
  15562. */
  15563. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15564. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15565. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15566. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15567. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15568. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15569. }
  15570. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15571. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15572. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15573. }
  15574. var gl = this._gl;
  15575. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15576. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15577. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15578. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15579. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15580. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15581. }
  15582. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15583. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15584. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15586. for (var face = 0; face < 6; face++) {
  15587. 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);
  15588. }
  15589. // Create the framebuffer
  15590. var framebuffer = gl.createFramebuffer();
  15591. this.bindUnboundFramebuffer(framebuffer);
  15592. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15593. // MipMaps
  15594. if (fullOptions.generateMipMaps) {
  15595. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15596. }
  15597. // Unbind
  15598. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15599. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15600. this.bindUnboundFramebuffer(null);
  15601. texture._framebuffer = framebuffer;
  15602. texture.width = size;
  15603. texture.height = size;
  15604. texture.isReady = true;
  15605. texture.isCube = true;
  15606. texture.samples = 1;
  15607. texture.generateMipMaps = fullOptions.generateMipMaps;
  15608. texture.samplingMode = fullOptions.samplingMode;
  15609. texture.type = fullOptions.type;
  15610. texture.format = fullOptions.format;
  15611. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15612. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15613. this._internalTexturesCache.push(texture);
  15614. return texture;
  15615. };
  15616. /**
  15617. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15618. * @param rootUrl defines the url where the file to load is located
  15619. * @param scene defines the current scene
  15620. * @param lodScale defines scale to apply to the mip map selection
  15621. * @param lodOffset defines offset to apply to the mip map selection
  15622. * @param onLoad defines an optional callback raised when the texture is loaded
  15623. * @param onError defines an optional callback raised if there is an issue to load the texture
  15624. * @param format defines the format of the data
  15625. * @param forcedExtension defines the extension to use to pick the right loader
  15626. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15627. * @returns the cube texture as an InternalTexture
  15628. */
  15629. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15630. var _this = this;
  15631. if (onLoad === void 0) { onLoad = null; }
  15632. if (onError === void 0) { onError = null; }
  15633. if (forcedExtension === void 0) { forcedExtension = null; }
  15634. if (createPolynomials === void 0) { createPolynomials = true; }
  15635. var callback = function (loadData) {
  15636. if (!loadData) {
  15637. if (onLoad) {
  15638. onLoad(null);
  15639. }
  15640. return;
  15641. }
  15642. var texture = loadData.texture;
  15643. if (!createPolynomials) {
  15644. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15645. }
  15646. else if (loadData.info.sphericalPolynomial) {
  15647. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15648. }
  15649. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15650. if (_this._caps.textureLOD) {
  15651. // Do not add extra process if texture lod is supported.
  15652. if (onLoad) {
  15653. onLoad(texture);
  15654. }
  15655. return;
  15656. }
  15657. var mipSlices = 3;
  15658. var gl = _this._gl;
  15659. var width = loadData.width;
  15660. if (!width) {
  15661. return;
  15662. }
  15663. var textures = [];
  15664. for (var i = 0; i < mipSlices; i++) {
  15665. //compute LOD from even spacing in smoothness (matching shader calculation)
  15666. var smoothness = i / (mipSlices - 1);
  15667. var roughness = 1 - smoothness;
  15668. var minLODIndex = lodOffset; // roughness = 0
  15669. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15670. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15671. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15672. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15673. glTextureFromLod.type = texture.type;
  15674. glTextureFromLod.format = texture.format;
  15675. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15676. glTextureFromLod.height = glTextureFromLod.width;
  15677. glTextureFromLod.isCube = true;
  15678. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15679. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15680. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15681. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15683. if (loadData.isDDS) {
  15684. var info = loadData.info;
  15685. var data = loadData.data;
  15686. _this._unpackFlipY(info.isCompressed);
  15687. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15688. }
  15689. else {
  15690. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15691. }
  15692. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15693. // Wrap in a base texture for easy binding.
  15694. var lodTexture = new BABYLON.BaseTexture(scene);
  15695. lodTexture.isCube = true;
  15696. lodTexture._texture = glTextureFromLod;
  15697. glTextureFromLod.isReady = true;
  15698. textures.push(lodTexture);
  15699. }
  15700. texture._lodTextureHigh = textures[2];
  15701. texture._lodTextureMid = textures[1];
  15702. texture._lodTextureLow = textures[0];
  15703. if (onLoad) {
  15704. onLoad(texture);
  15705. }
  15706. };
  15707. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15708. };
  15709. /**
  15710. * Creates a cube texture
  15711. * @param rootUrl defines the url where the files to load is located
  15712. * @param scene defines the current scene
  15713. * @param files defines the list of files to load (1 per face)
  15714. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15715. * @param onLoad defines an optional callback raised when the texture is loaded
  15716. * @param onError defines an optional callback raised if there is an issue to load the texture
  15717. * @param format defines the format of the data
  15718. * @param forcedExtension defines the extension to use to pick the right loader
  15719. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15720. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15721. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15722. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15723. * @returns the cube texture as an InternalTexture
  15724. */
  15725. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15726. var _this = this;
  15727. if (onLoad === void 0) { onLoad = null; }
  15728. if (onError === void 0) { onError = null; }
  15729. if (forcedExtension === void 0) { forcedExtension = null; }
  15730. if (createPolynomials === void 0) { createPolynomials = false; }
  15731. if (lodScale === void 0) { lodScale = 0; }
  15732. if (lodOffset === void 0) { lodOffset = 0; }
  15733. if (fallback === void 0) { fallback = null; }
  15734. var gl = this._gl;
  15735. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15736. texture.isCube = true;
  15737. texture.url = rootUrl;
  15738. texture.generateMipMaps = !noMipmap;
  15739. texture._lodGenerationScale = lodScale;
  15740. texture._lodGenerationOffset = lodOffset;
  15741. if (!this._doNotHandleContextLost) {
  15742. texture._extension = forcedExtension;
  15743. texture._files = files;
  15744. }
  15745. var lastDot = rootUrl.lastIndexOf('.');
  15746. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15747. var loader = null;
  15748. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15749. var availableLoader = _a[_i];
  15750. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15751. loader = availableLoader;
  15752. break;
  15753. }
  15754. }
  15755. var onInternalError = function (request, exception) {
  15756. if (loader) {
  15757. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15758. if (fallbackUrl) {
  15759. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15760. }
  15761. }
  15762. if (onError && request) {
  15763. onError(request.status + " " + request.statusText, exception);
  15764. }
  15765. };
  15766. if (loader) {
  15767. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15768. var onloaddata = function (data) {
  15769. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15770. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15771. };
  15772. if (files && files.length === 6) {
  15773. if (loader.supportCascades) {
  15774. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15775. }
  15776. else if (onError) {
  15777. onError("Textures type does not support cascades.");
  15778. }
  15779. }
  15780. else {
  15781. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15782. }
  15783. }
  15784. else {
  15785. if (!files) {
  15786. throw new Error("Cannot load cubemap because files were not defined");
  15787. }
  15788. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15789. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15790. var height = width;
  15791. _this._prepareWorkingCanvas();
  15792. if (!_this._workingCanvas || !_this._workingContext) {
  15793. return;
  15794. }
  15795. _this._workingCanvas.width = width;
  15796. _this._workingCanvas.height = height;
  15797. var faces = [
  15798. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15799. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15800. ];
  15801. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15802. _this._unpackFlipY(false);
  15803. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15804. for (var index = 0; index < faces.length; index++) {
  15805. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15806. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15807. }
  15808. if (!noMipmap) {
  15809. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15810. }
  15811. _this._setCubeMapTextureParams(!noMipmap);
  15812. texture.width = width;
  15813. texture.height = height;
  15814. texture.isReady = true;
  15815. if (format) {
  15816. texture.format = format;
  15817. }
  15818. texture.onLoadedObservable.notifyObservers(texture);
  15819. texture.onLoadedObservable.clear();
  15820. if (onLoad) {
  15821. onLoad();
  15822. }
  15823. }, files, onError);
  15824. }
  15825. this._internalTexturesCache.push(texture);
  15826. return texture;
  15827. };
  15828. /**
  15829. * @hidden
  15830. */
  15831. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15832. var gl = this._gl;
  15833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15837. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15838. // this.resetTextureCache();
  15839. };
  15840. /**
  15841. * Update a raw cube texture
  15842. * @param texture defines the texture to udpdate
  15843. * @param data defines the data to store
  15844. * @param format defines the data format
  15845. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15846. * @param invertY defines if data must be stored with Y axis inverted
  15847. * @param compression defines the compression used (null by default)
  15848. * @param level defines which level of the texture to update
  15849. */
  15850. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15851. if (compression === void 0) { compression = null; }
  15852. if (level === void 0) { level = 0; }
  15853. texture._bufferViewArray = data;
  15854. texture.format = format;
  15855. texture.type = type;
  15856. texture.invertY = invertY;
  15857. texture._compression = compression;
  15858. var gl = this._gl;
  15859. var textureType = this._getWebGLTextureType(type);
  15860. var internalFormat = this._getInternalFormat(format);
  15861. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15862. var needConversion = false;
  15863. if (internalFormat === gl.RGB) {
  15864. internalFormat = gl.RGBA;
  15865. needConversion = true;
  15866. }
  15867. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15868. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15869. if (texture.width % 4 !== 0) {
  15870. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15871. }
  15872. // Data are known to be in +X +Y +Z -X -Y -Z
  15873. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15874. var faceData = data[faceIndex];
  15875. if (compression) {
  15876. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15877. }
  15878. else {
  15879. if (needConversion) {
  15880. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15881. }
  15882. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15883. }
  15884. }
  15885. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15886. if (isPot && texture.generateMipMaps && level === 0) {
  15887. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15888. }
  15889. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15890. // this.resetTextureCache();
  15891. texture.isReady = true;
  15892. };
  15893. /**
  15894. * Creates a new raw cube texture
  15895. * @param data defines the array of data to use to create each face
  15896. * @param size defines the size of the textures
  15897. * @param format defines the format of the data
  15898. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15899. * @param generateMipMaps defines if the engine should generate the mip levels
  15900. * @param invertY defines if data must be stored with Y axis inverted
  15901. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15902. * @param compression defines the compression used (null by default)
  15903. * @returns the cube texture as an InternalTexture
  15904. */
  15905. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15906. if (compression === void 0) { compression = null; }
  15907. var gl = this._gl;
  15908. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15909. texture.isCube = true;
  15910. texture.format = format;
  15911. texture.type = type;
  15912. if (!this._doNotHandleContextLost) {
  15913. texture._bufferViewArray = data;
  15914. }
  15915. var textureType = this._getWebGLTextureType(type);
  15916. var internalFormat = this._getInternalFormat(format);
  15917. if (internalFormat === gl.RGB) {
  15918. internalFormat = gl.RGBA;
  15919. }
  15920. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15921. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15922. generateMipMaps = false;
  15923. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15924. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15925. }
  15926. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15927. generateMipMaps = false;
  15928. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15929. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15930. }
  15931. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15932. generateMipMaps = false;
  15933. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15934. }
  15935. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15936. generateMipMaps = false;
  15937. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15938. }
  15939. var width = size;
  15940. var height = width;
  15941. texture.width = width;
  15942. texture.height = height;
  15943. // Double check on POT to generate Mips.
  15944. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15945. if (!isPot) {
  15946. generateMipMaps = false;
  15947. }
  15948. // Upload data if needed. The texture won't be ready until then.
  15949. if (data) {
  15950. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15951. }
  15952. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15953. // Filters
  15954. if (data && generateMipMaps) {
  15955. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15956. }
  15957. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15962. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15963. texture.generateMipMaps = generateMipMaps;
  15964. return texture;
  15965. };
  15966. /**
  15967. * Creates a new raw cube texture from a specified url
  15968. * @param url defines the url where the data is located
  15969. * @param scene defines the current scene
  15970. * @param size defines the size of the textures
  15971. * @param format defines the format of the data
  15972. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15973. * @param noMipmap defines if the engine should avoid generating the mip levels
  15974. * @param callback defines a callback used to extract texture data from loaded data
  15975. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15976. * @param onLoad defines a callback called when texture is loaded
  15977. * @param onError defines a callback called if there is an error
  15978. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15979. * @param invertY defines if data must be stored with Y axis inverted
  15980. * @returns the cube texture as an InternalTexture
  15981. */
  15982. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15983. var _this = this;
  15984. if (onLoad === void 0) { onLoad = null; }
  15985. if (onError === void 0) { onError = null; }
  15986. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15987. if (invertY === void 0) { invertY = false; }
  15988. var gl = this._gl;
  15989. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15990. scene._addPendingData(texture);
  15991. texture.url = url;
  15992. this._internalTexturesCache.push(texture);
  15993. var onerror = function (request, exception) {
  15994. scene._removePendingData(texture);
  15995. if (onError && request) {
  15996. onError(request.status + " " + request.statusText, exception);
  15997. }
  15998. };
  15999. var internalCallback = function (data) {
  16000. var width = texture.width;
  16001. var faceDataArrays = callback(data);
  16002. if (!faceDataArrays) {
  16003. return;
  16004. }
  16005. if (mipmapGenerator) {
  16006. var textureType = _this._getWebGLTextureType(type);
  16007. var internalFormat = _this._getInternalFormat(format);
  16008. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16009. var needConversion = false;
  16010. if (internalFormat === gl.RGB) {
  16011. internalFormat = gl.RGBA;
  16012. needConversion = true;
  16013. }
  16014. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16015. _this._unpackFlipY(false);
  16016. var mipData = mipmapGenerator(faceDataArrays);
  16017. for (var level = 0; level < mipData.length; level++) {
  16018. var mipSize = width >> level;
  16019. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16020. var mipFaceData = mipData[level][faceIndex];
  16021. if (needConversion) {
  16022. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16023. }
  16024. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16025. }
  16026. }
  16027. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16028. }
  16029. else {
  16030. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16031. }
  16032. texture.isReady = true;
  16033. // this.resetTextureCache();
  16034. scene._removePendingData(texture);
  16035. if (onLoad) {
  16036. onLoad();
  16037. }
  16038. };
  16039. this._loadFile(url, function (data) {
  16040. internalCallback(data);
  16041. }, undefined, scene.database, true, onerror);
  16042. return texture;
  16043. };
  16044. ;
  16045. /**
  16046. * Update a raw 3D texture
  16047. * @param texture defines the texture to update
  16048. * @param data defines the data to store
  16049. * @param format defines the data format
  16050. * @param invertY defines if data must be stored with Y axis inverted
  16051. * @param compression defines the used compression (can be null)
  16052. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16053. */
  16054. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16055. if (compression === void 0) { compression = null; }
  16056. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16057. var internalType = this._getWebGLTextureType(textureType);
  16058. var internalFormat = this._getInternalFormat(format);
  16059. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16060. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16061. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16062. if (!this._doNotHandleContextLost) {
  16063. texture._bufferView = data;
  16064. texture.format = format;
  16065. texture.invertY = invertY;
  16066. texture._compression = compression;
  16067. }
  16068. if (texture.width % 4 !== 0) {
  16069. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16070. }
  16071. if (compression && data) {
  16072. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16073. }
  16074. else {
  16075. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16076. }
  16077. if (texture.generateMipMaps) {
  16078. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16079. }
  16080. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16081. // this.resetTextureCache();
  16082. texture.isReady = true;
  16083. };
  16084. /**
  16085. * Creates a new raw 3D texture
  16086. * @param data defines the data used to create the texture
  16087. * @param width defines the width of the texture
  16088. * @param height defines the height of the texture
  16089. * @param depth defines the depth of the texture
  16090. * @param format defines the format of the texture
  16091. * @param generateMipMaps defines if the engine must generate mip levels
  16092. * @param invertY defines if data must be stored with Y axis inverted
  16093. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16094. * @param compression defines the compressed used (can be null)
  16095. * @param textureType defines the compressed used (can be null)
  16096. * @returns a new raw 3D texture (stored in an InternalTexture)
  16097. */
  16098. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16099. if (compression === void 0) { compression = null; }
  16100. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16101. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16102. texture.baseWidth = width;
  16103. texture.baseHeight = height;
  16104. texture.baseDepth = depth;
  16105. texture.width = width;
  16106. texture.height = height;
  16107. texture.depth = depth;
  16108. texture.format = format;
  16109. texture.type = textureType;
  16110. texture.generateMipMaps = generateMipMaps;
  16111. texture.samplingMode = samplingMode;
  16112. texture.is3D = true;
  16113. if (!this._doNotHandleContextLost) {
  16114. texture._bufferView = data;
  16115. }
  16116. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16117. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16118. // Filters
  16119. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16120. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16121. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16122. if (generateMipMaps) {
  16123. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16124. }
  16125. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16126. this._internalTexturesCache.push(texture);
  16127. return texture;
  16128. };
  16129. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16130. var gl = this._gl;
  16131. if (!gl) {
  16132. return;
  16133. }
  16134. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16137. if (!noMipmap && !isCompressed) {
  16138. gl.generateMipmap(gl.TEXTURE_2D);
  16139. }
  16140. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16141. // this.resetTextureCache();
  16142. if (scene) {
  16143. scene._removePendingData(texture);
  16144. }
  16145. texture.onLoadedObservable.notifyObservers(texture);
  16146. texture.onLoadedObservable.clear();
  16147. };
  16148. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16149. var _this = this;
  16150. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16151. var maxTextureSize = this.getCaps().maxTextureSize;
  16152. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16153. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16154. var gl = this._gl;
  16155. if (!gl) {
  16156. return;
  16157. }
  16158. if (!texture._webGLTexture) {
  16159. // this.resetTextureCache();
  16160. if (scene) {
  16161. scene._removePendingData(texture);
  16162. }
  16163. return;
  16164. }
  16165. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16166. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16167. texture.baseWidth = width;
  16168. texture.baseHeight = height;
  16169. texture.width = potWidth;
  16170. texture.height = potHeight;
  16171. texture.isReady = true;
  16172. if (processFunction(potWidth, potHeight, function () {
  16173. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16174. })) {
  16175. // Returning as texture needs extra async steps
  16176. return;
  16177. }
  16178. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16179. };
  16180. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16181. // Create new RGBA data container.
  16182. var rgbaData;
  16183. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16184. rgbaData = new Float32Array(width * height * 4);
  16185. }
  16186. else {
  16187. rgbaData = new Uint32Array(width * height * 4);
  16188. }
  16189. // Convert each pixel.
  16190. for (var x = 0; x < width; x++) {
  16191. for (var y = 0; y < height; y++) {
  16192. var index = (y * width + x) * 3;
  16193. var newIndex = (y * width + x) * 4;
  16194. // Map Old Value to new value.
  16195. rgbaData[newIndex + 0] = rgbData[index + 0];
  16196. rgbaData[newIndex + 1] = rgbData[index + 1];
  16197. rgbaData[newIndex + 2] = rgbData[index + 2];
  16198. // Add fully opaque alpha channel.
  16199. rgbaData[newIndex + 3] = 1;
  16200. }
  16201. }
  16202. return rgbaData;
  16203. };
  16204. /** @hidden */
  16205. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16206. var gl = this._gl;
  16207. if (texture._framebuffer) {
  16208. gl.deleteFramebuffer(texture._framebuffer);
  16209. texture._framebuffer = null;
  16210. }
  16211. if (texture._depthStencilBuffer) {
  16212. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16213. texture._depthStencilBuffer = null;
  16214. }
  16215. if (texture._MSAAFramebuffer) {
  16216. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16217. texture._MSAAFramebuffer = null;
  16218. }
  16219. if (texture._MSAARenderBuffer) {
  16220. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16221. texture._MSAARenderBuffer = null;
  16222. }
  16223. };
  16224. /** @hidden */
  16225. Engine.prototype._releaseTexture = function (texture) {
  16226. var gl = this._gl;
  16227. this._releaseFramebufferObjects(texture);
  16228. gl.deleteTexture(texture._webGLTexture);
  16229. // Unbind channels
  16230. this.unbindAllTextures();
  16231. var index = this._internalTexturesCache.indexOf(texture);
  16232. if (index !== -1) {
  16233. this._internalTexturesCache.splice(index, 1);
  16234. }
  16235. // Integrated fixed lod samplers.
  16236. if (texture._lodTextureHigh) {
  16237. texture._lodTextureHigh.dispose();
  16238. }
  16239. if (texture._lodTextureMid) {
  16240. texture._lodTextureMid.dispose();
  16241. }
  16242. if (texture._lodTextureLow) {
  16243. texture._lodTextureLow.dispose();
  16244. }
  16245. // Set output texture of post process to null if the texture has been released/disposed
  16246. this.scenes.forEach(function (scene) {
  16247. scene.postProcesses.forEach(function (postProcess) {
  16248. if (postProcess._outputTexture == texture) {
  16249. postProcess._outputTexture = null;
  16250. }
  16251. });
  16252. scene.cameras.forEach(function (camera) {
  16253. camera._postProcesses.forEach(function (postProcess) {
  16254. if (postProcess) {
  16255. if (postProcess._outputTexture == texture) {
  16256. postProcess._outputTexture = null;
  16257. }
  16258. }
  16259. });
  16260. });
  16261. });
  16262. };
  16263. Engine.prototype.setProgram = function (program) {
  16264. if (this._currentProgram !== program) {
  16265. this._gl.useProgram(program);
  16266. this._currentProgram = program;
  16267. }
  16268. };
  16269. /**
  16270. * Binds an effect to the webGL context
  16271. * @param effect defines the effect to bind
  16272. */
  16273. Engine.prototype.bindSamplers = function (effect) {
  16274. this.setProgram(effect.getProgram());
  16275. var samplers = effect.getSamplers();
  16276. for (var index = 0; index < samplers.length; index++) {
  16277. var uniform = effect.getUniform(samplers[index]);
  16278. if (uniform) {
  16279. this._boundUniforms[index] = uniform;
  16280. }
  16281. }
  16282. this._currentEffect = null;
  16283. };
  16284. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16285. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16286. return;
  16287. }
  16288. // Remove
  16289. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16290. // Bind last to it
  16291. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16292. // Bind to dummy
  16293. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16294. };
  16295. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16296. if (!internalTexture) {
  16297. return -1;
  16298. }
  16299. internalTexture._initialSlot = channel;
  16300. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16301. if (channel !== internalTexture._designatedSlot) {
  16302. this._textureCollisions.addCount(1, false);
  16303. }
  16304. }
  16305. else {
  16306. if (channel !== internalTexture._designatedSlot) {
  16307. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16308. return internalTexture._designatedSlot;
  16309. }
  16310. else {
  16311. // No slot for this texture, let's pick a new one (if we find a free slot)
  16312. if (this._nextFreeTextureSlots.length) {
  16313. return this._nextFreeTextureSlots[0];
  16314. }
  16315. // We need to recycle the oldest bound texture, sorry.
  16316. this._textureCollisions.addCount(1, false);
  16317. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16318. }
  16319. }
  16320. }
  16321. return channel;
  16322. };
  16323. Engine.prototype._linkTrackers = function (previous, next) {
  16324. previous.next = next;
  16325. next.previous = previous;
  16326. };
  16327. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16328. var currentSlot = internalTexture._designatedSlot;
  16329. if (currentSlot === -1) {
  16330. return -1;
  16331. }
  16332. internalTexture._designatedSlot = -1;
  16333. if (this.disableTextureBindingOptimization) {
  16334. return -1;
  16335. }
  16336. // Remove from bound list
  16337. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16338. // Free the slot
  16339. this._boundTexturesCache[currentSlot] = null;
  16340. this._nextFreeTextureSlots.push(currentSlot);
  16341. return currentSlot;
  16342. };
  16343. Engine.prototype._activateCurrentTexture = function () {
  16344. if (this._currentTextureChannel !== this._activeChannel) {
  16345. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16346. this._currentTextureChannel = this._activeChannel;
  16347. }
  16348. };
  16349. /** @hidden */
  16350. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16351. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16352. if (force === void 0) { force = false; }
  16353. var wasPreviouslyBound = false;
  16354. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16355. this._activeChannel = texture._designatedSlot;
  16356. }
  16357. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16358. var isTextureForRendering = texture && texture._initialSlot > -1;
  16359. if (currentTextureBound !== texture || force) {
  16360. if (currentTextureBound) {
  16361. this._removeDesignatedSlot(currentTextureBound);
  16362. }
  16363. this._activateCurrentTexture();
  16364. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16365. this._boundTexturesCache[this._activeChannel] = texture;
  16366. if (texture) {
  16367. if (!this.disableTextureBindingOptimization) {
  16368. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16369. if (slotIndex > -1) {
  16370. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16371. }
  16372. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16373. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16374. }
  16375. texture._designatedSlot = this._activeChannel;
  16376. }
  16377. }
  16378. else if (forTextureDataUpdate) {
  16379. wasPreviouslyBound = true;
  16380. this._activateCurrentTexture();
  16381. }
  16382. if (isTextureForRendering && !forTextureDataUpdate) {
  16383. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16384. }
  16385. return wasPreviouslyBound;
  16386. };
  16387. /** @hidden */
  16388. Engine.prototype._bindTexture = function (channel, texture) {
  16389. if (channel < 0) {
  16390. return;
  16391. }
  16392. if (texture) {
  16393. channel = this._getCorrectTextureChannel(channel, texture);
  16394. }
  16395. this._activeChannel = channel;
  16396. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16397. };
  16398. /**
  16399. * Sets a texture to the webGL context from a postprocess
  16400. * @param channel defines the channel to use
  16401. * @param postProcess defines the source postprocess
  16402. */
  16403. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16404. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16405. };
  16406. /**
  16407. * Binds the output of the passed in post process to the texture channel specified
  16408. * @param channel The channel the texture should be bound to
  16409. * @param postProcess The post process which's output should be bound
  16410. */
  16411. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16412. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16413. };
  16414. /**
  16415. * Unbind all textures from the webGL context
  16416. */
  16417. Engine.prototype.unbindAllTextures = function () {
  16418. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16419. this._activeChannel = channel;
  16420. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16421. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16422. if (this.webGLVersion > 1) {
  16423. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16424. }
  16425. }
  16426. };
  16427. /**
  16428. * Sets a texture to the according uniform.
  16429. * @param channel The texture channel
  16430. * @param uniform The uniform to set
  16431. * @param texture The texture to apply
  16432. */
  16433. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16434. if (channel < 0) {
  16435. return;
  16436. }
  16437. if (uniform) {
  16438. this._boundUniforms[channel] = uniform;
  16439. }
  16440. this._setTexture(channel, texture);
  16441. };
  16442. /**
  16443. * Sets a depth stencil texture from a render target to the according uniform.
  16444. * @param channel The texture channel
  16445. * @param uniform The uniform to set
  16446. * @param texture The render target texture containing the depth stencil texture to apply
  16447. */
  16448. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16449. if (channel < 0) {
  16450. return;
  16451. }
  16452. if (uniform) {
  16453. this._boundUniforms[channel] = uniform;
  16454. }
  16455. if (!texture || !texture.depthStencilTexture) {
  16456. this._setTexture(channel, null);
  16457. }
  16458. else {
  16459. this._setTexture(channel, texture, false, true);
  16460. }
  16461. };
  16462. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16463. var uniform = this._boundUniforms[sourceSlot];
  16464. if (uniform._currentState === destination) {
  16465. return;
  16466. }
  16467. this._gl.uniform1i(uniform, destination);
  16468. uniform._currentState = destination;
  16469. };
  16470. Engine.prototype._getTextureWrapMode = function (mode) {
  16471. switch (mode) {
  16472. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16473. return this._gl.REPEAT;
  16474. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16475. return this._gl.CLAMP_TO_EDGE;
  16476. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16477. return this._gl.MIRRORED_REPEAT;
  16478. }
  16479. return this._gl.REPEAT;
  16480. };
  16481. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16482. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16483. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16484. // Not ready?
  16485. if (!texture) {
  16486. if (this._boundTexturesCache[channel] != null) {
  16487. this._activeChannel = channel;
  16488. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16489. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16490. if (this.webGLVersion > 1) {
  16491. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16492. }
  16493. }
  16494. return false;
  16495. }
  16496. // Video
  16497. if (texture.video) {
  16498. this._activeChannel = channel;
  16499. texture.update();
  16500. }
  16501. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16502. texture.delayLoad();
  16503. return false;
  16504. }
  16505. var internalTexture;
  16506. if (depthStencilTexture) {
  16507. internalTexture = texture.depthStencilTexture;
  16508. }
  16509. else if (texture.isReady()) {
  16510. internalTexture = texture.getInternalTexture();
  16511. }
  16512. else if (texture.isCube) {
  16513. internalTexture = this.emptyCubeTexture;
  16514. }
  16515. else if (texture.is3D) {
  16516. internalTexture = this.emptyTexture3D;
  16517. }
  16518. else {
  16519. internalTexture = this.emptyTexture;
  16520. }
  16521. if (!isPartOfTextureArray) {
  16522. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16523. }
  16524. var needToBind = true;
  16525. if (this._boundTexturesCache[channel] === internalTexture) {
  16526. this._moveBoundTextureOnTop(internalTexture);
  16527. if (!isPartOfTextureArray) {
  16528. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16529. }
  16530. needToBind = false;
  16531. }
  16532. this._activeChannel = channel;
  16533. if (internalTexture && internalTexture.is3D) {
  16534. if (needToBind) {
  16535. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16536. }
  16537. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16538. internalTexture._cachedWrapU = texture.wrapU;
  16539. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16540. }
  16541. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16542. internalTexture._cachedWrapV = texture.wrapV;
  16543. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16544. }
  16545. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16546. internalTexture._cachedWrapR = texture.wrapR;
  16547. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16548. }
  16549. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16550. }
  16551. else if (internalTexture && internalTexture.isCube) {
  16552. if (needToBind) {
  16553. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16554. }
  16555. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16556. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16557. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16558. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16559. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16560. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16561. }
  16562. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16563. }
  16564. else {
  16565. if (needToBind) {
  16566. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16567. }
  16568. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16569. internalTexture._cachedWrapU = texture.wrapU;
  16570. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16571. }
  16572. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16573. internalTexture._cachedWrapV = texture.wrapV;
  16574. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16575. }
  16576. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16577. }
  16578. return true;
  16579. };
  16580. /**
  16581. * Sets an array of texture to the webGL context
  16582. * @param channel defines the channel where the texture array must be set
  16583. * @param uniform defines the associated uniform location
  16584. * @param textures defines the array of textures to bind
  16585. */
  16586. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16587. if (channel < 0 || !uniform) {
  16588. return;
  16589. }
  16590. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16591. this._textureUnits = new Int32Array(textures.length);
  16592. }
  16593. for (var i = 0; i < textures.length; i++) {
  16594. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16595. }
  16596. this._gl.uniform1iv(uniform, this._textureUnits);
  16597. for (var index = 0; index < textures.length; index++) {
  16598. this._setTexture(this._textureUnits[index], textures[index], true);
  16599. }
  16600. };
  16601. /** @hidden */
  16602. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16603. var internalTexture = texture.getInternalTexture();
  16604. if (!internalTexture) {
  16605. return;
  16606. }
  16607. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16608. var value = texture.anisotropicFilteringLevel;
  16609. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16610. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16611. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16612. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16613. }
  16614. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16615. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16616. internalTexture._cachedAnisotropicFilteringLevel = value;
  16617. }
  16618. };
  16619. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16620. this._bindTextureDirectly(target, texture, true, true);
  16621. this._gl.texParameterf(target, parameter, value);
  16622. };
  16623. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16624. if (texture) {
  16625. this._bindTextureDirectly(target, texture, true, true);
  16626. }
  16627. this._gl.texParameteri(target, parameter, value);
  16628. };
  16629. /**
  16630. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16631. * @param x defines the x coordinate of the rectangle where pixels must be read
  16632. * @param y defines the y coordinate of the rectangle where pixels must be read
  16633. * @param width defines the width of the rectangle where pixels must be read
  16634. * @param height defines the height of the rectangle where pixels must be read
  16635. * @returns a Uint8Array containing RGBA colors
  16636. */
  16637. Engine.prototype.readPixels = function (x, y, width, height) {
  16638. var data = new Uint8Array(height * width * 4);
  16639. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16640. return data;
  16641. };
  16642. /**
  16643. * Add an externaly attached data from its key.
  16644. * This method call will fail and return false, if such key already exists.
  16645. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16646. * @param key the unique key that identifies the data
  16647. * @param data the data object to associate to the key for this Engine instance
  16648. * @return true if no such key were already present and the data was added successfully, false otherwise
  16649. */
  16650. Engine.prototype.addExternalData = function (key, data) {
  16651. if (!this._externalData) {
  16652. this._externalData = new BABYLON.StringDictionary();
  16653. }
  16654. return this._externalData.add(key, data);
  16655. };
  16656. /**
  16657. * Get an externaly attached data from its key
  16658. * @param key the unique key that identifies the data
  16659. * @return the associated data, if present (can be null), or undefined if not present
  16660. */
  16661. Engine.prototype.getExternalData = function (key) {
  16662. if (!this._externalData) {
  16663. this._externalData = new BABYLON.StringDictionary();
  16664. }
  16665. return this._externalData.get(key);
  16666. };
  16667. /**
  16668. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16669. * @param key the unique key that identifies the data
  16670. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16671. * @return the associated data, can be null if the factory returned null.
  16672. */
  16673. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16674. if (!this._externalData) {
  16675. this._externalData = new BABYLON.StringDictionary();
  16676. }
  16677. return this._externalData.getOrAddWithFactory(key, factory);
  16678. };
  16679. /**
  16680. * Remove an externaly attached data from the Engine instance
  16681. * @param key the unique key that identifies the data
  16682. * @return true if the data was successfully removed, false if it doesn't exist
  16683. */
  16684. Engine.prototype.removeExternalData = function (key) {
  16685. if (!this._externalData) {
  16686. this._externalData = new BABYLON.StringDictionary();
  16687. }
  16688. return this._externalData.remove(key);
  16689. };
  16690. /**
  16691. * Unbind all vertex attributes from the webGL context
  16692. */
  16693. Engine.prototype.unbindAllAttributes = function () {
  16694. if (this._mustWipeVertexAttributes) {
  16695. this._mustWipeVertexAttributes = false;
  16696. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16697. this._gl.disableVertexAttribArray(i);
  16698. this._vertexAttribArraysEnabled[i] = false;
  16699. this._currentBufferPointers[i].active = false;
  16700. }
  16701. return;
  16702. }
  16703. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16704. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16705. continue;
  16706. }
  16707. this._gl.disableVertexAttribArray(i);
  16708. this._vertexAttribArraysEnabled[i] = false;
  16709. this._currentBufferPointers[i].active = false;
  16710. }
  16711. };
  16712. /**
  16713. * 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
  16714. */
  16715. Engine.prototype.releaseEffects = function () {
  16716. for (var name in this._compiledEffects) {
  16717. this._deleteProgram(this._compiledEffects[name]._program);
  16718. }
  16719. this._compiledEffects = {};
  16720. };
  16721. /**
  16722. * Dispose and release all associated resources
  16723. */
  16724. Engine.prototype.dispose = function () {
  16725. this.hideLoadingUI();
  16726. this.stopRenderLoop();
  16727. // Release postProcesses
  16728. while (this.postProcesses.length) {
  16729. this.postProcesses[0].dispose();
  16730. }
  16731. // Empty texture
  16732. if (this._emptyTexture) {
  16733. this._releaseTexture(this._emptyTexture);
  16734. this._emptyTexture = null;
  16735. }
  16736. if (this._emptyCubeTexture) {
  16737. this._releaseTexture(this._emptyCubeTexture);
  16738. this._emptyCubeTexture = null;
  16739. }
  16740. // Rescale PP
  16741. if (this._rescalePostProcess) {
  16742. this._rescalePostProcess.dispose();
  16743. }
  16744. // Release scenes
  16745. while (this.scenes.length) {
  16746. this.scenes[0].dispose();
  16747. }
  16748. // Release audio engine
  16749. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16750. Engine.audioEngine.dispose();
  16751. }
  16752. // Release effects
  16753. this.releaseEffects();
  16754. // Unbind
  16755. this.unbindAllAttributes();
  16756. this._boundUniforms = [];
  16757. if (this._dummyFramebuffer) {
  16758. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16759. }
  16760. //WebVR
  16761. this.disableVR();
  16762. // Events
  16763. if (BABYLON.Tools.IsWindowObjectExist()) {
  16764. window.removeEventListener("blur", this._onBlur);
  16765. window.removeEventListener("focus", this._onFocus);
  16766. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16767. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16768. if (this._renderingCanvas) {
  16769. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16770. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16771. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16772. if (!this._doNotHandleContextLost) {
  16773. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16774. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16775. }
  16776. }
  16777. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16778. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16779. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16780. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16781. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16782. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16783. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16784. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16785. if (this._onVrDisplayConnect) {
  16786. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16787. if (this._onVrDisplayDisconnect) {
  16788. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16789. }
  16790. if (this._onVrDisplayPresentChange) {
  16791. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16792. }
  16793. this._onVrDisplayConnect = null;
  16794. this._onVrDisplayDisconnect = null;
  16795. }
  16796. }
  16797. // Remove from Instances
  16798. var index = Engine.Instances.indexOf(this);
  16799. if (index >= 0) {
  16800. Engine.Instances.splice(index, 1);
  16801. }
  16802. this._workingCanvas = null;
  16803. this._workingContext = null;
  16804. this._currentBufferPointers = [];
  16805. this._renderingCanvas = null;
  16806. this._currentProgram = null;
  16807. this._bindedRenderFunction = null;
  16808. this.onResizeObservable.clear();
  16809. this.onCanvasBlurObservable.clear();
  16810. this.onCanvasFocusObservable.clear();
  16811. this.onCanvasPointerOutObservable.clear();
  16812. this.onBeginFrameObservable.clear();
  16813. this.onEndFrameObservable.clear();
  16814. BABYLON.Effect.ResetCache();
  16815. // Abort active requests
  16816. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16817. var request = _a[_i];
  16818. request.abort();
  16819. }
  16820. };
  16821. // Loading screen
  16822. /**
  16823. * Display the loading screen
  16824. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16825. */
  16826. Engine.prototype.displayLoadingUI = function () {
  16827. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16828. return;
  16829. }
  16830. var loadingScreen = this.loadingScreen;
  16831. if (loadingScreen) {
  16832. loadingScreen.displayLoadingUI();
  16833. }
  16834. };
  16835. /**
  16836. * Hide the loading screen
  16837. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16838. */
  16839. Engine.prototype.hideLoadingUI = function () {
  16840. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16841. return;
  16842. }
  16843. var loadingScreen = this.loadingScreen;
  16844. if (loadingScreen) {
  16845. loadingScreen.hideLoadingUI();
  16846. }
  16847. };
  16848. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16849. /**
  16850. * Gets the current loading screen object
  16851. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16852. */
  16853. get: function () {
  16854. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16855. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16856. return this._loadingScreen;
  16857. },
  16858. /**
  16859. * Sets the current loading screen object
  16860. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16861. */
  16862. set: function (loadingScreen) {
  16863. this._loadingScreen = loadingScreen;
  16864. },
  16865. enumerable: true,
  16866. configurable: true
  16867. });
  16868. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16869. /**
  16870. * Sets the current loading screen text
  16871. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16872. */
  16873. set: function (text) {
  16874. this.loadingScreen.loadingUIText = text;
  16875. },
  16876. enumerable: true,
  16877. configurable: true
  16878. });
  16879. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16880. /**
  16881. * Sets the current loading screen background color
  16882. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16883. */
  16884. set: function (color) {
  16885. this.loadingScreen.loadingUIBackgroundColor = color;
  16886. },
  16887. enumerable: true,
  16888. configurable: true
  16889. });
  16890. /**
  16891. * Attach a new callback raised when context lost event is fired
  16892. * @param callback defines the callback to call
  16893. */
  16894. Engine.prototype.attachContextLostEvent = function (callback) {
  16895. if (this._renderingCanvas) {
  16896. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16897. }
  16898. };
  16899. /**
  16900. * Attach a new callback raised when context restored event is fired
  16901. * @param callback defines the callback to call
  16902. */
  16903. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16904. if (this._renderingCanvas) {
  16905. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16906. }
  16907. };
  16908. /**
  16909. * Gets the source code of the vertex shader associated with a specific webGL program
  16910. * @param program defines the program to use
  16911. * @returns a string containing the source code of the vertex shader associated with the program
  16912. */
  16913. Engine.prototype.getVertexShaderSource = function (program) {
  16914. var shaders = this._gl.getAttachedShaders(program);
  16915. if (!shaders) {
  16916. return null;
  16917. }
  16918. return this._gl.getShaderSource(shaders[0]);
  16919. };
  16920. /**
  16921. * Gets the source code of the fragment shader associated with a specific webGL program
  16922. * @param program defines the program to use
  16923. * @returns a string containing the source code of the fragment shader associated with the program
  16924. */
  16925. Engine.prototype.getFragmentShaderSource = function (program) {
  16926. var shaders = this._gl.getAttachedShaders(program);
  16927. if (!shaders) {
  16928. return null;
  16929. }
  16930. return this._gl.getShaderSource(shaders[1]);
  16931. };
  16932. /**
  16933. * Get the current error code of the webGL context
  16934. * @returns the error code
  16935. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16936. */
  16937. Engine.prototype.getError = function () {
  16938. return this._gl.getError();
  16939. };
  16940. // FPS
  16941. /**
  16942. * Gets the current framerate
  16943. * @returns a number representing the framerate
  16944. */
  16945. Engine.prototype.getFps = function () {
  16946. return this._fps;
  16947. };
  16948. /**
  16949. * Gets the time spent between current and previous frame
  16950. * @returns a number representing the delta time in ms
  16951. */
  16952. Engine.prototype.getDeltaTime = function () {
  16953. return this._deltaTime;
  16954. };
  16955. Engine.prototype._measureFps = function () {
  16956. this._performanceMonitor.sampleFrame();
  16957. this._fps = this._performanceMonitor.averageFPS;
  16958. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16959. };
  16960. /** @hidden */
  16961. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  16962. if (faceIndex === void 0) { faceIndex = -1; }
  16963. if (level === void 0) { level = 0; }
  16964. if (buffer === void 0) { buffer = null; }
  16965. var gl = this._gl;
  16966. if (!this._dummyFramebuffer) {
  16967. var dummy = gl.createFramebuffer();
  16968. if (!dummy) {
  16969. throw new Error("Unable to create dummy framebuffer");
  16970. }
  16971. this._dummyFramebuffer = dummy;
  16972. }
  16973. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16974. if (faceIndex > -1) {
  16975. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16976. }
  16977. else {
  16978. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16979. }
  16980. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16981. switch (readType) {
  16982. case gl.UNSIGNED_BYTE:
  16983. if (!buffer) {
  16984. buffer = new Uint8Array(4 * width * height);
  16985. }
  16986. readType = gl.UNSIGNED_BYTE;
  16987. break;
  16988. default:
  16989. if (!buffer) {
  16990. buffer = new Float32Array(4 * width * height);
  16991. }
  16992. readType = gl.FLOAT;
  16993. break;
  16994. }
  16995. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16996. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16997. return buffer;
  16998. };
  16999. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17000. if (this._webGLVersion > 1) {
  17001. return this._caps.colorBufferFloat;
  17002. }
  17003. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17004. };
  17005. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17006. if (this._webGLVersion > 1) {
  17007. return this._caps.colorBufferFloat;
  17008. }
  17009. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17010. };
  17011. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17012. Engine.prototype._canRenderToFramebuffer = function (type) {
  17013. var gl = this._gl;
  17014. //clear existing errors
  17015. while (gl.getError() !== gl.NO_ERROR) { }
  17016. var successful = true;
  17017. var texture = gl.createTexture();
  17018. gl.bindTexture(gl.TEXTURE_2D, texture);
  17019. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17022. var fb = gl.createFramebuffer();
  17023. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17025. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17026. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17027. successful = successful && (gl.getError() === gl.NO_ERROR);
  17028. //try render by clearing frame buffer's color buffer
  17029. if (successful) {
  17030. gl.clear(gl.COLOR_BUFFER_BIT);
  17031. successful = successful && (gl.getError() === gl.NO_ERROR);
  17032. }
  17033. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17034. if (successful) {
  17035. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17036. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17037. var readFormat = gl.RGBA;
  17038. var readType = gl.UNSIGNED_BYTE;
  17039. var buffer = new Uint8Array(4);
  17040. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17041. successful = successful && (gl.getError() === gl.NO_ERROR);
  17042. }
  17043. //clean up
  17044. gl.deleteTexture(texture);
  17045. gl.deleteFramebuffer(fb);
  17046. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17047. //clear accumulated errors
  17048. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17049. return successful;
  17050. };
  17051. /** @hidden */
  17052. Engine.prototype._getWebGLTextureType = function (type) {
  17053. if (this._webGLVersion === 1) {
  17054. switch (type) {
  17055. case Engine.TEXTURETYPE_FLOAT:
  17056. return this._gl.FLOAT;
  17057. case Engine.TEXTURETYPE_HALF_FLOAT:
  17058. return this._gl.HALF_FLOAT_OES;
  17059. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17060. return this._gl.UNSIGNED_BYTE;
  17061. }
  17062. return this._gl.UNSIGNED_BYTE;
  17063. }
  17064. switch (type) {
  17065. case Engine.TEXTURETYPE_BYTE:
  17066. return this._gl.BYTE;
  17067. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17068. return this._gl.UNSIGNED_BYTE;
  17069. case Engine.TEXTURETYPE_SHORT:
  17070. return this._gl.SHORT;
  17071. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17072. return this._gl.UNSIGNED_SHORT;
  17073. case Engine.TEXTURETYPE_INT:
  17074. return this._gl.INT;
  17075. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17076. return this._gl.UNSIGNED_INT;
  17077. case Engine.TEXTURETYPE_FLOAT:
  17078. return this._gl.FLOAT;
  17079. case Engine.TEXTURETYPE_HALF_FLOAT:
  17080. return this._gl.HALF_FLOAT;
  17081. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17082. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17083. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17084. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17085. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17086. return this._gl.UNSIGNED_SHORT_5_6_5;
  17087. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17088. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17089. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17090. return this._gl.UNSIGNED_INT_24_8;
  17091. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17092. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17093. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17094. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17095. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17096. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17097. }
  17098. return this._gl.UNSIGNED_BYTE;
  17099. };
  17100. ;
  17101. Engine.prototype._getInternalFormat = function (format) {
  17102. var internalFormat = this._gl.RGBA;
  17103. switch (format) {
  17104. case Engine.TEXTUREFORMAT_ALPHA:
  17105. internalFormat = this._gl.ALPHA;
  17106. break;
  17107. case Engine.TEXTUREFORMAT_LUMINANCE:
  17108. internalFormat = this._gl.LUMINANCE;
  17109. break;
  17110. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17111. internalFormat = this._gl.LUMINANCE_ALPHA;
  17112. break;
  17113. case Engine.TEXTUREFORMAT_RED:
  17114. internalFormat = this._gl.RED;
  17115. break;
  17116. case Engine.TEXTUREFORMAT_RG:
  17117. internalFormat = this._gl.RG;
  17118. break;
  17119. case Engine.TEXTUREFORMAT_RGB:
  17120. internalFormat = this._gl.RGB;
  17121. break;
  17122. case Engine.TEXTUREFORMAT_RGBA:
  17123. internalFormat = this._gl.RGBA;
  17124. break;
  17125. }
  17126. if (this._webGLVersion > 1) {
  17127. switch (format) {
  17128. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17129. internalFormat = this._gl.RED_INTEGER;
  17130. break;
  17131. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17132. internalFormat = this._gl.RG_INTEGER;
  17133. break;
  17134. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17135. internalFormat = this._gl.RGB_INTEGER;
  17136. break;
  17137. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17138. internalFormat = this._gl.RGBA_INTEGER;
  17139. break;
  17140. }
  17141. }
  17142. return internalFormat;
  17143. };
  17144. /** @hidden */
  17145. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17146. if (this._webGLVersion === 1) {
  17147. if (format !== undefined) {
  17148. switch (format) {
  17149. case Engine.TEXTUREFORMAT_ALPHA:
  17150. return this._gl.ALPHA;
  17151. case Engine.TEXTUREFORMAT_LUMINANCE:
  17152. return this._gl.LUMINANCE;
  17153. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17154. return this._gl.LUMINANCE_ALPHA;
  17155. }
  17156. }
  17157. return this._gl.RGBA;
  17158. }
  17159. switch (type) {
  17160. case Engine.TEXTURETYPE_BYTE:
  17161. switch (format) {
  17162. case Engine.TEXTUREFORMAT_RED:
  17163. return this._gl.R8_SNORM;
  17164. case Engine.TEXTUREFORMAT_RG:
  17165. return this._gl.RG8_SNORM;
  17166. case Engine.TEXTUREFORMAT_RGB:
  17167. return this._gl.RGB8_SNORM;
  17168. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17169. return this._gl.R8I;
  17170. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17171. return this._gl.RG8I;
  17172. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17173. return this._gl.RGB8I;
  17174. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17175. return this._gl.RGBA8I;
  17176. default:
  17177. return this._gl.RGBA8_SNORM;
  17178. }
  17179. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17180. switch (format) {
  17181. case Engine.TEXTUREFORMAT_RED:
  17182. return this._gl.R8;
  17183. case Engine.TEXTUREFORMAT_RG:
  17184. return this._gl.RG8;
  17185. case Engine.TEXTUREFORMAT_RGB:
  17186. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17187. case Engine.TEXTUREFORMAT_RGBA:
  17188. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17189. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17190. return this._gl.R8UI;
  17191. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17192. return this._gl.RG8UI;
  17193. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17194. return this._gl.RGB8UI;
  17195. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17196. return this._gl.RGBA8UI;
  17197. default:
  17198. return this._gl.RGBA8;
  17199. }
  17200. case Engine.TEXTURETYPE_SHORT:
  17201. switch (format) {
  17202. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17203. return this._gl.R16I;
  17204. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17205. return this._gl.RG16I;
  17206. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17207. return this._gl.RGB16I;
  17208. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17209. return this._gl.RGBA16I;
  17210. default:
  17211. return this._gl.RGBA16I;
  17212. }
  17213. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17214. switch (format) {
  17215. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17216. return this._gl.R16UI;
  17217. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17218. return this._gl.RG16UI;
  17219. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17220. return this._gl.RGB16UI;
  17221. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17222. return this._gl.RGBA16UI;
  17223. default:
  17224. return this._gl.RGBA16UI;
  17225. }
  17226. case Engine.TEXTURETYPE_INT:
  17227. switch (format) {
  17228. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17229. return this._gl.R32I;
  17230. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17231. return this._gl.RG32I;
  17232. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17233. return this._gl.RGB32I;
  17234. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17235. return this._gl.RGBA32I;
  17236. default:
  17237. return this._gl.RGBA32I;
  17238. }
  17239. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17240. switch (format) {
  17241. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17242. return this._gl.R32UI;
  17243. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17244. return this._gl.RG32UI;
  17245. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17246. return this._gl.RGB32UI;
  17247. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17248. return this._gl.RGBA32UI;
  17249. default:
  17250. return this._gl.RGBA32UI;
  17251. }
  17252. case Engine.TEXTURETYPE_FLOAT:
  17253. switch (format) {
  17254. case Engine.TEXTUREFORMAT_RED:
  17255. return this._gl.R32F; // By default. Other possibility is R16F.
  17256. case Engine.TEXTUREFORMAT_RG:
  17257. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17258. case Engine.TEXTUREFORMAT_RGB:
  17259. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17260. case Engine.TEXTUREFORMAT_RGBA:
  17261. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17262. default:
  17263. return this._gl.RGBA32F;
  17264. }
  17265. case Engine.TEXTURETYPE_HALF_FLOAT:
  17266. switch (format) {
  17267. case Engine.TEXTUREFORMAT_RED:
  17268. return this._gl.R16F;
  17269. case Engine.TEXTUREFORMAT_RG:
  17270. return this._gl.RG16F;
  17271. case Engine.TEXTUREFORMAT_RGB:
  17272. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17273. case Engine.TEXTUREFORMAT_RGBA:
  17274. return this._gl.RGBA16F;
  17275. default:
  17276. return this._gl.RGBA16F;
  17277. }
  17278. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17279. return this._gl.RGB565;
  17280. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17281. return this._gl.R11F_G11F_B10F;
  17282. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17283. return this._gl.RGB9_E5;
  17284. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17285. return this._gl.RGBA4;
  17286. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17287. return this._gl.RGB5_A1;
  17288. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17289. switch (format) {
  17290. case Engine.TEXTUREFORMAT_RGBA:
  17291. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17292. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17293. return this._gl.RGB10_A2UI;
  17294. default:
  17295. return this._gl.RGB10_A2;
  17296. }
  17297. }
  17298. return this._gl.RGBA8;
  17299. };
  17300. ;
  17301. /** @hidden */
  17302. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17303. if (type === Engine.TEXTURETYPE_FLOAT) {
  17304. return this._gl.RGBA32F;
  17305. }
  17306. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17307. return this._gl.RGBA16F;
  17308. }
  17309. return this._gl.RGBA8;
  17310. };
  17311. ;
  17312. /** @hidden */
  17313. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17314. var _this = this;
  17315. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17316. this._activeRequests.push(request);
  17317. request.onCompleteObservable.add(function (request) {
  17318. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17319. });
  17320. return request;
  17321. };
  17322. /** @hidden */
  17323. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17324. var _this = this;
  17325. return new Promise(function (resolve, reject) {
  17326. _this._loadFile(url, function (data) {
  17327. resolve(data);
  17328. }, undefined, database, useArrayBuffer, function (request, exception) {
  17329. reject(exception);
  17330. });
  17331. });
  17332. };
  17333. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17334. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17335. var onload = function (data) {
  17336. loadedFiles[index] = data;
  17337. loadedFiles._internalCount++;
  17338. if (loadedFiles._internalCount === 6) {
  17339. onfinish(loadedFiles);
  17340. }
  17341. };
  17342. var onerror = function (request, exception) {
  17343. if (onErrorCallBack && request) {
  17344. onErrorCallBack(request.status + " " + request.statusText, exception);
  17345. }
  17346. };
  17347. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17348. };
  17349. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17350. if (onError === void 0) { onError = null; }
  17351. var loadedFiles = [];
  17352. loadedFiles._internalCount = 0;
  17353. for (var index = 0; index < 6; index++) {
  17354. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17355. }
  17356. };
  17357. // Statics
  17358. /**
  17359. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17360. * @returns true if the engine can be created
  17361. * @ignorenaming
  17362. */
  17363. Engine.isSupported = function () {
  17364. try {
  17365. var tempcanvas = document.createElement("canvas");
  17366. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17367. return gl != null && !!window.WebGLRenderingContext;
  17368. }
  17369. catch (e) {
  17370. return false;
  17371. }
  17372. };
  17373. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17374. Engine.ExceptionList = [
  17375. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17376. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17377. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17378. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17379. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17380. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17381. ];
  17382. /** Gets the list of created engines */
  17383. Engine.Instances = new Array();
  17384. /**
  17385. * Hidden
  17386. */
  17387. Engine._TextureLoaders = [];
  17388. // Const statics
  17389. /** Defines that alpha blending is disabled */
  17390. Engine.ALPHA_DISABLE = 0;
  17391. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17392. Engine.ALPHA_ADD = 1;
  17393. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17394. Engine.ALPHA_COMBINE = 2;
  17395. /** Defines that alpha blending to DEST - SRC * DEST */
  17396. Engine.ALPHA_SUBTRACT = 3;
  17397. /** Defines that alpha blending to SRC * DEST */
  17398. Engine.ALPHA_MULTIPLY = 4;
  17399. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17400. Engine.ALPHA_MAXIMIZED = 5;
  17401. /** Defines that alpha blending to SRC + DEST */
  17402. Engine.ALPHA_ONEONE = 6;
  17403. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17404. Engine.ALPHA_PREMULTIPLIED = 7;
  17405. /**
  17406. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17407. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17408. */
  17409. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17410. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17411. Engine.ALPHA_INTERPOLATE = 9;
  17412. /**
  17413. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17414. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17415. */
  17416. Engine.ALPHA_SCREENMODE = 10;
  17417. /** Defines that the ressource is not delayed*/
  17418. Engine.DELAYLOADSTATE_NONE = 0;
  17419. /** Defines that the ressource was successfully delay loaded */
  17420. Engine.DELAYLOADSTATE_LOADED = 1;
  17421. /** Defines that the ressource is currently delay loading */
  17422. Engine.DELAYLOADSTATE_LOADING = 2;
  17423. /** Defines that the ressource is delayed and has not started loading */
  17424. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17425. // Depht or Stencil test Constants.
  17426. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17427. Engine.NEVER = 0x0200;
  17428. /** 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.ALWAYS = 0x0207;
  17430. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17431. Engine.LESS = 0x0201;
  17432. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17433. Engine.EQUAL = 0x0202;
  17434. /** 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 */
  17435. Engine.LEQUAL = 0x0203;
  17436. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17437. Engine.GREATER = 0x0204;
  17438. /** 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 */
  17439. Engine.GEQUAL = 0x0206;
  17440. /** 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 */
  17441. Engine.NOTEQUAL = 0x0205;
  17442. // Stencil Actions Constants.
  17443. /** Passed to stencilOperation to specify that stencil value must be kept */
  17444. Engine.KEEP = 0x1E00;
  17445. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17446. Engine.REPLACE = 0x1E01;
  17447. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17448. Engine.INCR = 0x1E02;
  17449. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17450. Engine.DECR = 0x1E03;
  17451. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17452. Engine.INVERT = 0x150A;
  17453. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17454. Engine.INCR_WRAP = 0x8507;
  17455. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17456. Engine.DECR_WRAP = 0x8508;
  17457. /** Texture is not repeating outside of 0..1 UVs */
  17458. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17459. /** Texture is repeating outside of 0..1 UVs */
  17460. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17461. /** Texture is repeating and mirrored */
  17462. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17463. /** ALPHA */
  17464. Engine.TEXTUREFORMAT_ALPHA = 0;
  17465. /** LUMINANCE */
  17466. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17467. /** LUMINANCE_ALPHA */
  17468. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17469. /** RGB */
  17470. Engine.TEXTUREFORMAT_RGB = 4;
  17471. /** RGBA */
  17472. Engine.TEXTUREFORMAT_RGBA = 5;
  17473. /** RED */
  17474. Engine.TEXTUREFORMAT_RED = 6;
  17475. /** RED (2nd reference) */
  17476. Engine.TEXTUREFORMAT_R = 6;
  17477. /** RG */
  17478. Engine.TEXTUREFORMAT_RG = 7;
  17479. /** RED_INTEGER */
  17480. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17481. /** RED_INTEGER (2nd reference) */
  17482. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17483. /** RG_INTEGER */
  17484. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17485. /** RGB_INTEGER */
  17486. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17487. /** RGBA_INTEGER */
  17488. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17489. /** UNSIGNED_BYTE */
  17490. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17491. /** UNSIGNED_BYTE (2nd reference) */
  17492. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17493. /** FLOAT */
  17494. Engine.TEXTURETYPE_FLOAT = 1;
  17495. /** HALF_FLOAT */
  17496. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17497. /** BYTE */
  17498. Engine.TEXTURETYPE_BYTE = 3;
  17499. /** SHORT */
  17500. Engine.TEXTURETYPE_SHORT = 4;
  17501. /** UNSIGNED_SHORT */
  17502. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17503. /** INT */
  17504. Engine.TEXTURETYPE_INT = 6;
  17505. /** UNSIGNED_INT */
  17506. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17507. /** UNSIGNED_SHORT_4_4_4_4 */
  17508. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17509. /** UNSIGNED_SHORT_5_5_5_1 */
  17510. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17511. /** UNSIGNED_SHORT_5_6_5 */
  17512. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17513. /** UNSIGNED_INT_2_10_10_10_REV */
  17514. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17515. /** UNSIGNED_INT_24_8 */
  17516. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17517. /** UNSIGNED_INT_10F_11F_11F_REV */
  17518. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17519. /** UNSIGNED_INT_5_9_9_9_REV */
  17520. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17521. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17522. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17523. /** nearest is mag = nearest and min = nearest and mip = linear */
  17524. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17525. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17526. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17527. /** Trilinear is mag = linear and min = linear and mip = linear */
  17528. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17529. /** nearest is mag = nearest and min = nearest and mip = linear */
  17530. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17531. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17532. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17533. /** Trilinear is mag = linear and min = linear and mip = linear */
  17534. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17535. /** mag = nearest and min = nearest and mip = nearest */
  17536. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17537. /** mag = nearest and min = linear and mip = nearest */
  17538. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17539. /** mag = nearest and min = linear and mip = linear */
  17540. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17541. /** mag = nearest and min = linear and mip = none */
  17542. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17543. /** mag = nearest and min = nearest and mip = none */
  17544. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17545. /** mag = linear and min = nearest and mip = nearest */
  17546. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17547. /** mag = linear and min = nearest and mip = linear */
  17548. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17549. /** mag = linear and min = linear and mip = none */
  17550. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17551. /** mag = linear and min = nearest and mip = none */
  17552. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17553. /** Explicit coordinates mode */
  17554. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17555. /** Spherical coordinates mode */
  17556. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17557. /** Planar coordinates mode */
  17558. Engine.TEXTURE_PLANAR_MODE = 2;
  17559. /** Cubic coordinates mode */
  17560. Engine.TEXTURE_CUBIC_MODE = 3;
  17561. /** Projection coordinates mode */
  17562. Engine.TEXTURE_PROJECTION_MODE = 4;
  17563. /** Skybox coordinates mode */
  17564. Engine.TEXTURE_SKYBOX_MODE = 5;
  17565. /** Inverse Cubic coordinates mode */
  17566. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17567. /** Equirectangular coordinates mode */
  17568. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17569. /** Equirectangular Fixed coordinates mode */
  17570. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17571. /** Equirectangular Fixed Mirrored coordinates mode */
  17572. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17573. // Texture rescaling mode
  17574. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17575. Engine.SCALEMODE_FLOOR = 1;
  17576. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17577. Engine.SCALEMODE_NEAREST = 2;
  17578. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17579. Engine.SCALEMODE_CEILING = 3;
  17580. // Updatable statics so stick with vars here
  17581. /**
  17582. * Gets or sets the epsilon value used by collision engine
  17583. */
  17584. Engine.CollisionsEpsilon = 0.001;
  17585. /**
  17586. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17587. */
  17588. Engine.CodeRepository = "src/";
  17589. /**
  17590. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17591. */
  17592. Engine.ShadersRepository = "src/Shaders/";
  17593. return Engine;
  17594. }());
  17595. BABYLON.Engine = Engine;
  17596. })(BABYLON || (BABYLON = {}));
  17597. //# sourceMappingURL=babylon.engine.js.map
  17598. var BABYLON;
  17599. (function (BABYLON) {
  17600. /**
  17601. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17602. */
  17603. var Node = /** @class */ (function () {
  17604. /**
  17605. * Creates a new Node
  17606. * @param {string} name - the name and id to be given to this node
  17607. * @param {BABYLON.Scene} the scene this node will be added to
  17608. */
  17609. function Node(name, scene) {
  17610. if (scene === void 0) { scene = null; }
  17611. /**
  17612. * Gets or sets a string used to store user defined state for the node
  17613. */
  17614. this.state = "";
  17615. /**
  17616. * Gets or sets an object used to store user defined information for the node
  17617. */
  17618. this.metadata = null;
  17619. /**
  17620. * Gets or sets a boolean used to define if the node must be serialized
  17621. */
  17622. this.doNotSerialize = false;
  17623. /** @hidden */
  17624. this._isDisposed = false;
  17625. /**
  17626. * Gets a list of Animations associated with the node
  17627. */
  17628. this.animations = new Array();
  17629. this._ranges = {};
  17630. this._isEnabled = true;
  17631. this._isReady = true;
  17632. /** @hidden */
  17633. this._currentRenderId = -1;
  17634. this._parentRenderId = -1;
  17635. this._childRenderId = -1;
  17636. /** @hidden */
  17637. this._worldMatrix = BABYLON.Matrix.Zero();
  17638. /** @hidden */
  17639. this._worldMatrixDeterminant = 0;
  17640. this._animationPropertiesOverride = null;
  17641. /**
  17642. * An event triggered when the mesh is disposed
  17643. */
  17644. this.onDisposeObservable = new BABYLON.Observable();
  17645. // Behaviors
  17646. this._behaviors = new Array();
  17647. this.name = name;
  17648. this.id = name;
  17649. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17650. this.uniqueId = this._scene.getUniqueId();
  17651. this._initCache();
  17652. this._scene.rootNodes.push(this);
  17653. }
  17654. /**
  17655. * Add a new node constructor
  17656. * @param type defines the type name of the node to construct
  17657. * @param constructorFunc defines the constructor function
  17658. */
  17659. Node.AddNodeConstructor = function (type, constructorFunc) {
  17660. this._NodeConstructors[type] = constructorFunc;
  17661. };
  17662. /**
  17663. * Returns a node constructor based on type name
  17664. * @param type defines the type name
  17665. * @param name defines the new node name
  17666. * @param scene defines the hosting scene
  17667. * @param options defines optional options to transmit to constructors
  17668. * @returns the new constructor or null
  17669. */
  17670. Node.Construct = function (type, name, scene, options) {
  17671. var constructorFunc = this._NodeConstructors[type];
  17672. if (!constructorFunc) {
  17673. return null;
  17674. }
  17675. return constructorFunc(name, scene, options);
  17676. };
  17677. /**
  17678. * Gets a boolean indicating if the node has been disposed
  17679. * @returns true if the node was disposed
  17680. */
  17681. Node.prototype.isDisposed = function () {
  17682. return this._isDisposed;
  17683. };
  17684. Object.defineProperty(Node.prototype, "parent", {
  17685. get: function () {
  17686. return this._parentNode;
  17687. },
  17688. /**
  17689. * Gets or sets the parent of the node
  17690. */
  17691. set: function (parent) {
  17692. if (this._parentNode === parent) {
  17693. return;
  17694. }
  17695. var previousParentNode = this._parentNode;
  17696. // Remove self from list of children of parent
  17697. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17698. var index = this._parentNode._children.indexOf(this);
  17699. if (index !== -1) {
  17700. this._parentNode._children.splice(index, 1);
  17701. }
  17702. if (!parent) {
  17703. // Need to add this node to the rootNodes
  17704. this._scene.rootNodes.push(this);
  17705. }
  17706. }
  17707. // Store new parent
  17708. this._parentNode = parent;
  17709. // Add as child to new parent
  17710. if (this._parentNode) {
  17711. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17712. this._parentNode._children = new Array();
  17713. }
  17714. this._parentNode._children.push(this);
  17715. if (!previousParentNode) {
  17716. // Need to remove from rootNodes
  17717. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17718. if (rootNodeIndex > -1) {
  17719. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17720. }
  17721. }
  17722. }
  17723. },
  17724. enumerable: true,
  17725. configurable: true
  17726. });
  17727. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17728. /**
  17729. * Gets or sets the animation properties override
  17730. */
  17731. get: function () {
  17732. if (!this._animationPropertiesOverride) {
  17733. return this._scene.animationPropertiesOverride;
  17734. }
  17735. return this._animationPropertiesOverride;
  17736. },
  17737. set: function (value) {
  17738. this._animationPropertiesOverride = value;
  17739. },
  17740. enumerable: true,
  17741. configurable: true
  17742. });
  17743. /**
  17744. * Gets a string idenfifying the name of the class
  17745. * @returns "Node" string
  17746. */
  17747. Node.prototype.getClassName = function () {
  17748. return "Node";
  17749. };
  17750. Object.defineProperty(Node.prototype, "onDispose", {
  17751. /**
  17752. * Sets a callback that will be raised when the node will be disposed
  17753. */
  17754. set: function (callback) {
  17755. if (this._onDisposeObserver) {
  17756. this.onDisposeObservable.remove(this._onDisposeObserver);
  17757. }
  17758. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17759. },
  17760. enumerable: true,
  17761. configurable: true
  17762. });
  17763. /**
  17764. * Gets the scene of the node
  17765. * @returns a {BABYLON.Scene}
  17766. */
  17767. Node.prototype.getScene = function () {
  17768. return this._scene;
  17769. };
  17770. /**
  17771. * Gets the engine of the node
  17772. * @returns a {BABYLON.Engine}
  17773. */
  17774. Node.prototype.getEngine = function () {
  17775. return this._scene.getEngine();
  17776. };
  17777. /**
  17778. * Attach a behavior to the node
  17779. * @see http://doc.babylonjs.com/features/behaviour
  17780. * @param behavior defines the behavior to attach
  17781. * @returns the current Node
  17782. */
  17783. Node.prototype.addBehavior = function (behavior) {
  17784. var _this = this;
  17785. var index = this._behaviors.indexOf(behavior);
  17786. if (index !== -1) {
  17787. return this;
  17788. }
  17789. behavior.init();
  17790. if (this._scene.isLoading) {
  17791. // We defer the attach when the scene will be loaded
  17792. this._scene.onDataLoadedObservable.addOnce(function () {
  17793. behavior.attach(_this);
  17794. });
  17795. }
  17796. else {
  17797. behavior.attach(this);
  17798. }
  17799. this._behaviors.push(behavior);
  17800. return this;
  17801. };
  17802. /**
  17803. * Remove an attached behavior
  17804. * @see http://doc.babylonjs.com/features/behaviour
  17805. * @param behavior defines the behavior to attach
  17806. * @returns the current Node
  17807. */
  17808. Node.prototype.removeBehavior = function (behavior) {
  17809. var index = this._behaviors.indexOf(behavior);
  17810. if (index === -1) {
  17811. return this;
  17812. }
  17813. this._behaviors[index].detach();
  17814. this._behaviors.splice(index, 1);
  17815. return this;
  17816. };
  17817. Object.defineProperty(Node.prototype, "behaviors", {
  17818. /**
  17819. * Gets the list of attached behaviors
  17820. * @see http://doc.babylonjs.com/features/behaviour
  17821. */
  17822. get: function () {
  17823. return this._behaviors;
  17824. },
  17825. enumerable: true,
  17826. configurable: true
  17827. });
  17828. /**
  17829. * Gets an attached behavior by name
  17830. * @param name defines the name of the behavior to look for
  17831. * @see http://doc.babylonjs.com/features/behaviour
  17832. * @returns null if behavior was not found else the requested behavior
  17833. */
  17834. Node.prototype.getBehaviorByName = function (name) {
  17835. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17836. var behavior = _a[_i];
  17837. if (behavior.name === name) {
  17838. return behavior;
  17839. }
  17840. }
  17841. return null;
  17842. };
  17843. /**
  17844. * Returns the latest update of the World matrix
  17845. * @returns a Matrix
  17846. */
  17847. Node.prototype.getWorldMatrix = function () {
  17848. if (this._currentRenderId !== this._scene.getRenderId()) {
  17849. this.computeWorldMatrix();
  17850. }
  17851. return this._worldMatrix;
  17852. };
  17853. /** @hidden */
  17854. Node.prototype._getWorldMatrixDeterminant = function () {
  17855. return this._worldMatrixDeterminant;
  17856. };
  17857. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17858. /**
  17859. * Returns directly the latest state of the mesh World matrix.
  17860. * A Matrix is returned.
  17861. */
  17862. get: function () {
  17863. return this._worldMatrix;
  17864. },
  17865. enumerable: true,
  17866. configurable: true
  17867. });
  17868. // override it in derived class if you add new variables to the cache
  17869. // and call the parent class method
  17870. /** @hidden */
  17871. Node.prototype._initCache = function () {
  17872. this._cache = {};
  17873. this._cache.parent = undefined;
  17874. };
  17875. /** @hidden */
  17876. Node.prototype.updateCache = function (force) {
  17877. if (!force && this.isSynchronized())
  17878. return;
  17879. this._cache.parent = this.parent;
  17880. this._updateCache();
  17881. };
  17882. // override it in derived class if you add new variables to the cache
  17883. // and call the parent class method if !ignoreParentClass
  17884. /** @hidden */
  17885. Node.prototype._updateCache = function (ignoreParentClass) {
  17886. };
  17887. // override it in derived class if you add new variables to the cache
  17888. /** @hidden */
  17889. Node.prototype._isSynchronized = function () {
  17890. return true;
  17891. };
  17892. /** @hidden */
  17893. Node.prototype._markSyncedWithParent = function () {
  17894. if (this._parentNode) {
  17895. this._parentRenderId = this._parentNode._childRenderId;
  17896. }
  17897. };
  17898. /** @hidden */
  17899. Node.prototype.isSynchronizedWithParent = function () {
  17900. if (!this._parentNode) {
  17901. return true;
  17902. }
  17903. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17904. return false;
  17905. }
  17906. return this._parentNode.isSynchronized();
  17907. };
  17908. /** @hidden */
  17909. Node.prototype.isSynchronized = function () {
  17910. if (this._cache.parent != this._parentNode) {
  17911. this._cache.parent = this._parentNode;
  17912. return false;
  17913. }
  17914. if (this._parentNode && !this.isSynchronizedWithParent()) {
  17915. return false;
  17916. }
  17917. return this._isSynchronized();
  17918. };
  17919. /**
  17920. * Is this node ready to be used/rendered
  17921. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17922. * @return true if the node is ready
  17923. */
  17924. Node.prototype.isReady = function (completeCheck) {
  17925. if (completeCheck === void 0) { completeCheck = false; }
  17926. return this._isReady;
  17927. };
  17928. /**
  17929. * Is this node enabled?
  17930. * 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
  17931. * @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
  17932. * @return whether this node (and its parent) is enabled
  17933. */
  17934. Node.prototype.isEnabled = function (checkAncestors) {
  17935. if (checkAncestors === void 0) { checkAncestors = true; }
  17936. if (checkAncestors === false) {
  17937. return this._isEnabled;
  17938. }
  17939. if (this._isEnabled === false) {
  17940. return false;
  17941. }
  17942. if (this._parentNode !== undefined && this._parentNode !== null) {
  17943. return this._parentNode.isEnabled(checkAncestors);
  17944. }
  17945. return true;
  17946. };
  17947. /**
  17948. * Set the enabled state of this node
  17949. * @param value defines the new enabled state
  17950. */
  17951. Node.prototype.setEnabled = function (value) {
  17952. this._isEnabled = value;
  17953. };
  17954. /**
  17955. * Is this node a descendant of the given node?
  17956. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17957. * @param ancestor defines the parent node to inspect
  17958. * @returns a boolean indicating if this node is a descendant of the given node
  17959. */
  17960. Node.prototype.isDescendantOf = function (ancestor) {
  17961. if (this.parent) {
  17962. if (this.parent === ancestor) {
  17963. return true;
  17964. }
  17965. return this.parent.isDescendantOf(ancestor);
  17966. }
  17967. return false;
  17968. };
  17969. /** @hidden */
  17970. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17971. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17972. if (!this._children) {
  17973. return;
  17974. }
  17975. for (var index = 0; index < this._children.length; index++) {
  17976. var item = this._children[index];
  17977. if (!predicate || predicate(item)) {
  17978. results.push(item);
  17979. }
  17980. if (!directDescendantsOnly) {
  17981. item._getDescendants(results, false, predicate);
  17982. }
  17983. }
  17984. };
  17985. /**
  17986. * Will return all nodes that have this node as ascendant
  17987. * @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
  17988. * @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
  17989. * @return all children nodes of all types
  17990. */
  17991. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17992. var results = new Array();
  17993. this._getDescendants(results, directDescendantsOnly, predicate);
  17994. return results;
  17995. };
  17996. /**
  17997. * Get all child-meshes of this node
  17998. * @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
  17999. * @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
  18000. * @returns an array of {BABYLON.AbstractMesh}
  18001. */
  18002. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18003. var results = [];
  18004. this._getDescendants(results, directDescendantsOnly, function (node) {
  18005. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18006. });
  18007. return results;
  18008. };
  18009. /**
  18010. * Get all child-transformNodes of this node
  18011. * @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
  18012. * @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
  18013. * @returns an array of {BABYLON.TransformNode}
  18014. */
  18015. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18016. var results = [];
  18017. this._getDescendants(results, directDescendantsOnly, function (node) {
  18018. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18019. });
  18020. return results;
  18021. };
  18022. /**
  18023. * Get all direct children of this node
  18024. * @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
  18025. * @returns an array of {BABYLON.Node}
  18026. */
  18027. Node.prototype.getChildren = function (predicate) {
  18028. if (!predicate) {
  18029. return this._children;
  18030. }
  18031. return this.getDescendants(true, predicate);
  18032. };
  18033. /** @hidden */
  18034. Node.prototype._setReady = function (state) {
  18035. if (state === this._isReady) {
  18036. return;
  18037. }
  18038. if (!state) {
  18039. this._isReady = false;
  18040. return;
  18041. }
  18042. if (this.onReady) {
  18043. this.onReady(this);
  18044. }
  18045. this._isReady = true;
  18046. };
  18047. /**
  18048. * Get an animation by name
  18049. * @param name defines the name of the animation to look for
  18050. * @returns null if not found else the requested animation
  18051. */
  18052. Node.prototype.getAnimationByName = function (name) {
  18053. for (var i = 0; i < this.animations.length; i++) {
  18054. var animation = this.animations[i];
  18055. if (animation.name === name) {
  18056. return animation;
  18057. }
  18058. }
  18059. return null;
  18060. };
  18061. /**
  18062. * Creates an animation range for this node
  18063. * @param name defines the name of the range
  18064. * @param from defines the starting key
  18065. * @param to defines the end key
  18066. */
  18067. Node.prototype.createAnimationRange = function (name, from, to) {
  18068. // check name not already in use
  18069. if (!this._ranges[name]) {
  18070. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18071. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18072. if (this.animations[i]) {
  18073. this.animations[i].createRange(name, from, to);
  18074. }
  18075. }
  18076. }
  18077. };
  18078. /**
  18079. * Delete a specific animation range
  18080. * @param name defines the name of the range to delete
  18081. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18082. */
  18083. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18084. if (deleteFrames === void 0) { deleteFrames = true; }
  18085. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18086. if (this.animations[i]) {
  18087. this.animations[i].deleteRange(name, deleteFrames);
  18088. }
  18089. }
  18090. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18091. };
  18092. /**
  18093. * Get an animation range by name
  18094. * @param name defines the name of the animation range to look for
  18095. * @returns null if not found else the requested animation range
  18096. */
  18097. Node.prototype.getAnimationRange = function (name) {
  18098. return this._ranges[name];
  18099. };
  18100. /**
  18101. * Will start the animation sequence
  18102. * @param name defines the range frames for animation sequence
  18103. * @param loop defines if the animation should loop (false by default)
  18104. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18105. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18106. * @returns the object created for this animation. If range does not exist, it will return null
  18107. */
  18108. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18109. var range = this.getAnimationRange(name);
  18110. if (!range) {
  18111. return null;
  18112. }
  18113. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18114. };
  18115. /**
  18116. * Serialize animation ranges into a JSON compatible object
  18117. * @returns serialization object
  18118. */
  18119. Node.prototype.serializeAnimationRanges = function () {
  18120. var serializationRanges = [];
  18121. for (var name in this._ranges) {
  18122. var localRange = this._ranges[name];
  18123. if (!localRange) {
  18124. continue;
  18125. }
  18126. var range = {};
  18127. range.name = name;
  18128. range.from = localRange.from;
  18129. range.to = localRange.to;
  18130. serializationRanges.push(range);
  18131. }
  18132. return serializationRanges;
  18133. };
  18134. /**
  18135. * Computes the world matrix of the node
  18136. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18137. * @returns the world matrix
  18138. */
  18139. Node.prototype.computeWorldMatrix = function (force) {
  18140. if (!this._worldMatrix) {
  18141. this._worldMatrix = BABYLON.Matrix.Identity();
  18142. }
  18143. return this._worldMatrix;
  18144. };
  18145. /**
  18146. * Releases resources associated with this node.
  18147. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18148. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18149. */
  18150. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18151. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18152. if (!doNotRecurse) {
  18153. var nodes = this.getDescendants(true);
  18154. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18155. var node = nodes_1[_i];
  18156. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18157. }
  18158. }
  18159. else {
  18160. var transformNodes = this.getChildTransformNodes(true);
  18161. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18162. var transformNode = transformNodes_1[_a];
  18163. transformNode.parent = null;
  18164. transformNode.computeWorldMatrix(true);
  18165. }
  18166. }
  18167. if (!this.parent) {
  18168. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18169. if (rootNodeIndex > -1) {
  18170. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18171. }
  18172. }
  18173. else {
  18174. this.parent = null;
  18175. }
  18176. // Callback
  18177. this.onDisposeObservable.notifyObservers(this);
  18178. this.onDisposeObservable.clear();
  18179. // Behaviors
  18180. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18181. var behavior = _c[_b];
  18182. behavior.detach();
  18183. }
  18184. this._behaviors = [];
  18185. this._isDisposed = true;
  18186. };
  18187. /**
  18188. * Parse animation range data from a serialization object and store them into a given node
  18189. * @param node defines where to store the animation ranges
  18190. * @param parsedNode defines the serialization object to read data from
  18191. * @param scene defines the hosting scene
  18192. */
  18193. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18194. if (parsedNode.ranges) {
  18195. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18196. var data = parsedNode.ranges[index];
  18197. node.createAnimationRange(data.name, data.from, data.to);
  18198. }
  18199. }
  18200. };
  18201. Node._NodeConstructors = {};
  18202. __decorate([
  18203. BABYLON.serialize()
  18204. ], Node.prototype, "name", void 0);
  18205. __decorate([
  18206. BABYLON.serialize()
  18207. ], Node.prototype, "id", void 0);
  18208. __decorate([
  18209. BABYLON.serialize()
  18210. ], Node.prototype, "uniqueId", void 0);
  18211. __decorate([
  18212. BABYLON.serialize()
  18213. ], Node.prototype, "state", void 0);
  18214. __decorate([
  18215. BABYLON.serialize()
  18216. ], Node.prototype, "metadata", void 0);
  18217. return Node;
  18218. }());
  18219. BABYLON.Node = Node;
  18220. })(BABYLON || (BABYLON = {}));
  18221. //# sourceMappingURL=babylon.node.js.map
  18222. var BABYLON;
  18223. (function (BABYLON) {
  18224. // This matrix is used as a value to reset the bounding box.
  18225. var _identityMatrix = BABYLON.Matrix.Identity();
  18226. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18227. var BoundingSphere = /** @class */ (function () {
  18228. /**
  18229. * Creates a new bounding sphere
  18230. * @param min defines the minimum vector (in local space)
  18231. * @param max defines the maximum vector (in local space)
  18232. */
  18233. function BoundingSphere(min, max) {
  18234. this.center = BABYLON.Vector3.Zero();
  18235. this.centerWorld = BABYLON.Vector3.Zero();
  18236. this.reConstruct(min, max);
  18237. }
  18238. /**
  18239. * Recreates the entire bounding sphere from scratch
  18240. * @param min defines the new minimum vector (in local space)
  18241. * @param max defines the new maximum vector (in local space)
  18242. */
  18243. BoundingSphere.prototype.reConstruct = function (min, max) {
  18244. this.minimum = min.clone();
  18245. this.maximum = max.clone();
  18246. var distance = BABYLON.Vector3.Distance(min, max);
  18247. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18248. this.radius = distance * 0.5;
  18249. this.centerWorld.set(0, 0, 0);
  18250. this._update(_identityMatrix);
  18251. };
  18252. /**
  18253. * Scale the current bounding sphere by applying a scale factor
  18254. * @param factor defines the scale factor to apply
  18255. * @returns the current bounding box
  18256. */
  18257. BoundingSphere.prototype.scale = function (factor) {
  18258. var newRadius = this.radius * factor;
  18259. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18260. var min = this.center.subtract(_tempRadiusVector);
  18261. var max = this.center.add(_tempRadiusVector);
  18262. this.reConstruct(min, max);
  18263. return this;
  18264. };
  18265. // Methods
  18266. /** @hidden */
  18267. BoundingSphere.prototype._update = function (world) {
  18268. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18269. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18270. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18271. };
  18272. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18273. for (var i = 0; i < 6; i++) {
  18274. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18275. return false;
  18276. }
  18277. return true;
  18278. };
  18279. BoundingSphere.prototype.intersectsPoint = function (point) {
  18280. var x = this.centerWorld.x - point.x;
  18281. var y = this.centerWorld.y - point.y;
  18282. var z = this.centerWorld.z - point.z;
  18283. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18284. if (this.radiusWorld < distance)
  18285. return false;
  18286. return true;
  18287. };
  18288. // Statics
  18289. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18290. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18291. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18292. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18293. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18294. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18295. return false;
  18296. return true;
  18297. };
  18298. return BoundingSphere;
  18299. }());
  18300. BABYLON.BoundingSphere = BoundingSphere;
  18301. })(BABYLON || (BABYLON = {}));
  18302. //# sourceMappingURL=babylon.boundingSphere.js.map
  18303. var BABYLON;
  18304. (function (BABYLON) {
  18305. var BoundingBox = /** @class */ (function () {
  18306. /**
  18307. * Creates a new bounding box
  18308. * @param min defines the minimum vector (in local space)
  18309. * @param max defines the maximum vector (in local space)
  18310. */
  18311. function BoundingBox(min, max) {
  18312. this.vectorsWorld = new Array();
  18313. this.reConstruct(min, max);
  18314. }
  18315. // Methods
  18316. /**
  18317. * Recreates the entire bounding box from scratch
  18318. * @param min defines the new minimum vector (in local space)
  18319. * @param max defines the new maximum vector (in local space)
  18320. */
  18321. BoundingBox.prototype.reConstruct = function (min, max) {
  18322. this.minimum = min.clone();
  18323. this.maximum = max.clone();
  18324. // Bounding vectors
  18325. this.vectors = [
  18326. this.minimum.clone(),
  18327. this.maximum.clone(),
  18328. this.minimum.clone(),
  18329. this.minimum.clone(),
  18330. this.minimum.clone(),
  18331. this.maximum.clone(),
  18332. this.maximum.clone(),
  18333. this.maximum.clone()
  18334. ];
  18335. this.vectors[2].x = this.maximum.x;
  18336. this.vectors[3].y = this.maximum.y;
  18337. this.vectors[4].z = this.maximum.z;
  18338. this.vectors[5].z = this.minimum.z;
  18339. this.vectors[6].x = this.minimum.x;
  18340. this.vectors[7].y = this.minimum.y;
  18341. // OBB
  18342. this.center = this.maximum.add(this.minimum).scale(0.5);
  18343. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18344. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18345. // World
  18346. for (var index = 0; index < this.vectors.length; index++) {
  18347. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18348. }
  18349. this.minimumWorld = BABYLON.Vector3.Zero();
  18350. this.maximumWorld = BABYLON.Vector3.Zero();
  18351. this.centerWorld = BABYLON.Vector3.Zero();
  18352. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18353. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18354. };
  18355. /**
  18356. * Scale the current bounding box by applying a scale factor
  18357. * @param factor defines the scale factor to apply
  18358. * @returns the current bounding box
  18359. */
  18360. BoundingBox.prototype.scale = function (factor) {
  18361. var diff = this.maximum.subtract(this.minimum);
  18362. var distance = diff.length() * factor;
  18363. diff.normalize();
  18364. var newRadius = diff.scale(distance / 2);
  18365. var min = this.center.subtract(newRadius);
  18366. var max = this.center.add(newRadius);
  18367. this.reConstruct(min, max);
  18368. return this;
  18369. };
  18370. BoundingBox.prototype.getWorldMatrix = function () {
  18371. return this._worldMatrix;
  18372. };
  18373. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18374. this._worldMatrix.copyFrom(matrix);
  18375. return this;
  18376. };
  18377. /** @hidden */
  18378. BoundingBox.prototype._update = function (world) {
  18379. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18380. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18381. for (var index = 0; index < this.vectors.length; index++) {
  18382. var v = this.vectorsWorld[index];
  18383. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18384. if (v.x < this.minimumWorld.x)
  18385. this.minimumWorld.x = v.x;
  18386. if (v.y < this.minimumWorld.y)
  18387. this.minimumWorld.y = v.y;
  18388. if (v.z < this.minimumWorld.z)
  18389. this.minimumWorld.z = v.z;
  18390. if (v.x > this.maximumWorld.x)
  18391. this.maximumWorld.x = v.x;
  18392. if (v.y > this.maximumWorld.y)
  18393. this.maximumWorld.y = v.y;
  18394. if (v.z > this.maximumWorld.z)
  18395. this.maximumWorld.z = v.z;
  18396. }
  18397. // Extend
  18398. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18399. this.extendSizeWorld.scaleInPlace(0.5);
  18400. // OBB
  18401. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18402. this.centerWorld.scaleInPlace(0.5);
  18403. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18404. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18405. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18406. this._worldMatrix = world;
  18407. };
  18408. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18409. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18410. };
  18411. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18412. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18413. };
  18414. BoundingBox.prototype.intersectsPoint = function (point) {
  18415. var delta = -BABYLON.Epsilon;
  18416. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18417. return false;
  18418. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18419. return false;
  18420. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18421. return false;
  18422. return true;
  18423. };
  18424. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18425. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18426. };
  18427. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18428. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18429. return false;
  18430. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18431. return false;
  18432. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18433. return false;
  18434. return true;
  18435. };
  18436. // Statics
  18437. BoundingBox.Intersects = function (box0, box1) {
  18438. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18439. return false;
  18440. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18441. return false;
  18442. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18443. return false;
  18444. return true;
  18445. };
  18446. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18447. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18448. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18449. return (num <= (sphereRadius * sphereRadius));
  18450. };
  18451. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18452. for (var p = 0; p < 6; p++) {
  18453. for (var i = 0; i < 8; i++) {
  18454. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18455. return false;
  18456. }
  18457. }
  18458. }
  18459. return true;
  18460. };
  18461. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18462. for (var p = 0; p < 6; p++) {
  18463. var inCount = 8;
  18464. for (var i = 0; i < 8; i++) {
  18465. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18466. --inCount;
  18467. }
  18468. else {
  18469. break;
  18470. }
  18471. }
  18472. if (inCount === 0)
  18473. return false;
  18474. }
  18475. return true;
  18476. };
  18477. return BoundingBox;
  18478. }());
  18479. BABYLON.BoundingBox = BoundingBox;
  18480. })(BABYLON || (BABYLON = {}));
  18481. //# sourceMappingURL=babylon.boundingBox.js.map
  18482. var BABYLON;
  18483. (function (BABYLON) {
  18484. var computeBoxExtents = function (axis, box) {
  18485. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18486. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18487. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18488. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18489. var r = r0 + r1 + r2;
  18490. return {
  18491. min: p - r,
  18492. max: p + r
  18493. };
  18494. };
  18495. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18496. var axisOverlap = function (axis, box0, box1) {
  18497. var result0 = computeBoxExtents(axis, box0);
  18498. var result1 = computeBoxExtents(axis, box1);
  18499. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18500. };
  18501. var BoundingInfo = /** @class */ (function () {
  18502. function BoundingInfo(minimum, maximum) {
  18503. this.minimum = minimum;
  18504. this.maximum = maximum;
  18505. this._isLocked = false;
  18506. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18507. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18508. }
  18509. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18510. get: function () {
  18511. return this._isLocked;
  18512. },
  18513. set: function (value) {
  18514. this._isLocked = value;
  18515. },
  18516. enumerable: true,
  18517. configurable: true
  18518. });
  18519. // Methods
  18520. BoundingInfo.prototype.update = function (world) {
  18521. if (this._isLocked) {
  18522. return;
  18523. }
  18524. this.boundingBox._update(world);
  18525. this.boundingSphere._update(world);
  18526. };
  18527. /**
  18528. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18529. * @param center New center of the bounding info
  18530. * @param extend New extend of the bounding info
  18531. */
  18532. BoundingInfo.prototype.centerOn = function (center, extend) {
  18533. this.minimum = center.subtract(extend);
  18534. this.maximum = center.add(extend);
  18535. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18536. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18537. return this;
  18538. };
  18539. /**
  18540. * Scale the current bounding info by applying a scale factor
  18541. * @param factor defines the scale factor to apply
  18542. * @returns the current bounding info
  18543. */
  18544. BoundingInfo.prototype.scale = function (factor) {
  18545. this.boundingBox.scale(factor);
  18546. this.boundingSphere.scale(factor);
  18547. return this;
  18548. };
  18549. /**
  18550. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18551. * @param frustumPlanes defines the frustum to test
  18552. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18553. * @returns true if the bounding info is in the frustum planes
  18554. */
  18555. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18556. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18557. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18558. return false;
  18559. }
  18560. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18561. return true;
  18562. }
  18563. return this.boundingBox.isInFrustum(frustumPlanes);
  18564. };
  18565. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18566. /**
  18567. * Gets the world distance between the min and max points of the bounding box
  18568. */
  18569. get: function () {
  18570. var boundingBox = this.boundingBox;
  18571. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18572. return size.length();
  18573. },
  18574. enumerable: true,
  18575. configurable: true
  18576. });
  18577. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18578. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18579. };
  18580. /** @hidden */
  18581. BoundingInfo.prototype._checkCollision = function (collider) {
  18582. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18583. };
  18584. BoundingInfo.prototype.intersectsPoint = function (point) {
  18585. if (!this.boundingSphere.centerWorld) {
  18586. return false;
  18587. }
  18588. if (!this.boundingSphere.intersectsPoint(point)) {
  18589. return false;
  18590. }
  18591. if (!this.boundingBox.intersectsPoint(point)) {
  18592. return false;
  18593. }
  18594. return true;
  18595. };
  18596. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18597. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18598. return false;
  18599. }
  18600. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18601. return false;
  18602. }
  18603. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18604. return false;
  18605. }
  18606. if (!precise) {
  18607. return true;
  18608. }
  18609. var box0 = this.boundingBox;
  18610. var box1 = boundingInfo.boundingBox;
  18611. if (!axisOverlap(box0.directions[0], box0, box1))
  18612. return false;
  18613. if (!axisOverlap(box0.directions[1], box0, box1))
  18614. return false;
  18615. if (!axisOverlap(box0.directions[2], box0, box1))
  18616. return false;
  18617. if (!axisOverlap(box1.directions[0], box0, box1))
  18618. return false;
  18619. if (!axisOverlap(box1.directions[1], box0, box1))
  18620. return false;
  18621. if (!axisOverlap(box1.directions[2], box0, box1))
  18622. return false;
  18623. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18624. return false;
  18625. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18626. return false;
  18627. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18628. return false;
  18629. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18630. return false;
  18631. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18632. return false;
  18633. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18634. return false;
  18635. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18636. return false;
  18637. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18638. return false;
  18639. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18640. return false;
  18641. return true;
  18642. };
  18643. return BoundingInfo;
  18644. }());
  18645. BABYLON.BoundingInfo = BoundingInfo;
  18646. })(BABYLON || (BABYLON = {}));
  18647. //# sourceMappingURL=babylon.boundingInfo.js.map
  18648. var BABYLON;
  18649. (function (BABYLON) {
  18650. var TransformNode = /** @class */ (function (_super) {
  18651. __extends(TransformNode, _super);
  18652. function TransformNode(name, scene, isPure) {
  18653. if (scene === void 0) { scene = null; }
  18654. if (isPure === void 0) { isPure = true; }
  18655. var _this = _super.call(this, name, scene) || this;
  18656. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18657. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18658. _this._up = new BABYLON.Vector3(0, 1, 0);
  18659. _this._right = new BABYLON.Vector3(1, 0, 0);
  18660. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18661. // Properties
  18662. _this._position = BABYLON.Vector3.Zero();
  18663. _this._rotation = BABYLON.Vector3.Zero();
  18664. _this._scaling = BABYLON.Vector3.One();
  18665. _this._isDirty = false;
  18666. /**
  18667. * Set the billboard mode. Default is 0.
  18668. *
  18669. * | Value | Type | Description |
  18670. * | --- | --- | --- |
  18671. * | 0 | BILLBOARDMODE_NONE | |
  18672. * | 1 | BILLBOARDMODE_X | |
  18673. * | 2 | BILLBOARDMODE_Y | |
  18674. * | 4 | BILLBOARDMODE_Z | |
  18675. * | 7 | BILLBOARDMODE_ALL | |
  18676. *
  18677. */
  18678. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18679. _this.scalingDeterminant = 1;
  18680. _this.infiniteDistance = false;
  18681. /**
  18682. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18683. * By default the system will update normals to compensate
  18684. */
  18685. _this.ignoreNonUniformScaling = false;
  18686. _this._localWorld = BABYLON.Matrix.Zero();
  18687. _this._absolutePosition = BABYLON.Vector3.Zero();
  18688. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18689. _this._postMultiplyPivotMatrix = false;
  18690. _this._isWorldMatrixFrozen = false;
  18691. /**
  18692. * An event triggered after the world matrix is updated
  18693. */
  18694. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18695. _this._nonUniformScaling = false;
  18696. if (isPure) {
  18697. _this.getScene().addTransformNode(_this);
  18698. }
  18699. return _this;
  18700. }
  18701. /**
  18702. * Gets a string identifying the name of the class
  18703. * @returns "TransformNode" string
  18704. */
  18705. TransformNode.prototype.getClassName = function () {
  18706. return "TransformNode";
  18707. };
  18708. Object.defineProperty(TransformNode.prototype, "position", {
  18709. /**
  18710. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18711. */
  18712. get: function () {
  18713. return this._position;
  18714. },
  18715. set: function (newPosition) {
  18716. this._position = newPosition;
  18717. this._isDirty = true;
  18718. },
  18719. enumerable: true,
  18720. configurable: true
  18721. });
  18722. Object.defineProperty(TransformNode.prototype, "rotation", {
  18723. /**
  18724. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18725. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18726. */
  18727. get: function () {
  18728. return this._rotation;
  18729. },
  18730. set: function (newRotation) {
  18731. this._rotation = newRotation;
  18732. this._isDirty = true;
  18733. },
  18734. enumerable: true,
  18735. configurable: true
  18736. });
  18737. Object.defineProperty(TransformNode.prototype, "scaling", {
  18738. /**
  18739. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18740. */
  18741. get: function () {
  18742. return this._scaling;
  18743. },
  18744. set: function (newScaling) {
  18745. this._scaling = newScaling;
  18746. this._isDirty = true;
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18752. /**
  18753. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18754. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18755. */
  18756. get: function () {
  18757. return this._rotationQuaternion;
  18758. },
  18759. set: function (quaternion) {
  18760. this._rotationQuaternion = quaternion;
  18761. //reset the rotation vector.
  18762. if (quaternion && this.rotation.length()) {
  18763. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18764. }
  18765. },
  18766. enumerable: true,
  18767. configurable: true
  18768. });
  18769. Object.defineProperty(TransformNode.prototype, "forward", {
  18770. /**
  18771. * The forward direction of that transform in world space.
  18772. */
  18773. get: function () {
  18774. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18775. },
  18776. enumerable: true,
  18777. configurable: true
  18778. });
  18779. Object.defineProperty(TransformNode.prototype, "up", {
  18780. /**
  18781. * The up direction of that transform in world space.
  18782. */
  18783. get: function () {
  18784. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18785. },
  18786. enumerable: true,
  18787. configurable: true
  18788. });
  18789. Object.defineProperty(TransformNode.prototype, "right", {
  18790. /**
  18791. * The right direction of that transform in world space.
  18792. */
  18793. get: function () {
  18794. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18795. },
  18796. enumerable: true,
  18797. configurable: true
  18798. });
  18799. /**
  18800. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18801. * Returns the TransformNode.
  18802. */
  18803. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18804. this._poseMatrix.copyFrom(matrix);
  18805. return this;
  18806. };
  18807. /**
  18808. * Returns the mesh Pose matrix.
  18809. * Returned object : Matrix
  18810. */
  18811. TransformNode.prototype.getPoseMatrix = function () {
  18812. return this._poseMatrix;
  18813. };
  18814. /** @hidden */
  18815. TransformNode.prototype._isSynchronized = function () {
  18816. if (this._isDirty) {
  18817. return false;
  18818. }
  18819. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18820. return false;
  18821. if (this._cache.pivotMatrixUpdated) {
  18822. return false;
  18823. }
  18824. if (this.infiniteDistance) {
  18825. return false;
  18826. }
  18827. if (!this._cache.position.equals(this._position))
  18828. return false;
  18829. if (this._rotationQuaternion) {
  18830. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18831. return false;
  18832. }
  18833. else if (!this._cache.rotation.equals(this._rotation))
  18834. return false;
  18835. if (!this._cache.scaling.equals(this._scaling))
  18836. return false;
  18837. return true;
  18838. };
  18839. /** @hidden */
  18840. TransformNode.prototype._initCache = function () {
  18841. _super.prototype._initCache.call(this);
  18842. this._cache.localMatrixUpdated = false;
  18843. this._cache.position = BABYLON.Vector3.Zero();
  18844. this._cache.scaling = BABYLON.Vector3.Zero();
  18845. this._cache.rotation = BABYLON.Vector3.Zero();
  18846. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18847. this._cache.billboardMode = -1;
  18848. };
  18849. TransformNode.prototype.markAsDirty = function (property) {
  18850. if (property === "rotation") {
  18851. this.rotationQuaternion = null;
  18852. }
  18853. this._currentRenderId = Number.MAX_VALUE;
  18854. this._isDirty = true;
  18855. return this;
  18856. };
  18857. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18858. /**
  18859. * Returns the current mesh absolute position.
  18860. * Returns a Vector3.
  18861. */
  18862. get: function () {
  18863. return this._absolutePosition;
  18864. },
  18865. enumerable: true,
  18866. configurable: true
  18867. });
  18868. /**
  18869. * Sets a new matrix to apply before all other transformation
  18870. * @param matrix defines the transform matrix
  18871. * @returns the current TransformNode
  18872. */
  18873. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18874. return this.setPivotMatrix(matrix, false);
  18875. };
  18876. /**
  18877. * Sets a new pivot matrix to the current node
  18878. * @param matrix defines the new pivot matrix to use
  18879. * @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
  18880. * @returns the current TransformNode
  18881. */
  18882. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18883. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18884. this._pivotMatrix = matrix.clone();
  18885. this._cache.pivotMatrixUpdated = true;
  18886. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18887. if (this._postMultiplyPivotMatrix) {
  18888. if (!this._pivotMatrixInverse) {
  18889. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18890. }
  18891. else {
  18892. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18893. }
  18894. }
  18895. return this;
  18896. };
  18897. /**
  18898. * Returns the mesh pivot matrix.
  18899. * Default : Identity.
  18900. * A Matrix is returned.
  18901. */
  18902. TransformNode.prototype.getPivotMatrix = function () {
  18903. return this._pivotMatrix;
  18904. };
  18905. /**
  18906. * Prevents the World matrix to be computed any longer.
  18907. * Returns the TransformNode.
  18908. */
  18909. TransformNode.prototype.freezeWorldMatrix = function () {
  18910. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18911. this.computeWorldMatrix(true);
  18912. this._isWorldMatrixFrozen = true;
  18913. return this;
  18914. };
  18915. /**
  18916. * Allows back the World matrix computation.
  18917. * Returns the TransformNode.
  18918. */
  18919. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18920. this._isWorldMatrixFrozen = false;
  18921. this.computeWorldMatrix(true);
  18922. return this;
  18923. };
  18924. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18925. /**
  18926. * True if the World matrix has been frozen.
  18927. * Returns a boolean.
  18928. */
  18929. get: function () {
  18930. return this._isWorldMatrixFrozen;
  18931. },
  18932. enumerable: true,
  18933. configurable: true
  18934. });
  18935. /**
  18936. * Retuns the mesh absolute position in the World.
  18937. * Returns a Vector3.
  18938. */
  18939. TransformNode.prototype.getAbsolutePosition = function () {
  18940. this.computeWorldMatrix();
  18941. return this._absolutePosition;
  18942. };
  18943. /**
  18944. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18945. * Returns the TransformNode.
  18946. */
  18947. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18948. if (!absolutePosition) {
  18949. return this;
  18950. }
  18951. var absolutePositionX;
  18952. var absolutePositionY;
  18953. var absolutePositionZ;
  18954. if (absolutePosition.x === undefined) {
  18955. if (arguments.length < 3) {
  18956. return this;
  18957. }
  18958. absolutePositionX = arguments[0];
  18959. absolutePositionY = arguments[1];
  18960. absolutePositionZ = arguments[2];
  18961. }
  18962. else {
  18963. absolutePositionX = absolutePosition.x;
  18964. absolutePositionY = absolutePosition.y;
  18965. absolutePositionZ = absolutePosition.z;
  18966. }
  18967. if (this.parent) {
  18968. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18969. invertParentWorldMatrix.invert();
  18970. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18971. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18972. }
  18973. else {
  18974. this.position.x = absolutePositionX;
  18975. this.position.y = absolutePositionY;
  18976. this.position.z = absolutePositionZ;
  18977. }
  18978. return this;
  18979. };
  18980. /**
  18981. * Sets the mesh position in its local space.
  18982. * Returns the TransformNode.
  18983. */
  18984. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18985. this.computeWorldMatrix();
  18986. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18987. return this;
  18988. };
  18989. /**
  18990. * Returns the mesh position in the local space from the current World matrix values.
  18991. * Returns a new Vector3.
  18992. */
  18993. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18994. this.computeWorldMatrix();
  18995. var invLocalWorldMatrix = this._localWorld.clone();
  18996. invLocalWorldMatrix.invert();
  18997. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18998. };
  18999. /**
  19000. * Translates the mesh along the passed Vector3 in its local space.
  19001. * Returns the TransformNode.
  19002. */
  19003. TransformNode.prototype.locallyTranslate = function (vector3) {
  19004. this.computeWorldMatrix(true);
  19005. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19006. return this;
  19007. };
  19008. /**
  19009. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19010. * @param targetPoint the position (must be in same space as current mesh) to look at
  19011. * @param yawCor optional yaw (y-axis) correction in radians
  19012. * @param pitchCor optional pitch (x-axis) correction in radians
  19013. * @param rollCor optional roll (z-axis) correction in radians
  19014. * @param space the choosen space of the target
  19015. * @returns the TransformNode.
  19016. */
  19017. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19018. if (yawCor === void 0) { yawCor = 0; }
  19019. if (pitchCor === void 0) { pitchCor = 0; }
  19020. if (rollCor === void 0) { rollCor = 0; }
  19021. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19022. var dv = TransformNode._lookAtVectorCache;
  19023. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19024. targetPoint.subtractToRef(pos, dv);
  19025. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19026. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19027. var pitch = Math.atan2(dv.y, len);
  19028. if (this.rotationQuaternion) {
  19029. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19030. }
  19031. else {
  19032. this.rotation.x = pitch + pitchCor;
  19033. this.rotation.y = yaw + yawCor;
  19034. this.rotation.z = rollCor;
  19035. }
  19036. return this;
  19037. };
  19038. /**
  19039. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19040. * This Vector3 is expressed in the World space.
  19041. */
  19042. TransformNode.prototype.getDirection = function (localAxis) {
  19043. var result = BABYLON.Vector3.Zero();
  19044. this.getDirectionToRef(localAxis, result);
  19045. return result;
  19046. };
  19047. /**
  19048. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19049. * localAxis is expressed in the mesh local space.
  19050. * result is computed in the Wordl space from the mesh World matrix.
  19051. * Returns the TransformNode.
  19052. */
  19053. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19054. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19055. return this;
  19056. };
  19057. /**
  19058. * Sets a new pivot point to the current node
  19059. * @param point defines the new pivot point to use
  19060. * @param space defines if the point is in world or local space (local by default)
  19061. * @returns the current TransformNode
  19062. */
  19063. TransformNode.prototype.setPivotPoint = function (point, space) {
  19064. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19065. if (this.getScene().getRenderId() == 0) {
  19066. this.computeWorldMatrix(true);
  19067. }
  19068. var wm = this.getWorldMatrix();
  19069. if (space == BABYLON.Space.WORLD) {
  19070. var tmat = BABYLON.Tmp.Matrix[0];
  19071. wm.invertToRef(tmat);
  19072. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19073. }
  19074. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19075. };
  19076. /**
  19077. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19078. */
  19079. TransformNode.prototype.getPivotPoint = function () {
  19080. var point = BABYLON.Vector3.Zero();
  19081. this.getPivotPointToRef(point);
  19082. return point;
  19083. };
  19084. /**
  19085. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19086. * Returns the TransformNode.
  19087. */
  19088. TransformNode.prototype.getPivotPointToRef = function (result) {
  19089. result.x = -this._pivotMatrix.m[12];
  19090. result.y = -this._pivotMatrix.m[13];
  19091. result.z = -this._pivotMatrix.m[14];
  19092. return this;
  19093. };
  19094. /**
  19095. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19096. */
  19097. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19098. var point = BABYLON.Vector3.Zero();
  19099. this.getAbsolutePivotPointToRef(point);
  19100. return point;
  19101. };
  19102. /**
  19103. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19104. * Returns the TransformNode.
  19105. */
  19106. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19107. result.x = this._pivotMatrix.m[12];
  19108. result.y = this._pivotMatrix.m[13];
  19109. result.z = this._pivotMatrix.m[14];
  19110. this.getPivotPointToRef(result);
  19111. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19112. return this;
  19113. };
  19114. /**
  19115. * Defines the passed node as the parent of the current node.
  19116. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19117. * Returns the TransformNode.
  19118. */
  19119. TransformNode.prototype.setParent = function (node) {
  19120. if (!node && !this.parent) {
  19121. return this;
  19122. }
  19123. if (!node) {
  19124. var rotation = BABYLON.Tmp.Quaternion[0];
  19125. var position = BABYLON.Tmp.Vector3[0];
  19126. var scale = BABYLON.Tmp.Vector3[1];
  19127. if (this.parent && this.parent.computeWorldMatrix) {
  19128. this.parent.computeWorldMatrix(true);
  19129. }
  19130. this.computeWorldMatrix(true);
  19131. this.getWorldMatrix().decompose(scale, rotation, position);
  19132. if (this.rotationQuaternion) {
  19133. this.rotationQuaternion.copyFrom(rotation);
  19134. }
  19135. else {
  19136. rotation.toEulerAnglesToRef(this.rotation);
  19137. }
  19138. this.scaling.x = scale.x;
  19139. this.scaling.y = scale.y;
  19140. this.scaling.z = scale.z;
  19141. this.position.x = position.x;
  19142. this.position.y = position.y;
  19143. this.position.z = position.z;
  19144. }
  19145. else {
  19146. var rotation = BABYLON.Tmp.Quaternion[0];
  19147. var position = BABYLON.Tmp.Vector3[0];
  19148. var scale = BABYLON.Tmp.Vector3[1];
  19149. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19150. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19151. this.computeWorldMatrix(true);
  19152. node.computeWorldMatrix(true);
  19153. node.getWorldMatrix().invertToRef(invParentMatrix);
  19154. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19155. diffMatrix.decompose(scale, rotation, position);
  19156. if (this.rotationQuaternion) {
  19157. this.rotationQuaternion.copyFrom(rotation);
  19158. }
  19159. else {
  19160. rotation.toEulerAnglesToRef(this.rotation);
  19161. }
  19162. this.position.x = position.x;
  19163. this.position.y = position.y;
  19164. this.position.z = position.z;
  19165. this.scaling.x = scale.x;
  19166. this.scaling.y = scale.y;
  19167. this.scaling.z = scale.z;
  19168. }
  19169. this.parent = node;
  19170. return this;
  19171. };
  19172. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19173. get: function () {
  19174. return this._nonUniformScaling;
  19175. },
  19176. enumerable: true,
  19177. configurable: true
  19178. });
  19179. /** @hidden */
  19180. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19181. if (this._nonUniformScaling === value) {
  19182. return false;
  19183. }
  19184. this._nonUniformScaling = value;
  19185. return true;
  19186. };
  19187. /**
  19188. * Attach the current TransformNode to another TransformNode associated with a bone
  19189. * @param bone Bone affecting the TransformNode
  19190. * @param affectedTransformNode TransformNode associated with the bone
  19191. */
  19192. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19193. this._transformToBoneReferal = affectedTransformNode;
  19194. this.parent = bone;
  19195. if (bone.getWorldMatrix().determinant() < 0) {
  19196. this.scalingDeterminant *= -1;
  19197. }
  19198. return this;
  19199. };
  19200. TransformNode.prototype.detachFromBone = function () {
  19201. if (!this.parent) {
  19202. return this;
  19203. }
  19204. if (this.parent.getWorldMatrix().determinant() < 0) {
  19205. this.scalingDeterminant *= -1;
  19206. }
  19207. this._transformToBoneReferal = null;
  19208. this.parent = null;
  19209. return this;
  19210. };
  19211. /**
  19212. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19213. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19214. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19215. * The passed axis is also normalized.
  19216. * Returns the TransformNode.
  19217. */
  19218. TransformNode.prototype.rotate = function (axis, amount, space) {
  19219. axis.normalize();
  19220. if (!this.rotationQuaternion) {
  19221. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19222. this.rotation = BABYLON.Vector3.Zero();
  19223. }
  19224. var rotationQuaternion;
  19225. if (!space || space === BABYLON.Space.LOCAL) {
  19226. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19227. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19228. }
  19229. else {
  19230. if (this.parent) {
  19231. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19232. invertParentWorldMatrix.invert();
  19233. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19234. }
  19235. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19236. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19237. }
  19238. return this;
  19239. };
  19240. /**
  19241. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19242. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19243. * The passed axis is also normalized.
  19244. * Returns the TransformNode.
  19245. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19246. */
  19247. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19248. axis.normalize();
  19249. if (!this.rotationQuaternion) {
  19250. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19251. this.rotation.copyFromFloats(0, 0, 0);
  19252. }
  19253. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19254. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19255. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19256. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19257. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19258. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19259. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19260. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19261. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19262. return this;
  19263. };
  19264. /**
  19265. * Translates the mesh along the axis vector for the passed distance in the given space.
  19266. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19267. * Returns the TransformNode.
  19268. */
  19269. TransformNode.prototype.translate = function (axis, distance, space) {
  19270. var displacementVector = axis.scale(distance);
  19271. if (!space || space === BABYLON.Space.LOCAL) {
  19272. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19273. this.setPositionWithLocalVector(tempV3);
  19274. }
  19275. else {
  19276. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19277. }
  19278. return this;
  19279. };
  19280. /**
  19281. * Adds a rotation step to the mesh current rotation.
  19282. * x, y, z are Euler angles expressed in radians.
  19283. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19284. * This means this rotation is made in the mesh local space only.
  19285. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19286. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19287. * ```javascript
  19288. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19289. * ```
  19290. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19291. * 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.
  19292. * Returns the TransformNode.
  19293. */
  19294. TransformNode.prototype.addRotation = function (x, y, z) {
  19295. var rotationQuaternion;
  19296. if (this.rotationQuaternion) {
  19297. rotationQuaternion = this.rotationQuaternion;
  19298. }
  19299. else {
  19300. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19301. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19302. }
  19303. var accumulation = BABYLON.Tmp.Quaternion[0];
  19304. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19305. rotationQuaternion.multiplyInPlace(accumulation);
  19306. if (!this.rotationQuaternion) {
  19307. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19308. }
  19309. return this;
  19310. };
  19311. /**
  19312. * Computes the world matrix of the node
  19313. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19314. * @returns the world matrix
  19315. */
  19316. TransformNode.prototype.computeWorldMatrix = function (force) {
  19317. if (this._isWorldMatrixFrozen) {
  19318. return this._worldMatrix;
  19319. }
  19320. if (!force && this.isSynchronized()) {
  19321. this._currentRenderId = this.getScene().getRenderId();
  19322. return this._worldMatrix;
  19323. }
  19324. this._updateCache();
  19325. this._cache.position.copyFrom(this.position);
  19326. this._cache.scaling.copyFrom(this.scaling);
  19327. this._cache.pivotMatrixUpdated = false;
  19328. this._cache.billboardMode = this.billboardMode;
  19329. this._currentRenderId = this.getScene().getRenderId();
  19330. this._childRenderId = this.getScene().getRenderId();
  19331. this._isDirty = false;
  19332. // Scaling
  19333. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19334. // Rotation
  19335. //rotate, if quaternion is set and rotation was used
  19336. if (this.rotationQuaternion) {
  19337. var len = this.rotation.length();
  19338. if (len) {
  19339. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19340. this.rotation.copyFromFloats(0, 0, 0);
  19341. }
  19342. }
  19343. if (this.rotationQuaternion) {
  19344. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19345. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19346. }
  19347. else {
  19348. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19349. this._cache.rotation.copyFrom(this.rotation);
  19350. }
  19351. // Translation
  19352. var camera = this.getScene().activeCamera;
  19353. if (this.infiniteDistance && !this.parent && camera) {
  19354. var cameraWorldMatrix = camera.getWorldMatrix();
  19355. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19356. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19357. }
  19358. else {
  19359. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19360. }
  19361. // Composing transformations
  19362. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19363. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19364. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19365. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19366. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19367. // Need to decompose each rotation here
  19368. var currentPosition = BABYLON.Tmp.Vector3[3];
  19369. if (this.parent && this.parent.getWorldMatrix) {
  19370. if (this._transformToBoneReferal) {
  19371. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19372. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19373. }
  19374. else {
  19375. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19376. }
  19377. }
  19378. else {
  19379. currentPosition.copyFrom(this.position);
  19380. }
  19381. currentPosition.subtractInPlace(camera.globalPosition);
  19382. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19383. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19384. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19385. }
  19386. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19387. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19388. }
  19389. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19390. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19391. }
  19392. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19393. }
  19394. else {
  19395. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19396. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19397. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19398. }
  19399. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19400. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19401. }
  19402. // Post multiply inverse of pivotMatrix
  19403. if (this._postMultiplyPivotMatrix) {
  19404. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19405. }
  19406. // Local world
  19407. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19408. // Parent
  19409. if (this.parent && this.parent.getWorldMatrix) {
  19410. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19411. if (this._transformToBoneReferal) {
  19412. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19413. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19414. }
  19415. else {
  19416. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19417. }
  19418. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19419. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19420. this._worldMatrix.copyFrom(this._localWorld);
  19421. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19422. }
  19423. else {
  19424. if (this._transformToBoneReferal) {
  19425. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19426. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19427. }
  19428. else {
  19429. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19430. }
  19431. }
  19432. this._markSyncedWithParent();
  19433. }
  19434. else {
  19435. this._worldMatrix.copyFrom(this._localWorld);
  19436. }
  19437. // Normal matrix
  19438. if (!this.ignoreNonUniformScaling) {
  19439. if (this.scaling.isNonUniform) {
  19440. this._updateNonUniformScalingState(true);
  19441. }
  19442. else if (this.parent && this.parent._nonUniformScaling) {
  19443. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19444. }
  19445. else {
  19446. this._updateNonUniformScalingState(false);
  19447. }
  19448. }
  19449. else {
  19450. this._updateNonUniformScalingState(false);
  19451. }
  19452. this._afterComputeWorldMatrix();
  19453. // Absolute position
  19454. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19455. // Callbacks
  19456. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19457. if (!this._poseMatrix) {
  19458. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19459. }
  19460. // Cache the determinant
  19461. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19462. return this._worldMatrix;
  19463. };
  19464. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19465. };
  19466. /**
  19467. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19468. * @param func: callback function to add
  19469. *
  19470. * Returns the TransformNode.
  19471. */
  19472. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19473. this.onAfterWorldMatrixUpdateObservable.add(func);
  19474. return this;
  19475. };
  19476. /**
  19477. * Removes a registered callback function.
  19478. * Returns the TransformNode.
  19479. */
  19480. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19481. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19482. return this;
  19483. };
  19484. /**
  19485. * Clone the current transform node
  19486. * Returns the new transform node
  19487. * @param name Name of the new clone
  19488. * @param newParent New parent for the clone
  19489. * @param doNotCloneChildren Do not clone children hierarchy
  19490. */
  19491. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19492. var _this = this;
  19493. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19494. result.name = name;
  19495. result.id = name;
  19496. if (newParent) {
  19497. result.parent = newParent;
  19498. }
  19499. if (!doNotCloneChildren) {
  19500. // Children
  19501. var directDescendants = this.getDescendants(true);
  19502. for (var index = 0; index < directDescendants.length; index++) {
  19503. var child = directDescendants[index];
  19504. if (child.clone) {
  19505. child.clone(name + "." + child.name, result);
  19506. }
  19507. }
  19508. }
  19509. return result;
  19510. };
  19511. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19512. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19513. serializationObject.type = this.getClassName();
  19514. // Parent
  19515. if (this.parent) {
  19516. serializationObject.parentId = this.parent.id;
  19517. }
  19518. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19519. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19520. }
  19521. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19522. serializationObject.isEnabled = this.isEnabled();
  19523. // Parent
  19524. if (this.parent) {
  19525. serializationObject.parentId = this.parent.id;
  19526. }
  19527. return serializationObject;
  19528. };
  19529. // Statics
  19530. /**
  19531. * Returns a new TransformNode object parsed from the source provided.
  19532. * The parameter `parsedMesh` is the source.
  19533. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19534. */
  19535. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19536. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19537. if (BABYLON.Tags) {
  19538. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19539. }
  19540. if (parsedTransformNode.localMatrix) {
  19541. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19542. }
  19543. else if (parsedTransformNode.pivotMatrix) {
  19544. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19545. }
  19546. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19547. // Parent
  19548. if (parsedTransformNode.parentId) {
  19549. transformNode._waitingParentId = parsedTransformNode.parentId;
  19550. }
  19551. return transformNode;
  19552. };
  19553. /**
  19554. * Releases resources associated with this transform node.
  19555. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19556. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19557. */
  19558. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19559. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19560. // Animations
  19561. this.getScene().stopAnimation(this);
  19562. // Remove from scene
  19563. this.getScene().removeTransformNode(this);
  19564. this.onAfterWorldMatrixUpdateObservable.clear();
  19565. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19566. };
  19567. // Statics
  19568. TransformNode.BILLBOARDMODE_NONE = 0;
  19569. TransformNode.BILLBOARDMODE_X = 1;
  19570. TransformNode.BILLBOARDMODE_Y = 2;
  19571. TransformNode.BILLBOARDMODE_Z = 4;
  19572. TransformNode.BILLBOARDMODE_ALL = 7;
  19573. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19574. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19575. __decorate([
  19576. BABYLON.serializeAsVector3("position")
  19577. ], TransformNode.prototype, "_position", void 0);
  19578. __decorate([
  19579. BABYLON.serializeAsVector3("rotation")
  19580. ], TransformNode.prototype, "_rotation", void 0);
  19581. __decorate([
  19582. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19583. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19584. __decorate([
  19585. BABYLON.serializeAsVector3("scaling")
  19586. ], TransformNode.prototype, "_scaling", void 0);
  19587. __decorate([
  19588. BABYLON.serialize()
  19589. ], TransformNode.prototype, "billboardMode", void 0);
  19590. __decorate([
  19591. BABYLON.serialize()
  19592. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19593. __decorate([
  19594. BABYLON.serialize()
  19595. ], TransformNode.prototype, "infiniteDistance", void 0);
  19596. __decorate([
  19597. BABYLON.serialize()
  19598. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19599. return TransformNode;
  19600. }(BABYLON.Node));
  19601. BABYLON.TransformNode = TransformNode;
  19602. })(BABYLON || (BABYLON = {}));
  19603. //# sourceMappingURL=babylon.transformNode.js.map
  19604. var BABYLON;
  19605. (function (BABYLON) {
  19606. /**
  19607. * Class used to store all common mesh properties
  19608. */
  19609. var AbstractMesh = /** @class */ (function (_super) {
  19610. __extends(AbstractMesh, _super);
  19611. // Constructor
  19612. /**
  19613. * Creates a new AbstractMesh
  19614. * @param name defines the name of the mesh
  19615. * @param scene defines the hosting scene
  19616. */
  19617. function AbstractMesh(name, scene) {
  19618. if (scene === void 0) { scene = null; }
  19619. var _this = _super.call(this, name, scene, false) || this;
  19620. _this._facetNb = 0; // facet number
  19621. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19622. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19623. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19624. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19625. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19626. _this._subDiv = {
  19627. max: 1,
  19628. X: 1,
  19629. Y: 1,
  19630. Z: 1
  19631. };
  19632. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19633. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19634. /** Gets ot sets the culling strategy to use to find visible meshes */
  19635. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19636. // Events
  19637. /**
  19638. * An event triggered when this mesh collides with another one
  19639. */
  19640. _this.onCollideObservable = new BABYLON.Observable();
  19641. /**
  19642. * An event triggered when the collision's position changes
  19643. */
  19644. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19645. /**
  19646. * An event triggered when material is changed
  19647. */
  19648. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19649. // Properties
  19650. /**
  19651. * Gets or sets the orientation for POV movement & rotation
  19652. */
  19653. _this.definedFacingForward = true;
  19654. /**
  19655. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19656. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19657. * * 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.
  19658. * @see http://doc.babylonjs.com/features/occlusionquery
  19659. */
  19660. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19661. /**
  19662. * 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:
  19663. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19664. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19665. * * 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.
  19666. * @see http://doc.babylonjs.com/features/occlusionquery
  19667. */
  19668. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19669. /**
  19670. * 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.
  19671. * The default value is -1 which means don't break the query and wait till the result
  19672. * @see http://doc.babylonjs.com/features/occlusionquery
  19673. */
  19674. _this.occlusionRetryCount = -1;
  19675. /** @hidden */
  19676. _this._occlusionInternalRetryCounter = 0;
  19677. /** @hidden */
  19678. _this._isOccluded = false;
  19679. /** @hidden */
  19680. _this._isOcclusionQueryInProgress = false;
  19681. _this._visibility = 1.0;
  19682. /** Gets or sets the alpha index used to sort transparent meshes
  19683. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19684. */
  19685. _this.alphaIndex = Number.MAX_VALUE;
  19686. /**
  19687. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19688. */
  19689. _this.isVisible = true;
  19690. /**
  19691. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19692. */
  19693. _this.isPickable = true;
  19694. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19695. _this.showSubMeshesBoundingBox = false;
  19696. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19697. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19698. */
  19699. _this.isBlocker = false;
  19700. /**
  19701. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19702. */
  19703. _this.enablePointerMoveEvents = false;
  19704. /**
  19705. * Specifies the rendering group id for this mesh (0 by default)
  19706. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19707. */
  19708. _this.renderingGroupId = 0;
  19709. _this._receiveShadows = false;
  19710. /** Defines color to use when rendering outline */
  19711. _this.outlineColor = BABYLON.Color3.Red();
  19712. /** Define width to use when rendering outline */
  19713. _this.outlineWidth = 0.02;
  19714. /** Defines color to use when rendering overlay */
  19715. _this.overlayColor = BABYLON.Color3.Red();
  19716. /** Defines alpha to use when rendering overlay */
  19717. _this.overlayAlpha = 0.5;
  19718. _this._hasVertexAlpha = false;
  19719. _this._useVertexColors = true;
  19720. _this._computeBonesUsingShaders = true;
  19721. _this._numBoneInfluencers = 4;
  19722. _this._applyFog = true;
  19723. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19724. _this.useOctreeForRenderingSelection = true;
  19725. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19726. _this.useOctreeForPicking = true;
  19727. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19728. _this.useOctreeForCollisions = true;
  19729. _this._layerMask = 0x0FFFFFFF;
  19730. /**
  19731. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19732. */
  19733. _this.alwaysSelectAsActiveMesh = false;
  19734. /**
  19735. * Gets or sets the current action manager
  19736. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19737. */
  19738. _this.actionManager = null;
  19739. // Collisions
  19740. _this._checkCollisions = false;
  19741. _this._collisionMask = -1;
  19742. _this._collisionGroup = -1;
  19743. /**
  19744. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19745. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19746. */
  19747. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19748. /**
  19749. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19750. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19751. */
  19752. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19753. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19754. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19755. // Edges
  19756. /**
  19757. * Defines edge width used when edgesRenderer is enabled
  19758. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19759. */
  19760. _this.edgesWidth = 1;
  19761. /**
  19762. * Defines edge color used when edgesRenderer is enabled
  19763. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19764. */
  19765. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19766. // Cache
  19767. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19768. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19769. /** @hidden */
  19770. _this._renderId = 0;
  19771. /** @hidden */
  19772. _this._intersectionsInProgress = new Array();
  19773. /** @hidden */
  19774. _this._unIndexed = false;
  19775. /** @hidden */
  19776. _this._lightSources = new Array();
  19777. /**
  19778. * An event triggered when the mesh is rebuilt.
  19779. */
  19780. _this.onRebuildObservable = new BABYLON.Observable();
  19781. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19782. if (collidedMesh === void 0) { collidedMesh = null; }
  19783. //TODO move this to the collision coordinator!
  19784. if (_this.getScene().workerCollisions)
  19785. newPosition.multiplyInPlace(_this._collider._radius);
  19786. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19787. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19788. _this.position.addInPlace(_this._diffPositionForCollisions);
  19789. }
  19790. if (collidedMesh) {
  19791. _this.onCollideObservable.notifyObservers(collidedMesh);
  19792. }
  19793. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19794. };
  19795. _this.getScene().addMesh(_this);
  19796. _this._resyncLightSources();
  19797. return _this;
  19798. }
  19799. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19800. /**
  19801. * No billboard
  19802. */
  19803. get: function () {
  19804. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19810. /** Billboard on X axis */
  19811. get: function () {
  19812. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19813. },
  19814. enumerable: true,
  19815. configurable: true
  19816. });
  19817. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19818. /** Billboard on Y axis */
  19819. get: function () {
  19820. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19826. /** Billboard on Z axis */
  19827. get: function () {
  19828. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19829. },
  19830. enumerable: true,
  19831. configurable: true
  19832. });
  19833. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19834. /** Billboard on all axes */
  19835. get: function () {
  19836. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19837. },
  19838. enumerable: true,
  19839. configurable: true
  19840. });
  19841. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19842. /**
  19843. * Gets the number of facets in the mesh
  19844. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19845. */
  19846. get: function () {
  19847. return this._facetNb;
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19853. /**
  19854. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19855. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19856. */
  19857. get: function () {
  19858. return this._partitioningSubdivisions;
  19859. },
  19860. set: function (nb) {
  19861. this._partitioningSubdivisions = nb;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19867. /**
  19868. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19869. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19870. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19871. */
  19872. get: function () {
  19873. return this._partitioningBBoxRatio;
  19874. },
  19875. set: function (ratio) {
  19876. this._partitioningBBoxRatio = ratio;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19882. /**
  19883. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19884. * Works only for updatable meshes.
  19885. * Doesn't work with multi-materials
  19886. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19887. */
  19888. get: function () {
  19889. return this._facetDepthSort;
  19890. },
  19891. set: function (sort) {
  19892. this._facetDepthSort = sort;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19898. /**
  19899. * The location (Vector3) where the facet depth sort must be computed from.
  19900. * By default, the active camera position.
  19901. * Used only when facet depth sort is enabled
  19902. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19903. */
  19904. get: function () {
  19905. return this._facetDepthSortFrom;
  19906. },
  19907. set: function (location) {
  19908. this._facetDepthSortFrom = location;
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19914. /**
  19915. * gets a boolean indicating if facetData is enabled
  19916. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19917. */
  19918. get: function () {
  19919. return this._facetDataEnabled;
  19920. },
  19921. enumerable: true,
  19922. configurable: true
  19923. });
  19924. /** @hidden */
  19925. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19926. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19927. return false;
  19928. }
  19929. this._markSubMeshesAsMiscDirty();
  19930. return true;
  19931. };
  19932. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19933. /** Set a function to call when this mesh collides with another one */
  19934. set: function (callback) {
  19935. if (this._onCollideObserver) {
  19936. this.onCollideObservable.remove(this._onCollideObserver);
  19937. }
  19938. this._onCollideObserver = this.onCollideObservable.add(callback);
  19939. },
  19940. enumerable: true,
  19941. configurable: true
  19942. });
  19943. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19944. /** Set a function to call when the collision's position changes */
  19945. set: function (callback) {
  19946. if (this._onCollisionPositionChangeObserver) {
  19947. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19948. }
  19949. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19950. },
  19951. enumerable: true,
  19952. configurable: true
  19953. });
  19954. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19955. /**
  19956. * 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
  19957. * @see http://doc.babylonjs.com/features/occlusionquery
  19958. */
  19959. get: function () {
  19960. return this._isOccluded;
  19961. },
  19962. set: function (value) {
  19963. this._isOccluded = value;
  19964. },
  19965. enumerable: true,
  19966. configurable: true
  19967. });
  19968. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19969. /**
  19970. * Flag to check the progress status of the query
  19971. * @see http://doc.babylonjs.com/features/occlusionquery
  19972. */
  19973. get: function () {
  19974. return this._isOcclusionQueryInProgress;
  19975. },
  19976. enumerable: true,
  19977. configurable: true
  19978. });
  19979. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19980. /**
  19981. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19982. */
  19983. get: function () {
  19984. return this._visibility;
  19985. },
  19986. /**
  19987. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19988. */
  19989. set: function (value) {
  19990. if (this._visibility === value) {
  19991. return;
  19992. }
  19993. this._visibility = value;
  19994. this._markSubMeshesAsMiscDirty();
  19995. },
  19996. enumerable: true,
  19997. configurable: true
  19998. });
  19999. Object.defineProperty(AbstractMesh.prototype, "material", {
  20000. /** Gets or sets current material */
  20001. get: function () {
  20002. return this._material;
  20003. },
  20004. set: function (value) {
  20005. if (this._material === value) {
  20006. return;
  20007. }
  20008. this._material = value;
  20009. if (this.onMaterialChangedObservable.hasObservers) {
  20010. this.onMaterialChangedObservable.notifyObservers(this);
  20011. }
  20012. if (!this.subMeshes) {
  20013. return;
  20014. }
  20015. this._unBindEffect();
  20016. },
  20017. enumerable: true,
  20018. configurable: true
  20019. });
  20020. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20021. /**
  20022. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20023. * @see http://doc.babylonjs.com/babylon101/shadows
  20024. */
  20025. get: function () {
  20026. return this._receiveShadows;
  20027. },
  20028. set: function (value) {
  20029. if (this._receiveShadows === value) {
  20030. return;
  20031. }
  20032. this._receiveShadows = value;
  20033. this._markSubMeshesAsLightDirty();
  20034. },
  20035. enumerable: true,
  20036. configurable: true
  20037. });
  20038. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20039. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20040. get: function () {
  20041. return this._hasVertexAlpha;
  20042. },
  20043. set: function (value) {
  20044. if (this._hasVertexAlpha === value) {
  20045. return;
  20046. }
  20047. this._hasVertexAlpha = value;
  20048. this._markSubMeshesAsAttributesDirty();
  20049. this._markSubMeshesAsMiscDirty();
  20050. },
  20051. enumerable: true,
  20052. configurable: true
  20053. });
  20054. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20055. /** 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) */
  20056. get: function () {
  20057. return this._useVertexColors;
  20058. },
  20059. set: function (value) {
  20060. if (this._useVertexColors === value) {
  20061. return;
  20062. }
  20063. this._useVertexColors = value;
  20064. this._markSubMeshesAsAttributesDirty();
  20065. },
  20066. enumerable: true,
  20067. configurable: true
  20068. });
  20069. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20070. /**
  20071. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20072. */
  20073. get: function () {
  20074. return this._computeBonesUsingShaders;
  20075. },
  20076. set: function (value) {
  20077. if (this._computeBonesUsingShaders === value) {
  20078. return;
  20079. }
  20080. this._computeBonesUsingShaders = value;
  20081. this._markSubMeshesAsAttributesDirty();
  20082. },
  20083. enumerable: true,
  20084. configurable: true
  20085. });
  20086. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20087. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20088. get: function () {
  20089. return this._numBoneInfluencers;
  20090. },
  20091. set: function (value) {
  20092. if (this._numBoneInfluencers === value) {
  20093. return;
  20094. }
  20095. this._numBoneInfluencers = value;
  20096. this._markSubMeshesAsAttributesDirty();
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20102. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20103. get: function () {
  20104. return this._applyFog;
  20105. },
  20106. set: function (value) {
  20107. if (this._applyFog === value) {
  20108. return;
  20109. }
  20110. this._applyFog = value;
  20111. this._markSubMeshesAsMiscDirty();
  20112. },
  20113. enumerable: true,
  20114. configurable: true
  20115. });
  20116. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20117. /**
  20118. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20119. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20120. */
  20121. get: function () {
  20122. return this._layerMask;
  20123. },
  20124. set: function (value) {
  20125. if (value === this._layerMask) {
  20126. return;
  20127. }
  20128. this._layerMask = value;
  20129. this._resyncLightSources();
  20130. },
  20131. enumerable: true,
  20132. configurable: true
  20133. });
  20134. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20135. /**
  20136. * Gets or sets a collision mask used to mask collisions (default is -1).
  20137. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20138. */
  20139. get: function () {
  20140. return this._collisionMask;
  20141. },
  20142. set: function (mask) {
  20143. this._collisionMask = !isNaN(mask) ? mask : -1;
  20144. },
  20145. enumerable: true,
  20146. configurable: true
  20147. });
  20148. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20149. /**
  20150. * Gets or sets the current collision group mask (-1 by default).
  20151. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20152. */
  20153. get: function () {
  20154. return this._collisionGroup;
  20155. },
  20156. set: function (mask) {
  20157. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20158. },
  20159. enumerable: true,
  20160. configurable: true
  20161. });
  20162. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20163. /** @hidden */
  20164. get: function () {
  20165. return null;
  20166. },
  20167. enumerable: true,
  20168. configurable: true
  20169. });
  20170. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20171. get: function () {
  20172. return this._skeleton;
  20173. },
  20174. /**
  20175. * Gets or sets a skeleton to apply skining transformations
  20176. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20177. */
  20178. set: function (value) {
  20179. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20180. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20181. }
  20182. if (value && value.needInitialSkinMatrix) {
  20183. value._registerMeshWithPoseMatrix(this);
  20184. }
  20185. this._skeleton = value;
  20186. if (!this._skeleton) {
  20187. this._bonesTransformMatrices = null;
  20188. }
  20189. this._markSubMeshesAsAttributesDirty();
  20190. },
  20191. enumerable: true,
  20192. configurable: true
  20193. });
  20194. /**
  20195. * Returns the string "AbstractMesh"
  20196. * @returns "AbstractMesh"
  20197. */
  20198. AbstractMesh.prototype.getClassName = function () {
  20199. return "AbstractMesh";
  20200. };
  20201. /**
  20202. * Gets a string representation of the current mesh
  20203. * @param fullDetails defines a boolean indicating if full details must be included
  20204. * @returns a string representation of the current mesh
  20205. */
  20206. AbstractMesh.prototype.toString = function (fullDetails) {
  20207. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20208. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20209. if (this._skeleton) {
  20210. ret += ", skeleton: " + this._skeleton.name;
  20211. }
  20212. if (fullDetails) {
  20213. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20214. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20215. }
  20216. return ret;
  20217. };
  20218. /** @hidden */
  20219. AbstractMesh.prototype._rebuild = function () {
  20220. this.onRebuildObservable.notifyObservers(this);
  20221. if (this._occlusionQuery) {
  20222. this._occlusionQuery = null;
  20223. }
  20224. if (!this.subMeshes) {
  20225. return;
  20226. }
  20227. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20228. var subMesh = _a[_i];
  20229. subMesh._rebuild();
  20230. }
  20231. };
  20232. /** @hidden */
  20233. AbstractMesh.prototype._resyncLightSources = function () {
  20234. this._lightSources.length = 0;
  20235. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20236. var light = _a[_i];
  20237. if (!light.isEnabled()) {
  20238. continue;
  20239. }
  20240. if (light.canAffectMesh(this)) {
  20241. this._lightSources.push(light);
  20242. }
  20243. }
  20244. this._markSubMeshesAsLightDirty();
  20245. };
  20246. /** @hidden */
  20247. AbstractMesh.prototype._resyncLighSource = function (light) {
  20248. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20249. var index = this._lightSources.indexOf(light);
  20250. if (index === -1) {
  20251. if (!isIn) {
  20252. return;
  20253. }
  20254. this._lightSources.push(light);
  20255. }
  20256. else {
  20257. if (isIn) {
  20258. return;
  20259. }
  20260. this._lightSources.splice(index, 1);
  20261. }
  20262. this._markSubMeshesAsLightDirty();
  20263. };
  20264. /** @hidden */
  20265. AbstractMesh.prototype._unBindEffect = function () {
  20266. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20267. var subMesh = _a[_i];
  20268. subMesh.setEffect(null);
  20269. }
  20270. };
  20271. /** @hidden */
  20272. AbstractMesh.prototype._removeLightSource = function (light) {
  20273. var index = this._lightSources.indexOf(light);
  20274. if (index === -1) {
  20275. return;
  20276. }
  20277. this._lightSources.splice(index, 1);
  20278. this._markSubMeshesAsLightDirty();
  20279. };
  20280. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20281. if (!this.subMeshes) {
  20282. return;
  20283. }
  20284. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20285. var subMesh = _a[_i];
  20286. if (subMesh._materialDefines) {
  20287. func(subMesh._materialDefines);
  20288. }
  20289. }
  20290. };
  20291. /** @hidden */
  20292. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20293. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20294. };
  20295. /** @hidden */
  20296. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20297. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20298. };
  20299. /** @hidden */
  20300. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20301. if (!this.subMeshes) {
  20302. return;
  20303. }
  20304. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20305. var subMesh = _a[_i];
  20306. var material = subMesh.getMaterial();
  20307. if (material) {
  20308. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20309. }
  20310. }
  20311. };
  20312. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20313. /**
  20314. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20315. */
  20316. get: function () {
  20317. return this._scaling;
  20318. },
  20319. set: function (newScaling) {
  20320. this._scaling = newScaling;
  20321. if (this.physicsImpostor) {
  20322. this.physicsImpostor.forceUpdate();
  20323. }
  20324. },
  20325. enumerable: true,
  20326. configurable: true
  20327. });
  20328. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20329. // Methods
  20330. /**
  20331. * Returns true if the mesh is blocked. Implemented by child classes
  20332. */
  20333. get: function () {
  20334. return false;
  20335. },
  20336. enumerable: true,
  20337. configurable: true
  20338. });
  20339. /**
  20340. * Returns the mesh itself by default. Implemented by child classes
  20341. * @param camera defines the camera to use to pick the right LOD level
  20342. * @returns the currentAbstractMesh
  20343. */
  20344. AbstractMesh.prototype.getLOD = function (camera) {
  20345. return this;
  20346. };
  20347. /**
  20348. * Returns 0 by default. Implemented by child classes
  20349. * @returns an integer
  20350. */
  20351. AbstractMesh.prototype.getTotalVertices = function () {
  20352. return 0;
  20353. };
  20354. /**
  20355. * Returns null by default. Implemented by child classes
  20356. * @returns null
  20357. */
  20358. AbstractMesh.prototype.getIndices = function () {
  20359. return null;
  20360. };
  20361. /**
  20362. * Returns the array of the requested vertex data kind. Implemented by child classes
  20363. * @param kind defines the vertex data kind to use
  20364. * @returns null
  20365. */
  20366. AbstractMesh.prototype.getVerticesData = function (kind) {
  20367. return null;
  20368. };
  20369. /**
  20370. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20371. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20372. * Note that a new underlying VertexBuffer object is created each call.
  20373. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20374. * @param kind defines vertex data kind:
  20375. * * BABYLON.VertexBuffer.PositionKind
  20376. * * BABYLON.VertexBuffer.UVKind
  20377. * * BABYLON.VertexBuffer.UV2Kind
  20378. * * BABYLON.VertexBuffer.UV3Kind
  20379. * * BABYLON.VertexBuffer.UV4Kind
  20380. * * BABYLON.VertexBuffer.UV5Kind
  20381. * * BABYLON.VertexBuffer.UV6Kind
  20382. * * BABYLON.VertexBuffer.ColorKind
  20383. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20384. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20385. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20386. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20387. * @param data defines the data source
  20388. * @param updatable defines if the data must be flagged as updatable (or static)
  20389. * @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
  20390. * @returns the current mesh
  20391. */
  20392. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20393. return this;
  20394. };
  20395. /**
  20396. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20397. * If the mesh has no geometry, it is simply returned as it is.
  20398. * @param kind defines vertex data kind:
  20399. * * BABYLON.VertexBuffer.PositionKind
  20400. * * BABYLON.VertexBuffer.UVKind
  20401. * * BABYLON.VertexBuffer.UV2Kind
  20402. * * BABYLON.VertexBuffer.UV3Kind
  20403. * * BABYLON.VertexBuffer.UV4Kind
  20404. * * BABYLON.VertexBuffer.UV5Kind
  20405. * * BABYLON.VertexBuffer.UV6Kind
  20406. * * BABYLON.VertexBuffer.ColorKind
  20407. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20408. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20409. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20410. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20411. * @param data defines the data source
  20412. * @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
  20413. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20414. * @returns the current mesh
  20415. */
  20416. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20417. return this;
  20418. };
  20419. /**
  20420. * Sets the mesh indices,
  20421. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20422. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20423. * @param totalVertices Defines the total number of vertices
  20424. * @returns the current mesh
  20425. */
  20426. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20427. return this;
  20428. };
  20429. /**
  20430. * Gets a boolean indicating if specific vertex data is present
  20431. * @param kind defines the vertex data kind to use
  20432. * @returns true is data kind is present
  20433. */
  20434. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20435. return false;
  20436. };
  20437. /**
  20438. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20439. * @returns a BoundingInfo
  20440. */
  20441. AbstractMesh.prototype.getBoundingInfo = function () {
  20442. if (this._masterMesh) {
  20443. return this._masterMesh.getBoundingInfo();
  20444. }
  20445. if (!this._boundingInfo) {
  20446. // this._boundingInfo is being created here
  20447. this._updateBoundingInfo();
  20448. }
  20449. // cannot be null.
  20450. return this._boundingInfo;
  20451. };
  20452. /**
  20453. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20454. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20455. * @returns the current mesh
  20456. */
  20457. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20458. if (includeDescendants === void 0) { includeDescendants = true; }
  20459. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20460. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20461. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20462. if (maxDimension === 0) {
  20463. return this;
  20464. }
  20465. var scale = 1 / maxDimension;
  20466. this.scaling.scaleInPlace(scale);
  20467. return this;
  20468. };
  20469. /**
  20470. * Overwrite the current bounding info
  20471. * @param boundingInfo defines the new bounding info
  20472. * @returns the current mesh
  20473. */
  20474. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20475. this._boundingInfo = boundingInfo;
  20476. return this;
  20477. };
  20478. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20479. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20480. get: function () {
  20481. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20482. },
  20483. enumerable: true,
  20484. configurable: true
  20485. });
  20486. /** @hidden */
  20487. AbstractMesh.prototype._preActivate = function () {
  20488. };
  20489. /** @hidden */
  20490. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20491. };
  20492. /** @hidden */
  20493. AbstractMesh.prototype._activate = function (renderId) {
  20494. this._renderId = renderId;
  20495. };
  20496. /**
  20497. * Gets the current world matrix
  20498. * @returns a Matrix
  20499. */
  20500. AbstractMesh.prototype.getWorldMatrix = function () {
  20501. if (this._masterMesh) {
  20502. return this._masterMesh.getWorldMatrix();
  20503. }
  20504. return _super.prototype.getWorldMatrix.call(this);
  20505. };
  20506. /** @hidden */
  20507. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20508. if (this._masterMesh) {
  20509. return this._masterMesh._getWorldMatrixDeterminant();
  20510. }
  20511. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20512. };
  20513. // ================================== Point of View Movement =================================
  20514. /**
  20515. * Perform relative position change from the point of view of behind the front of the mesh.
  20516. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20517. * Supports definition of mesh facing forward or backward
  20518. * @param amountRight defines the distance on the right axis
  20519. * @param amountUp defines the distance on the up axis
  20520. * @param amountForward defines the distance on the forward axis
  20521. * @returns the current mesh
  20522. */
  20523. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20524. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20525. return this;
  20526. };
  20527. /**
  20528. * Calculate relative position change from the point of view of behind the front of the mesh.
  20529. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20530. * Supports definition of mesh facing forward or backward
  20531. * @param amountRight defines the distance on the right axis
  20532. * @param amountUp defines the distance on the up axis
  20533. * @param amountForward defines the distance on the forward axis
  20534. * @returns the new displacement vector
  20535. */
  20536. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20537. var rotMatrix = new BABYLON.Matrix();
  20538. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20539. rotQuaternion.toRotationMatrix(rotMatrix);
  20540. var translationDelta = BABYLON.Vector3.Zero();
  20541. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20542. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20543. return translationDelta;
  20544. };
  20545. // ================================== Point of View Rotation =================================
  20546. /**
  20547. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20548. * Supports definition of mesh facing forward or backward
  20549. * @param flipBack defines the flip
  20550. * @param twirlClockwise defines the twirl
  20551. * @param tiltRight defines the tilt
  20552. * @returns the current mesh
  20553. */
  20554. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20555. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20556. return this;
  20557. };
  20558. /**
  20559. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20560. * Supports definition of mesh facing forward or backward.
  20561. * @param flipBack defines the flip
  20562. * @param twirlClockwise defines the twirl
  20563. * @param tiltRight defines the tilt
  20564. * @returns the new rotation vector
  20565. */
  20566. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20567. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20568. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20569. };
  20570. /**
  20571. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20572. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20573. * @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
  20574. * @returns the new bounding vectors
  20575. */
  20576. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20577. if (includeDescendants === void 0) { includeDescendants = true; }
  20578. if (predicate === void 0) { predicate = null; }
  20579. // Ensures that all world matrix will be recomputed.
  20580. this.getScene().incrementRenderId();
  20581. this.computeWorldMatrix(true);
  20582. var min;
  20583. var max;
  20584. var boundingInfo = this.getBoundingInfo();
  20585. if (!this.subMeshes) {
  20586. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20587. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20588. }
  20589. else {
  20590. min = boundingInfo.boundingBox.minimumWorld;
  20591. max = boundingInfo.boundingBox.maximumWorld;
  20592. }
  20593. if (includeDescendants) {
  20594. var descendants = this.getDescendants(false);
  20595. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20596. var descendant = descendants_1[_i];
  20597. var childMesh = descendant;
  20598. childMesh.computeWorldMatrix(true);
  20599. // Filters meshes based on custom predicate function.
  20600. if (predicate && !predicate(childMesh)) {
  20601. continue;
  20602. }
  20603. //make sure we have the needed params to get mix and max
  20604. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20605. continue;
  20606. }
  20607. var childBoundingInfo = childMesh.getBoundingInfo();
  20608. var boundingBox = childBoundingInfo.boundingBox;
  20609. var minBox = boundingBox.minimumWorld;
  20610. var maxBox = boundingBox.maximumWorld;
  20611. BABYLON.Tools.CheckExtends(minBox, min, max);
  20612. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20613. }
  20614. }
  20615. return {
  20616. min: min,
  20617. max: max
  20618. };
  20619. };
  20620. /** @hidden */
  20621. AbstractMesh.prototype._updateBoundingInfo = function () {
  20622. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20623. this._boundingInfo.update(this.worldMatrixFromCache);
  20624. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20625. return this;
  20626. };
  20627. /** @hidden */
  20628. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20629. if (!this.subMeshes) {
  20630. return this;
  20631. }
  20632. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20633. var subMesh = this.subMeshes[subIndex];
  20634. if (!subMesh.IsGlobal) {
  20635. subMesh.updateBoundingInfo(matrix);
  20636. }
  20637. }
  20638. return this;
  20639. };
  20640. /** @hidden */
  20641. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20642. // Bounding info
  20643. this._updateBoundingInfo();
  20644. };
  20645. /**
  20646. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20647. * A mesh is in the frustum if its bounding box intersects the frustum
  20648. * @param frustumPlanes defines the frustum to test
  20649. * @returns true if the mesh is in the frustum planes
  20650. */
  20651. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20652. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20653. };
  20654. /**
  20655. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20656. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20657. * @param frustumPlanes defines the frustum to test
  20658. * @returns true if the mesh is completely in the frustum planes
  20659. */
  20660. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20661. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20662. };
  20663. /**
  20664. * True if the mesh intersects another mesh or a SolidParticle object
  20665. * @param mesh defines a target mesh or SolidParticle to test
  20666. * @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)
  20667. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20668. * @returns true if there is an intersection
  20669. */
  20670. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20671. if (precise === void 0) { precise = false; }
  20672. if (!this._boundingInfo || !mesh._boundingInfo) {
  20673. return false;
  20674. }
  20675. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20676. return true;
  20677. }
  20678. if (includeDescendants) {
  20679. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20680. var child = _a[_i];
  20681. if (child.intersectsMesh(mesh, precise, true)) {
  20682. return true;
  20683. }
  20684. }
  20685. }
  20686. return false;
  20687. };
  20688. /**
  20689. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20690. * @param point defines the point to test
  20691. * @returns true if there is an intersection
  20692. */
  20693. AbstractMesh.prototype.intersectsPoint = function (point) {
  20694. if (!this._boundingInfo) {
  20695. return false;
  20696. }
  20697. return this._boundingInfo.intersectsPoint(point);
  20698. };
  20699. /**
  20700. * Gets the position of the current mesh in camera space
  20701. * @param camera defines the camera to use
  20702. * @returns a position
  20703. */
  20704. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20705. if (camera === void 0) { camera = null; }
  20706. if (!camera) {
  20707. camera = this.getScene().activeCamera;
  20708. }
  20709. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20710. };
  20711. /**
  20712. * Returns the distance from the mesh to the active camera
  20713. * @param camera defines the camera to use
  20714. * @returns the distance
  20715. */
  20716. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20717. if (camera === void 0) { camera = null; }
  20718. if (!camera) {
  20719. camera = this.getScene().activeCamera;
  20720. }
  20721. return this.absolutePosition.subtract(camera.position).length();
  20722. };
  20723. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20724. // Collisions
  20725. /**
  20726. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20727. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20728. */
  20729. get: function () {
  20730. return this._checkCollisions;
  20731. },
  20732. set: function (collisionEnabled) {
  20733. this._checkCollisions = collisionEnabled;
  20734. if (this.getScene().workerCollisions) {
  20735. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20736. }
  20737. },
  20738. enumerable: true,
  20739. configurable: true
  20740. });
  20741. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20742. /**
  20743. * Gets Collider object used to compute collisions (not physics)
  20744. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20745. */
  20746. get: function () {
  20747. return this._collider;
  20748. },
  20749. enumerable: true,
  20750. configurable: true
  20751. });
  20752. /**
  20753. * Move the mesh using collision engine
  20754. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20755. * @param displacement defines the requested displacement vector
  20756. * @returns the current mesh
  20757. */
  20758. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20759. var globalPosition = this.getAbsolutePosition();
  20760. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20761. if (!this._collider) {
  20762. this._collider = new BABYLON.Collider();
  20763. }
  20764. this._collider._radius = this.ellipsoid;
  20765. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20766. return this;
  20767. };
  20768. // Collisions
  20769. /** @hidden */
  20770. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20771. this._generatePointsArray();
  20772. if (!this._positions) {
  20773. return this;
  20774. }
  20775. // Transformation
  20776. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20777. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20778. subMesh._lastColliderWorldVertices = [];
  20779. subMesh._trianglePlanes = [];
  20780. var start = subMesh.verticesStart;
  20781. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20782. for (var i = start; i < end; i++) {
  20783. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20784. }
  20785. }
  20786. // Collide
  20787. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20788. if (collider.collisionFound) {
  20789. collider.collidedMesh = this;
  20790. }
  20791. return this;
  20792. };
  20793. /** @hidden */
  20794. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20795. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20796. var len = subMeshes.length;
  20797. for (var index = 0; index < len; index++) {
  20798. var subMesh = subMeshes.data[index];
  20799. // Bounding test
  20800. if (len > 1 && !subMesh._checkCollision(collider))
  20801. continue;
  20802. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20803. }
  20804. return this;
  20805. };
  20806. /** @hidden */
  20807. AbstractMesh.prototype._checkCollision = function (collider) {
  20808. // Bounding box test
  20809. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20810. return this;
  20811. // Transformation matrix
  20812. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20813. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20814. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20815. return this;
  20816. };
  20817. // Picking
  20818. /** @hidden */
  20819. AbstractMesh.prototype._generatePointsArray = function () {
  20820. return false;
  20821. };
  20822. /**
  20823. * Checks if the passed Ray intersects with the mesh
  20824. * @param ray defines the ray to use
  20825. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20826. * @returns the picking info
  20827. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20828. */
  20829. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20830. var pickingInfo = new BABYLON.PickingInfo();
  20831. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20832. return pickingInfo;
  20833. }
  20834. if (!this._generatePointsArray()) {
  20835. return pickingInfo;
  20836. }
  20837. var intersectInfo = null;
  20838. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20839. var len = subMeshes.length;
  20840. for (var index = 0; index < len; index++) {
  20841. var subMesh = subMeshes.data[index];
  20842. // Bounding test
  20843. if (len > 1 && !subMesh.canIntersects(ray))
  20844. continue;
  20845. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20846. if (currentIntersectInfo) {
  20847. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20848. intersectInfo = currentIntersectInfo;
  20849. intersectInfo.subMeshId = index;
  20850. if (fastCheck) {
  20851. break;
  20852. }
  20853. }
  20854. }
  20855. }
  20856. if (intersectInfo) {
  20857. // Get picked point
  20858. var world = this.getWorldMatrix();
  20859. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20860. var direction = ray.direction.clone();
  20861. direction = direction.scale(intersectInfo.distance);
  20862. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20863. var pickedPoint = worldOrigin.add(worldDirection);
  20864. // Return result
  20865. pickingInfo.hit = true;
  20866. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20867. pickingInfo.pickedPoint = pickedPoint;
  20868. pickingInfo.pickedMesh = this;
  20869. pickingInfo.bu = intersectInfo.bu || 0;
  20870. pickingInfo.bv = intersectInfo.bv || 0;
  20871. pickingInfo.faceId = intersectInfo.faceId;
  20872. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20873. return pickingInfo;
  20874. }
  20875. return pickingInfo;
  20876. };
  20877. /**
  20878. * Clones the current mesh
  20879. * @param name defines the mesh name
  20880. * @param newParent defines the new mesh parent
  20881. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20882. * @returns the new mesh
  20883. */
  20884. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20885. return null;
  20886. };
  20887. /**
  20888. * Disposes all the submeshes of the current meshnp
  20889. * @returns the current mesh
  20890. */
  20891. AbstractMesh.prototype.releaseSubMeshes = function () {
  20892. if (this.subMeshes) {
  20893. while (this.subMeshes.length) {
  20894. this.subMeshes[0].dispose();
  20895. }
  20896. }
  20897. else {
  20898. this.subMeshes = new Array();
  20899. }
  20900. return this;
  20901. };
  20902. /**
  20903. * Releases resources associated with this abstract mesh.
  20904. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20905. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20906. */
  20907. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20908. var _this = this;
  20909. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20910. var index;
  20911. // Smart Array Retainers.
  20912. this.getScene().freeActiveMeshes();
  20913. this.getScene().freeRenderingGroups();
  20914. // Action manager
  20915. if (this.actionManager !== undefined && this.actionManager !== null) {
  20916. this.actionManager.dispose();
  20917. this.actionManager = null;
  20918. }
  20919. // Skeleton
  20920. this._skeleton = null;
  20921. // Intersections in progress
  20922. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20923. var other = this._intersectionsInProgress[index];
  20924. var pos = other._intersectionsInProgress.indexOf(this);
  20925. other._intersectionsInProgress.splice(pos, 1);
  20926. }
  20927. this._intersectionsInProgress = [];
  20928. // Lights
  20929. var lights = this.getScene().lights;
  20930. lights.forEach(function (light) {
  20931. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20932. if (meshIndex !== -1) {
  20933. light.includedOnlyMeshes.splice(meshIndex, 1);
  20934. }
  20935. meshIndex = light.excludedMeshes.indexOf(_this);
  20936. if (meshIndex !== -1) {
  20937. light.excludedMeshes.splice(meshIndex, 1);
  20938. }
  20939. // Shadow generators
  20940. var generator = light.getShadowGenerator();
  20941. if (generator) {
  20942. var shadowMap = generator.getShadowMap();
  20943. if (shadowMap && shadowMap.renderList) {
  20944. meshIndex = shadowMap.renderList.indexOf(_this);
  20945. if (meshIndex !== -1) {
  20946. shadowMap.renderList.splice(meshIndex, 1);
  20947. }
  20948. }
  20949. }
  20950. });
  20951. // SubMeshes
  20952. if (this.getClassName() !== "InstancedMesh") {
  20953. this.releaseSubMeshes();
  20954. }
  20955. // Query
  20956. var engine = this.getScene().getEngine();
  20957. if (this._occlusionQuery) {
  20958. this._isOcclusionQueryInProgress = false;
  20959. engine.deleteQuery(this._occlusionQuery);
  20960. this._occlusionQuery = null;
  20961. }
  20962. // Engine
  20963. engine.wipeCaches();
  20964. // Remove from scene
  20965. this.getScene().removeMesh(this);
  20966. if (disposeMaterialAndTextures) {
  20967. if (this.material) {
  20968. this.material.dispose(false, true);
  20969. }
  20970. }
  20971. if (!doNotRecurse) {
  20972. // Particles
  20973. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20974. if (this.getScene().particleSystems[index].emitter === this) {
  20975. this.getScene().particleSystems[index].dispose();
  20976. index--;
  20977. }
  20978. }
  20979. }
  20980. // facet data
  20981. if (this._facetDataEnabled) {
  20982. this.disableFacetData();
  20983. }
  20984. this.onAfterWorldMatrixUpdateObservable.clear();
  20985. this.onCollideObservable.clear();
  20986. this.onCollisionPositionChangeObservable.clear();
  20987. this.onRebuildObservable.clear();
  20988. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20989. };
  20990. /**
  20991. * Adds the passed mesh as a child to the current mesh
  20992. * @param mesh defines the child mesh
  20993. * @returns the current mesh
  20994. */
  20995. AbstractMesh.prototype.addChild = function (mesh) {
  20996. mesh.setParent(this);
  20997. return this;
  20998. };
  20999. /**
  21000. * Removes the passed mesh from the current mesh children list
  21001. * @param mesh defines the child mesh
  21002. * @returns the current mesh
  21003. */
  21004. AbstractMesh.prototype.removeChild = function (mesh) {
  21005. mesh.setParent(null);
  21006. return this;
  21007. };
  21008. // Facet data
  21009. /** @hidden */
  21010. AbstractMesh.prototype._initFacetData = function () {
  21011. if (!this._facetNormals) {
  21012. this._facetNormals = new Array();
  21013. }
  21014. if (!this._facetPositions) {
  21015. this._facetPositions = new Array();
  21016. }
  21017. if (!this._facetPartitioning) {
  21018. this._facetPartitioning = new Array();
  21019. }
  21020. this._facetNb = (this.getIndices().length / 3) | 0;
  21021. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21022. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21023. for (var f = 0; f < this._facetNb; f++) {
  21024. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21025. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21026. }
  21027. this._facetDataEnabled = true;
  21028. return this;
  21029. };
  21030. /**
  21031. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21032. * This method can be called within the render loop.
  21033. * 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
  21034. * @returns the current mesh
  21035. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21036. */
  21037. AbstractMesh.prototype.updateFacetData = function () {
  21038. if (!this._facetDataEnabled) {
  21039. this._initFacetData();
  21040. }
  21041. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21042. var indices = this.getIndices();
  21043. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21044. var bInfo = this.getBoundingInfo();
  21045. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21046. // init arrays, matrix and sort function on first call
  21047. this._facetDepthSortEnabled = true;
  21048. if (indices instanceof Uint16Array) {
  21049. this._depthSortedIndices = new Uint16Array(indices);
  21050. }
  21051. else if (indices instanceof Uint32Array) {
  21052. this._depthSortedIndices = new Uint32Array(indices);
  21053. }
  21054. else {
  21055. var needs32bits = false;
  21056. for (var i = 0; i < indices.length; i++) {
  21057. if (indices[i] > 65535) {
  21058. needs32bits = true;
  21059. break;
  21060. }
  21061. }
  21062. if (needs32bits) {
  21063. this._depthSortedIndices = new Uint32Array(indices);
  21064. }
  21065. else {
  21066. this._depthSortedIndices = new Uint16Array(indices);
  21067. }
  21068. }
  21069. this._facetDepthSortFunction = function (f1, f2) {
  21070. return (f2.sqDistance - f1.sqDistance);
  21071. };
  21072. if (!this._facetDepthSortFrom) {
  21073. var camera = this.getScene().activeCamera;
  21074. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21075. }
  21076. this._depthSortedFacets = [];
  21077. for (var f = 0; f < this._facetNb; f++) {
  21078. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21079. this._depthSortedFacets.push(depthSortedFacet);
  21080. }
  21081. this._invertedMatrix = BABYLON.Matrix.Identity();
  21082. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21083. }
  21084. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21085. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21086. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21087. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21088. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21089. this._subDiv.max = this._partitioningSubdivisions;
  21090. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21091. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21092. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21093. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21094. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21095. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21096. // set the parameters for ComputeNormals()
  21097. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21098. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21099. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21100. this._facetParameters.bInfo = bInfo;
  21101. this._facetParameters.bbSize = this._bbSize;
  21102. this._facetParameters.subDiv = this._subDiv;
  21103. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21104. this._facetParameters.depthSort = this._facetDepthSort;
  21105. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21106. this.computeWorldMatrix(true);
  21107. this._worldMatrix.invertToRef(this._invertedMatrix);
  21108. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21109. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21110. }
  21111. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21112. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21113. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21114. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21115. var l = (this._depthSortedIndices.length / 3) | 0;
  21116. for (var f = 0; f < l; f++) {
  21117. var sind = this._depthSortedFacets[f].ind;
  21118. this._depthSortedIndices[f * 3] = indices[sind];
  21119. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21120. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21121. }
  21122. this.updateIndices(this._depthSortedIndices);
  21123. }
  21124. return this;
  21125. };
  21126. /**
  21127. * Returns the facetLocalNormals array.
  21128. * The normals are expressed in the mesh local spac
  21129. * @returns an array of Vector3
  21130. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21131. */
  21132. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21133. if (!this._facetNormals) {
  21134. this.updateFacetData();
  21135. }
  21136. return this._facetNormals;
  21137. };
  21138. /**
  21139. * Returns the facetLocalPositions array.
  21140. * The facet positions are expressed in the mesh local space
  21141. * @returns an array of Vector3
  21142. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21143. */
  21144. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21145. if (!this._facetPositions) {
  21146. this.updateFacetData();
  21147. }
  21148. return this._facetPositions;
  21149. };
  21150. /**
  21151. * Returns the facetLocalPartioning array
  21152. * @returns an array of array of numbers
  21153. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21154. */
  21155. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21156. if (!this._facetPartitioning) {
  21157. this.updateFacetData();
  21158. }
  21159. return this._facetPartitioning;
  21160. };
  21161. /**
  21162. * Returns the i-th facet position in the world system.
  21163. * This method allocates a new Vector3 per call
  21164. * @param i defines the facet index
  21165. * @returns a new Vector3
  21166. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21167. */
  21168. AbstractMesh.prototype.getFacetPosition = function (i) {
  21169. var pos = BABYLON.Vector3.Zero();
  21170. this.getFacetPositionToRef(i, pos);
  21171. return pos;
  21172. };
  21173. /**
  21174. * Sets the reference Vector3 with the i-th facet position in the world system
  21175. * @param i defines the facet index
  21176. * @param ref defines the target vector
  21177. * @returns the current mesh
  21178. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21179. */
  21180. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21181. var localPos = (this.getFacetLocalPositions())[i];
  21182. var world = this.getWorldMatrix();
  21183. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21184. return this;
  21185. };
  21186. /**
  21187. * Returns the i-th facet normal in the world system.
  21188. * This method allocates a new Vector3 per call
  21189. * @param i defines the facet index
  21190. * @returns a new Vector3
  21191. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21192. */
  21193. AbstractMesh.prototype.getFacetNormal = function (i) {
  21194. var norm = BABYLON.Vector3.Zero();
  21195. this.getFacetNormalToRef(i, norm);
  21196. return norm;
  21197. };
  21198. /**
  21199. * Sets the reference Vector3 with the i-th facet normal in the world system
  21200. * @param i defines the facet index
  21201. * @param ref defines the target vector
  21202. * @returns the current mesh
  21203. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21204. */
  21205. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21206. var localNorm = (this.getFacetLocalNormals())[i];
  21207. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21208. return this;
  21209. };
  21210. /**
  21211. * 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)
  21212. * @param x defines x coordinate
  21213. * @param y defines y coordinate
  21214. * @param z defines z coordinate
  21215. * @returns the array of facet indexes
  21216. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21217. */
  21218. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21219. var bInfo = this.getBoundingInfo();
  21220. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21221. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21222. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21223. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21224. return null;
  21225. }
  21226. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21227. };
  21228. /**
  21229. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21230. * @param projected sets as the (x,y,z) world projection on the facet
  21231. * @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
  21232. * @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
  21233. * @param x defines x coordinate
  21234. * @param y defines y coordinate
  21235. * @param z defines z coordinate
  21236. * @returns the face index if found (or null instead)
  21237. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21238. */
  21239. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21240. if (checkFace === void 0) { checkFace = false; }
  21241. if (facing === void 0) { facing = true; }
  21242. var world = this.getWorldMatrix();
  21243. var invMat = BABYLON.Tmp.Matrix[5];
  21244. world.invertToRef(invMat);
  21245. var invVect = BABYLON.Tmp.Vector3[8];
  21246. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21247. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21248. if (projected) {
  21249. // tranform the local computed projected vector to world coordinates
  21250. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21251. }
  21252. return closest;
  21253. };
  21254. /**
  21255. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21256. * @param projected sets as the (x,y,z) local projection on the facet
  21257. * @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
  21258. * @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
  21259. * @param x defines x coordinate
  21260. * @param y defines y coordinate
  21261. * @param z defines z coordinate
  21262. * @returns the face index if found (or null instead)
  21263. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21264. */
  21265. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21266. if (checkFace === void 0) { checkFace = false; }
  21267. if (facing === void 0) { facing = true; }
  21268. var closest = null;
  21269. var tmpx = 0.0;
  21270. var tmpy = 0.0;
  21271. var tmpz = 0.0;
  21272. var d = 0.0; // tmp dot facet normal * facet position
  21273. var t0 = 0.0;
  21274. var projx = 0.0;
  21275. var projy = 0.0;
  21276. var projz = 0.0;
  21277. // Get all the facets in the same partitioning block than (x, y, z)
  21278. var facetPositions = this.getFacetLocalPositions();
  21279. var facetNormals = this.getFacetLocalNormals();
  21280. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21281. if (!facetsInBlock) {
  21282. return null;
  21283. }
  21284. // Get the closest facet to (x, y, z)
  21285. var shortest = Number.MAX_VALUE; // init distance vars
  21286. var tmpDistance = shortest;
  21287. var fib; // current facet in the block
  21288. var norm; // current facet normal
  21289. var p0; // current facet barycenter position
  21290. // loop on all the facets in the current partitioning block
  21291. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21292. fib = facetsInBlock[idx];
  21293. norm = facetNormals[fib];
  21294. p0 = facetPositions[fib];
  21295. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21296. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21297. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21298. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21299. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21300. projx = x + norm.x * t0;
  21301. projy = y + norm.y * t0;
  21302. projz = z + norm.z * t0;
  21303. tmpx = projx - x;
  21304. tmpy = projy - y;
  21305. tmpz = projz - z;
  21306. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21307. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21308. shortest = tmpDistance;
  21309. closest = fib;
  21310. if (projected) {
  21311. projected.x = projx;
  21312. projected.y = projy;
  21313. projected.z = projz;
  21314. }
  21315. }
  21316. }
  21317. }
  21318. return closest;
  21319. };
  21320. /**
  21321. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21322. * @returns the parameters
  21323. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21324. */
  21325. AbstractMesh.prototype.getFacetDataParameters = function () {
  21326. return this._facetParameters;
  21327. };
  21328. /**
  21329. * Disables the feature FacetData and frees the related memory
  21330. * @returns the current mesh
  21331. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21332. */
  21333. AbstractMesh.prototype.disableFacetData = function () {
  21334. if (this._facetDataEnabled) {
  21335. this._facetDataEnabled = false;
  21336. this._facetPositions = new Array();
  21337. this._facetNormals = new Array();
  21338. this._facetPartitioning = new Array();
  21339. this._facetParameters = null;
  21340. this._depthSortedIndices = new Uint32Array(0);
  21341. }
  21342. return this;
  21343. };
  21344. /**
  21345. * Updates the AbstractMesh indices array
  21346. * @param indices defines the data source
  21347. * @returns the current mesh
  21348. */
  21349. AbstractMesh.prototype.updateIndices = function (indices) {
  21350. return this;
  21351. };
  21352. /**
  21353. * Creates new normals data for the mesh
  21354. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21355. * @returns the current mesh
  21356. */
  21357. AbstractMesh.prototype.createNormals = function (updatable) {
  21358. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21359. var indices = this.getIndices();
  21360. var normals;
  21361. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21362. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21363. }
  21364. else {
  21365. normals = [];
  21366. }
  21367. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21368. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21369. return this;
  21370. };
  21371. /**
  21372. * Align the mesh with a normal
  21373. * @param normal defines the normal to use
  21374. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21375. * @returns the current mesh
  21376. */
  21377. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21378. if (!upDirection) {
  21379. upDirection = BABYLON.Axis.Y;
  21380. }
  21381. var axisX = BABYLON.Tmp.Vector3[0];
  21382. var axisZ = BABYLON.Tmp.Vector3[1];
  21383. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21384. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21385. if (this.rotationQuaternion) {
  21386. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21387. }
  21388. else {
  21389. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21390. }
  21391. return this;
  21392. };
  21393. /** @hidden */
  21394. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21395. this._isOccluded = false;
  21396. };
  21397. /** No occlusion */
  21398. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21399. /** Occlusion set to optimisitic */
  21400. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21401. /** Occlusion set to strict */
  21402. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21403. /** Use an accurante occlusion algorithm */
  21404. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21405. /** Use a conservative occlusion algorithm */
  21406. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21407. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21408. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21409. /** Culling strategy with bounding sphere only and then frustum culling */
  21410. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21411. return AbstractMesh;
  21412. }(BABYLON.TransformNode));
  21413. BABYLON.AbstractMesh = AbstractMesh;
  21414. })(BABYLON || (BABYLON = {}));
  21415. //# sourceMappingURL=babylon.abstractMesh.js.map
  21416. var BABYLON;
  21417. (function (BABYLON) {
  21418. /**
  21419. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21420. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21421. * 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.
  21422. */
  21423. var Light = /** @class */ (function (_super) {
  21424. __extends(Light, _super);
  21425. /**
  21426. * Creates a Light object in the scene.
  21427. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21428. * @param name The firendly name of the light
  21429. * @param scene The scene the light belongs too
  21430. */
  21431. function Light(name, scene) {
  21432. var _this = _super.call(this, name, scene) || this;
  21433. /**
  21434. * Diffuse gives the basic color to an object.
  21435. */
  21436. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21437. /**
  21438. * Specular produces a highlight color on an object.
  21439. * Note: This is note affecting PBR materials.
  21440. */
  21441. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21442. /**
  21443. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21444. * falling off base on range or angle.
  21445. * This can be set to any values in Light.FALLOFF_x.
  21446. *
  21447. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21448. * other types of materials.
  21449. */
  21450. _this.falloffType = Light.FALLOFF_DEFAULT;
  21451. /**
  21452. * Strength of the light.
  21453. * Note: By default it is define in the framework own unit.
  21454. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21455. */
  21456. _this.intensity = 1.0;
  21457. _this._range = Number.MAX_VALUE;
  21458. _this._inverseSquaredRange = 0;
  21459. /**
  21460. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21461. * of light.
  21462. */
  21463. _this._photometricScale = 1.0;
  21464. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21465. _this._radius = 0.00001;
  21466. /**
  21467. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21468. * exceeding the number allowed of the materials.
  21469. */
  21470. _this.renderPriority = 0;
  21471. _this._shadowEnabled = true;
  21472. _this._excludeWithLayerMask = 0;
  21473. _this._includeOnlyWithLayerMask = 0;
  21474. _this._lightmapMode = 0;
  21475. /**
  21476. * @hidden Internal use only.
  21477. */
  21478. _this._excludedMeshesIds = new Array();
  21479. /**
  21480. * @hidden Internal use only.
  21481. */
  21482. _this._includedOnlyMeshesIds = new Array();
  21483. _this.getScene().addLight(_this);
  21484. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21485. _this._buildUniformLayout();
  21486. _this.includedOnlyMeshes = new Array();
  21487. _this.excludedMeshes = new Array();
  21488. _this._resyncMeshes();
  21489. return _this;
  21490. }
  21491. Object.defineProperty(Light.prototype, "range", {
  21492. /**
  21493. * Defines how far from the source the light is impacting in scene units.
  21494. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21495. */
  21496. get: function () {
  21497. return this._range;
  21498. },
  21499. /**
  21500. * Defines how far from the source the light is impacting in scene units.
  21501. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21502. */
  21503. set: function (value) {
  21504. this._range = value;
  21505. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21506. },
  21507. enumerable: true,
  21508. configurable: true
  21509. });
  21510. Object.defineProperty(Light.prototype, "intensityMode", {
  21511. /**
  21512. * Gets the photometric scale used to interpret the intensity.
  21513. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21514. */
  21515. get: function () {
  21516. return this._intensityMode;
  21517. },
  21518. /**
  21519. * Sets the photometric scale used to interpret the intensity.
  21520. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21521. */
  21522. set: function (value) {
  21523. this._intensityMode = value;
  21524. this._computePhotometricScale();
  21525. },
  21526. enumerable: true,
  21527. configurable: true
  21528. });
  21529. ;
  21530. ;
  21531. Object.defineProperty(Light.prototype, "radius", {
  21532. /**
  21533. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21534. */
  21535. get: function () {
  21536. return this._radius;
  21537. },
  21538. /**
  21539. * sets the light radius used by PBR Materials to simulate soft area lights.
  21540. */
  21541. set: function (value) {
  21542. this._radius = value;
  21543. this._computePhotometricScale();
  21544. },
  21545. enumerable: true,
  21546. configurable: true
  21547. });
  21548. ;
  21549. ;
  21550. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21551. /**
  21552. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21553. * the current shadow generator.
  21554. */
  21555. get: function () {
  21556. return this._shadowEnabled;
  21557. },
  21558. /**
  21559. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21560. * the current shadow generator.
  21561. */
  21562. set: function (value) {
  21563. if (this._shadowEnabled === value) {
  21564. return;
  21565. }
  21566. this._shadowEnabled = value;
  21567. this._markMeshesAsLightDirty();
  21568. },
  21569. enumerable: true,
  21570. configurable: true
  21571. });
  21572. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21573. /**
  21574. * Gets the only meshes impacted by this light.
  21575. */
  21576. get: function () {
  21577. return this._includedOnlyMeshes;
  21578. },
  21579. /**
  21580. * Sets the only meshes impacted by this light.
  21581. */
  21582. set: function (value) {
  21583. this._includedOnlyMeshes = value;
  21584. this._hookArrayForIncludedOnly(value);
  21585. },
  21586. enumerable: true,
  21587. configurable: true
  21588. });
  21589. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21590. /**
  21591. * Gets the meshes not impacted by this light.
  21592. */
  21593. get: function () {
  21594. return this._excludedMeshes;
  21595. },
  21596. /**
  21597. * Sets the meshes not impacted by this light.
  21598. */
  21599. set: function (value) {
  21600. this._excludedMeshes = value;
  21601. this._hookArrayForExcluded(value);
  21602. },
  21603. enumerable: true,
  21604. configurable: true
  21605. });
  21606. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21607. /**
  21608. * Gets the layer id use to find what meshes are not impacted by the light.
  21609. * Inactive if 0
  21610. */
  21611. get: function () {
  21612. return this._excludeWithLayerMask;
  21613. },
  21614. /**
  21615. * Sets the layer id use to find what meshes are not impacted by the light.
  21616. * Inactive if 0
  21617. */
  21618. set: function (value) {
  21619. this._excludeWithLayerMask = value;
  21620. this._resyncMeshes();
  21621. },
  21622. enumerable: true,
  21623. configurable: true
  21624. });
  21625. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21626. /**
  21627. * Gets the layer id use to find what meshes are impacted by the light.
  21628. * Inactive if 0
  21629. */
  21630. get: function () {
  21631. return this._includeOnlyWithLayerMask;
  21632. },
  21633. /**
  21634. * Sets the layer id use to find what meshes are impacted by the light.
  21635. * Inactive if 0
  21636. */
  21637. set: function (value) {
  21638. this._includeOnlyWithLayerMask = value;
  21639. this._resyncMeshes();
  21640. },
  21641. enumerable: true,
  21642. configurable: true
  21643. });
  21644. Object.defineProperty(Light.prototype, "lightmapMode", {
  21645. /**
  21646. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21647. */
  21648. get: function () {
  21649. return this._lightmapMode;
  21650. },
  21651. /**
  21652. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21653. */
  21654. set: function (value) {
  21655. if (this._lightmapMode === value) {
  21656. return;
  21657. }
  21658. this._lightmapMode = value;
  21659. this._markMeshesAsLightDirty();
  21660. },
  21661. enumerable: true,
  21662. configurable: true
  21663. });
  21664. /**
  21665. * Returns the string "Light".
  21666. * @returns the class name
  21667. */
  21668. Light.prototype.getClassName = function () {
  21669. return "Light";
  21670. };
  21671. /**
  21672. * Converts the light information to a readable string for debug purpose.
  21673. * @param fullDetails Supports for multiple levels of logging within scene loading
  21674. * @returns the human readable light info
  21675. */
  21676. Light.prototype.toString = function (fullDetails) {
  21677. var ret = "Name: " + this.name;
  21678. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21679. if (this.animations) {
  21680. for (var i = 0; i < this.animations.length; i++) {
  21681. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21682. }
  21683. }
  21684. if (fullDetails) {
  21685. }
  21686. return ret;
  21687. };
  21688. /**
  21689. * Set the enabled state of this node.
  21690. * @param value - the new enabled state
  21691. */
  21692. Light.prototype.setEnabled = function (value) {
  21693. _super.prototype.setEnabled.call(this, value);
  21694. this._resyncMeshes();
  21695. };
  21696. /**
  21697. * Returns the Light associated shadow generator if any.
  21698. * @return the associated shadow generator.
  21699. */
  21700. Light.prototype.getShadowGenerator = function () {
  21701. return this._shadowGenerator;
  21702. };
  21703. /**
  21704. * Returns a Vector3, the absolute light position in the World.
  21705. * @returns the world space position of the light
  21706. */
  21707. Light.prototype.getAbsolutePosition = function () {
  21708. return BABYLON.Vector3.Zero();
  21709. };
  21710. /**
  21711. * Specifies if the light will affect the passed mesh.
  21712. * @param mesh The mesh to test against the light
  21713. * @return true the mesh is affected otherwise, false.
  21714. */
  21715. Light.prototype.canAffectMesh = function (mesh) {
  21716. if (!mesh) {
  21717. return true;
  21718. }
  21719. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21720. return false;
  21721. }
  21722. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21723. return false;
  21724. }
  21725. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21726. return false;
  21727. }
  21728. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21729. return false;
  21730. }
  21731. return true;
  21732. };
  21733. /**
  21734. * Sort function to order lights for rendering.
  21735. * @param a First Light object to compare to second.
  21736. * @param b Second Light object to compare first.
  21737. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21738. */
  21739. Light.CompareLightsPriority = function (a, b) {
  21740. //shadow-casting lights have priority over non-shadow-casting lights
  21741. //the renderPrioirty is a secondary sort criterion
  21742. if (a.shadowEnabled !== b.shadowEnabled) {
  21743. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21744. }
  21745. return b.renderPriority - a.renderPriority;
  21746. };
  21747. /**
  21748. * Releases resources associated with this node.
  21749. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21750. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21751. */
  21752. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21753. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21754. if (this._shadowGenerator) {
  21755. this._shadowGenerator.dispose();
  21756. this._shadowGenerator = null;
  21757. }
  21758. // Animations
  21759. this.getScene().stopAnimation(this);
  21760. // Remove from meshes
  21761. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21762. var mesh = _a[_i];
  21763. mesh._removeLightSource(this);
  21764. }
  21765. this._uniformBuffer.dispose();
  21766. // Remove from scene
  21767. this.getScene().removeLight(this);
  21768. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21769. };
  21770. /**
  21771. * Returns the light type ID (integer).
  21772. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21773. */
  21774. Light.prototype.getTypeID = function () {
  21775. return 0;
  21776. };
  21777. /**
  21778. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21779. * @returns the scaled intensity in intensity mode unit
  21780. */
  21781. Light.prototype.getScaledIntensity = function () {
  21782. return this._photometricScale * this.intensity;
  21783. };
  21784. /**
  21785. * Returns a new Light object, named "name", from the current one.
  21786. * @param name The name of the cloned light
  21787. * @returns the new created light
  21788. */
  21789. Light.prototype.clone = function (name) {
  21790. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21791. if (!constructor) {
  21792. return null;
  21793. }
  21794. return BABYLON.SerializationHelper.Clone(constructor, this);
  21795. };
  21796. /**
  21797. * Serializes the current light into a Serialization object.
  21798. * @returns the serialized object.
  21799. */
  21800. Light.prototype.serialize = function () {
  21801. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21802. // Type
  21803. serializationObject.type = this.getTypeID();
  21804. // Parent
  21805. if (this.parent) {
  21806. serializationObject.parentId = this.parent.id;
  21807. }
  21808. // Inclusion / exclusions
  21809. if (this.excludedMeshes.length > 0) {
  21810. serializationObject.excludedMeshesIds = [];
  21811. this.excludedMeshes.forEach(function (mesh) {
  21812. serializationObject.excludedMeshesIds.push(mesh.id);
  21813. });
  21814. }
  21815. if (this.includedOnlyMeshes.length > 0) {
  21816. serializationObject.includedOnlyMeshesIds = [];
  21817. this.includedOnlyMeshes.forEach(function (mesh) {
  21818. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21819. });
  21820. }
  21821. // Animations
  21822. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21823. serializationObject.ranges = this.serializeAnimationRanges();
  21824. return serializationObject;
  21825. };
  21826. /**
  21827. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21828. * This new light is named "name" and added to the passed scene.
  21829. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21830. * @param name The friendly name of the light
  21831. * @param scene The scene the new light will belong to
  21832. * @returns the constructor function
  21833. */
  21834. Light.GetConstructorFromName = function (type, name, scene) {
  21835. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21836. if (constructorFunc) {
  21837. return constructorFunc;
  21838. }
  21839. // Default to no light for none present once.
  21840. return null;
  21841. };
  21842. /**
  21843. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21844. * @param parsedLight The JSON representation of the light
  21845. * @param scene The scene to create the parsed light in
  21846. * @returns the created light after parsing
  21847. */
  21848. Light.Parse = function (parsedLight, scene) {
  21849. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21850. if (!constructor) {
  21851. return null;
  21852. }
  21853. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21854. // Inclusion / exclusions
  21855. if (parsedLight.excludedMeshesIds) {
  21856. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21857. }
  21858. if (parsedLight.includedOnlyMeshesIds) {
  21859. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21860. }
  21861. // Parent
  21862. if (parsedLight.parentId) {
  21863. light._waitingParentId = parsedLight.parentId;
  21864. }
  21865. // Animations
  21866. if (parsedLight.animations) {
  21867. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21868. var parsedAnimation = parsedLight.animations[animationIndex];
  21869. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21870. }
  21871. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21872. }
  21873. if (parsedLight.autoAnimate) {
  21874. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21875. }
  21876. return light;
  21877. };
  21878. Light.prototype._hookArrayForExcluded = function (array) {
  21879. var _this = this;
  21880. var oldPush = array.push;
  21881. array.push = function () {
  21882. var items = [];
  21883. for (var _i = 0; _i < arguments.length; _i++) {
  21884. items[_i] = arguments[_i];
  21885. }
  21886. var result = oldPush.apply(array, items);
  21887. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21888. var item = items_1[_a];
  21889. item._resyncLighSource(_this);
  21890. }
  21891. return result;
  21892. };
  21893. var oldSplice = array.splice;
  21894. array.splice = function (index, deleteCount) {
  21895. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21896. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21897. var item = deleted_1[_i];
  21898. item._resyncLighSource(_this);
  21899. }
  21900. return deleted;
  21901. };
  21902. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21903. var item = array_1[_i];
  21904. item._resyncLighSource(this);
  21905. }
  21906. };
  21907. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21908. var _this = this;
  21909. var oldPush = array.push;
  21910. array.push = function () {
  21911. var items = [];
  21912. for (var _i = 0; _i < arguments.length; _i++) {
  21913. items[_i] = arguments[_i];
  21914. }
  21915. var result = oldPush.apply(array, items);
  21916. _this._resyncMeshes();
  21917. return result;
  21918. };
  21919. var oldSplice = array.splice;
  21920. array.splice = function (index, deleteCount) {
  21921. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21922. _this._resyncMeshes();
  21923. return deleted;
  21924. };
  21925. this._resyncMeshes();
  21926. };
  21927. Light.prototype._resyncMeshes = function () {
  21928. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21929. var mesh = _a[_i];
  21930. mesh._resyncLighSource(this);
  21931. }
  21932. };
  21933. /**
  21934. * Forces the meshes to update their light related information in their rendering used effects
  21935. * @hidden Internal Use Only
  21936. */
  21937. Light.prototype._markMeshesAsLightDirty = function () {
  21938. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21939. var mesh = _a[_i];
  21940. if (mesh._lightSources.indexOf(this) !== -1) {
  21941. mesh._markSubMeshesAsLightDirty();
  21942. }
  21943. }
  21944. };
  21945. /**
  21946. * Recomputes the cached photometric scale if needed.
  21947. */
  21948. Light.prototype._computePhotometricScale = function () {
  21949. this._photometricScale = this._getPhotometricScale();
  21950. this.getScene().resetCachedMaterial();
  21951. };
  21952. /**
  21953. * Returns the Photometric Scale according to the light type and intensity mode.
  21954. */
  21955. Light.prototype._getPhotometricScale = function () {
  21956. var photometricScale = 0.0;
  21957. var lightTypeID = this.getTypeID();
  21958. //get photometric mode
  21959. var photometricMode = this.intensityMode;
  21960. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21961. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21962. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21963. }
  21964. else {
  21965. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21966. }
  21967. }
  21968. //compute photometric scale
  21969. switch (lightTypeID) {
  21970. case Light.LIGHTTYPEID_POINTLIGHT:
  21971. case Light.LIGHTTYPEID_SPOTLIGHT:
  21972. switch (photometricMode) {
  21973. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21974. photometricScale = 1.0 / (4.0 * Math.PI);
  21975. break;
  21976. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21977. photometricScale = 1.0;
  21978. break;
  21979. case Light.INTENSITYMODE_LUMINANCE:
  21980. photometricScale = this.radius * this.radius;
  21981. break;
  21982. }
  21983. break;
  21984. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21985. switch (photometricMode) {
  21986. case Light.INTENSITYMODE_ILLUMINANCE:
  21987. photometricScale = 1.0;
  21988. break;
  21989. case Light.INTENSITYMODE_LUMINANCE:
  21990. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21991. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21992. var apexAngleRadians = this.radius;
  21993. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21994. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21995. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21996. photometricScale = solidAngle;
  21997. break;
  21998. }
  21999. break;
  22000. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22001. // No fall off in hemisperic light.
  22002. photometricScale = 1.0;
  22003. break;
  22004. }
  22005. return photometricScale;
  22006. };
  22007. /**
  22008. * Reorder the light in the scene according to their defined priority.
  22009. * @hidden Internal Use Only
  22010. */
  22011. Light.prototype._reorderLightsInScene = function () {
  22012. var scene = this.getScene();
  22013. if (this._renderPriority != 0) {
  22014. scene.requireLightSorting = true;
  22015. }
  22016. this.getScene().sortLightsByPriority();
  22017. };
  22018. /**
  22019. * Falloff Default: light is falling off following the material specification:
  22020. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22021. */
  22022. Light.FALLOFF_DEFAULT = 0;
  22023. /**
  22024. * Falloff Physical: light is falling off following the inverse squared distance law.
  22025. */
  22026. Light.FALLOFF_PHYSICAL = 1;
  22027. /**
  22028. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22029. * to enhance interoperability with other engines.
  22030. */
  22031. Light.FALLOFF_GLTF = 2;
  22032. /**
  22033. * Falloff Standard: light is falling off like in the standard material
  22034. * to enhance interoperability with other materials.
  22035. */
  22036. Light.FALLOFF_STANDARD = 3;
  22037. //lightmapMode Consts
  22038. /**
  22039. * If every light affecting the material is in this lightmapMode,
  22040. * material.lightmapTexture adds or multiplies
  22041. * (depends on material.useLightmapAsShadowmap)
  22042. * after every other light calculations.
  22043. */
  22044. Light.LIGHTMAP_DEFAULT = 0;
  22045. /**
  22046. * material.lightmapTexture as only diffuse lighting from this light
  22047. * adds only specular lighting from this light
  22048. * adds dynamic shadows
  22049. */
  22050. Light.LIGHTMAP_SPECULAR = 1;
  22051. /**
  22052. * material.lightmapTexture as only lighting
  22053. * no light calculation from this light
  22054. * only adds dynamic shadows from this light
  22055. */
  22056. Light.LIGHTMAP_SHADOWSONLY = 2;
  22057. // Intensity Mode Consts
  22058. /**
  22059. * Each light type uses the default quantity according to its type:
  22060. * point/spot lights use luminous intensity
  22061. * directional lights use illuminance
  22062. */
  22063. Light.INTENSITYMODE_AUTOMATIC = 0;
  22064. /**
  22065. * lumen (lm)
  22066. */
  22067. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22068. /**
  22069. * candela (lm/sr)
  22070. */
  22071. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22072. /**
  22073. * lux (lm/m^2)
  22074. */
  22075. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22076. /**
  22077. * nit (cd/m^2)
  22078. */
  22079. Light.INTENSITYMODE_LUMINANCE = 4;
  22080. // Light types ids const.
  22081. /**
  22082. * Light type const id of the point light.
  22083. */
  22084. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22085. /**
  22086. * Light type const id of the directional light.
  22087. */
  22088. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22089. /**
  22090. * Light type const id of the spot light.
  22091. */
  22092. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22093. /**
  22094. * Light type const id of the hemispheric light.
  22095. */
  22096. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22097. __decorate([
  22098. BABYLON.serializeAsColor3()
  22099. ], Light.prototype, "diffuse", void 0);
  22100. __decorate([
  22101. BABYLON.serializeAsColor3()
  22102. ], Light.prototype, "specular", void 0);
  22103. __decorate([
  22104. BABYLON.serialize()
  22105. ], Light.prototype, "falloffType", void 0);
  22106. __decorate([
  22107. BABYLON.serialize()
  22108. ], Light.prototype, "intensity", void 0);
  22109. __decorate([
  22110. BABYLON.serialize()
  22111. ], Light.prototype, "range", null);
  22112. __decorate([
  22113. BABYLON.serialize()
  22114. ], Light.prototype, "intensityMode", null);
  22115. __decorate([
  22116. BABYLON.serialize()
  22117. ], Light.prototype, "radius", null);
  22118. __decorate([
  22119. BABYLON.serialize()
  22120. ], Light.prototype, "_renderPriority", void 0);
  22121. __decorate([
  22122. BABYLON.expandToProperty("_reorderLightsInScene")
  22123. ], Light.prototype, "renderPriority", void 0);
  22124. __decorate([
  22125. BABYLON.serialize("shadowEnabled")
  22126. ], Light.prototype, "_shadowEnabled", void 0);
  22127. __decorate([
  22128. BABYLON.serialize("excludeWithLayerMask")
  22129. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22130. __decorate([
  22131. BABYLON.serialize("includeOnlyWithLayerMask")
  22132. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22133. __decorate([
  22134. BABYLON.serialize("lightmapMode")
  22135. ], Light.prototype, "_lightmapMode", void 0);
  22136. return Light;
  22137. }(BABYLON.Node));
  22138. BABYLON.Light = Light;
  22139. })(BABYLON || (BABYLON = {}));
  22140. //# sourceMappingURL=babylon.light.js.map
  22141. var BABYLON;
  22142. (function (BABYLON) {
  22143. var Camera = /** @class */ (function (_super) {
  22144. __extends(Camera, _super);
  22145. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22146. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22147. var _this = _super.call(this, name, scene) || this;
  22148. /**
  22149. * The vector the camera should consider as up.
  22150. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22151. */
  22152. _this.upVector = BABYLON.Vector3.Up();
  22153. _this.orthoLeft = null;
  22154. _this.orthoRight = null;
  22155. _this.orthoBottom = null;
  22156. _this.orthoTop = null;
  22157. /**
  22158. * FOV is set in Radians. (default is 0.8)
  22159. */
  22160. _this.fov = 0.8;
  22161. _this.minZ = 1;
  22162. _this.maxZ = 10000.0;
  22163. _this.inertia = 0.9;
  22164. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22165. _this.isIntermediate = false;
  22166. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22167. /**
  22168. * Restricts the camera to viewing objects with the same layerMask.
  22169. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22170. */
  22171. _this.layerMask = 0x0FFFFFFF;
  22172. /**
  22173. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22174. */
  22175. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22176. // Camera rig members
  22177. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22178. /** @hidden */
  22179. _this._rigCameras = new Array();
  22180. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22181. /** @hidden */
  22182. _this._skipRendering = false;
  22183. _this.customRenderTargets = new Array();
  22184. // Observables
  22185. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22186. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22187. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22188. _this.onRestoreStateObservable = new BABYLON.Observable();
  22189. // Cache
  22190. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22191. _this._projectionMatrix = new BABYLON.Matrix();
  22192. _this._doNotComputeProjectionMatrix = false;
  22193. _this._postProcesses = new Array();
  22194. _this._transformMatrix = BABYLON.Matrix.Zero();
  22195. _this._activeMeshes = new BABYLON.SmartArray(256);
  22196. _this._globalPosition = BABYLON.Vector3.Zero();
  22197. _this._refreshFrustumPlanes = true;
  22198. _this.getScene().addCamera(_this);
  22199. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22200. _this.getScene().activeCamera = _this;
  22201. }
  22202. _this.position = position;
  22203. return _this;
  22204. }
  22205. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22206. get: function () {
  22207. return Camera._PERSPECTIVE_CAMERA;
  22208. },
  22209. enumerable: true,
  22210. configurable: true
  22211. });
  22212. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22213. get: function () {
  22214. return Camera._ORTHOGRAPHIC_CAMERA;
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22220. /**
  22221. * This is the default FOV mode for perspective cameras.
  22222. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22223. *
  22224. */
  22225. get: function () {
  22226. return Camera._FOVMODE_VERTICAL_FIXED;
  22227. },
  22228. enumerable: true,
  22229. configurable: true
  22230. });
  22231. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22232. /**
  22233. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22234. *
  22235. */
  22236. get: function () {
  22237. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22238. },
  22239. enumerable: true,
  22240. configurable: true
  22241. });
  22242. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22243. get: function () {
  22244. return Camera._RIG_MODE_NONE;
  22245. },
  22246. enumerable: true,
  22247. configurable: true
  22248. });
  22249. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22250. get: function () {
  22251. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22252. },
  22253. enumerable: true,
  22254. configurable: true
  22255. });
  22256. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22257. get: function () {
  22258. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22259. },
  22260. enumerable: true,
  22261. configurable: true
  22262. });
  22263. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22264. get: function () {
  22265. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22266. },
  22267. enumerable: true,
  22268. configurable: true
  22269. });
  22270. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22271. get: function () {
  22272. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22273. },
  22274. enumerable: true,
  22275. configurable: true
  22276. });
  22277. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22278. get: function () {
  22279. return Camera._RIG_MODE_VR;
  22280. },
  22281. enumerable: true,
  22282. configurable: true
  22283. });
  22284. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22285. get: function () {
  22286. return Camera._RIG_MODE_WEBVR;
  22287. },
  22288. enumerable: true,
  22289. configurable: true
  22290. });
  22291. /**
  22292. * Store current camera state (fov, position, etc..)
  22293. */
  22294. Camera.prototype.storeState = function () {
  22295. this._stateStored = true;
  22296. this._storedFov = this.fov;
  22297. return this;
  22298. };
  22299. /**
  22300. * Restores the camera state values if it has been stored. You must call storeState() first
  22301. */
  22302. Camera.prototype._restoreStateValues = function () {
  22303. if (!this._stateStored) {
  22304. return false;
  22305. }
  22306. this.fov = this._storedFov;
  22307. return true;
  22308. };
  22309. /**
  22310. * Restored camera state. You must call storeState() first
  22311. */
  22312. Camera.prototype.restoreState = function () {
  22313. if (this._restoreStateValues()) {
  22314. this.onRestoreStateObservable.notifyObservers(this);
  22315. return true;
  22316. }
  22317. return false;
  22318. };
  22319. Camera.prototype.getClassName = function () {
  22320. return "Camera";
  22321. };
  22322. /**
  22323. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22324. */
  22325. Camera.prototype.toString = function (fullDetails) {
  22326. var ret = "Name: " + this.name;
  22327. ret += ", type: " + this.getClassName();
  22328. if (this.animations) {
  22329. for (var i = 0; i < this.animations.length; i++) {
  22330. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22331. }
  22332. }
  22333. if (fullDetails) {
  22334. }
  22335. return ret;
  22336. };
  22337. Object.defineProperty(Camera.prototype, "globalPosition", {
  22338. get: function () {
  22339. return this._globalPosition;
  22340. },
  22341. enumerable: true,
  22342. configurable: true
  22343. });
  22344. Camera.prototype.getActiveMeshes = function () {
  22345. return this._activeMeshes;
  22346. };
  22347. Camera.prototype.isActiveMesh = function (mesh) {
  22348. return (this._activeMeshes.indexOf(mesh) !== -1);
  22349. };
  22350. /**
  22351. * Is this camera ready to be used/rendered
  22352. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22353. * @return true if the camera is ready
  22354. */
  22355. Camera.prototype.isReady = function (completeCheck) {
  22356. if (completeCheck === void 0) { completeCheck = false; }
  22357. if (completeCheck) {
  22358. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22359. var pp = _a[_i];
  22360. if (pp && !pp.isReady()) {
  22361. return false;
  22362. }
  22363. }
  22364. }
  22365. return _super.prototype.isReady.call(this, completeCheck);
  22366. };
  22367. //Cache
  22368. /** @hidden */
  22369. Camera.prototype._initCache = function () {
  22370. _super.prototype._initCache.call(this);
  22371. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22372. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22373. this._cache.mode = undefined;
  22374. this._cache.minZ = undefined;
  22375. this._cache.maxZ = undefined;
  22376. this._cache.fov = undefined;
  22377. this._cache.fovMode = undefined;
  22378. this._cache.aspectRatio = undefined;
  22379. this._cache.orthoLeft = undefined;
  22380. this._cache.orthoRight = undefined;
  22381. this._cache.orthoBottom = undefined;
  22382. this._cache.orthoTop = undefined;
  22383. this._cache.renderWidth = undefined;
  22384. this._cache.renderHeight = undefined;
  22385. };
  22386. /** @hidden */
  22387. Camera.prototype._updateCache = function (ignoreParentClass) {
  22388. if (!ignoreParentClass) {
  22389. _super.prototype._updateCache.call(this);
  22390. }
  22391. this._cache.position.copyFrom(this.position);
  22392. this._cache.upVector.copyFrom(this.upVector);
  22393. };
  22394. // Synchronized
  22395. /** @hidden */
  22396. Camera.prototype._isSynchronized = function () {
  22397. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22398. };
  22399. /** @hidden */
  22400. Camera.prototype._isSynchronizedViewMatrix = function () {
  22401. if (!_super.prototype._isSynchronized.call(this))
  22402. return false;
  22403. return this._cache.position.equals(this.position)
  22404. && this._cache.upVector.equals(this.upVector)
  22405. && this.isSynchronizedWithParent();
  22406. };
  22407. /** @hidden */
  22408. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22409. var check = this._cache.mode === this.mode
  22410. && this._cache.minZ === this.minZ
  22411. && this._cache.maxZ === this.maxZ;
  22412. if (!check) {
  22413. return false;
  22414. }
  22415. var engine = this.getEngine();
  22416. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22417. check = this._cache.fov === this.fov
  22418. && this._cache.fovMode === this.fovMode
  22419. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22420. }
  22421. else {
  22422. check = this._cache.orthoLeft === this.orthoLeft
  22423. && this._cache.orthoRight === this.orthoRight
  22424. && this._cache.orthoBottom === this.orthoBottom
  22425. && this._cache.orthoTop === this.orthoTop
  22426. && this._cache.renderWidth === engine.getRenderWidth()
  22427. && this._cache.renderHeight === engine.getRenderHeight();
  22428. }
  22429. return check;
  22430. };
  22431. // Controls
  22432. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22433. };
  22434. Camera.prototype.detachControl = function (element) {
  22435. };
  22436. Camera.prototype.update = function () {
  22437. this._checkInputs();
  22438. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22439. this._updateRigCameras();
  22440. }
  22441. };
  22442. /** @hidden */
  22443. Camera.prototype._checkInputs = function () {
  22444. this.onAfterCheckInputsObservable.notifyObservers(this);
  22445. };
  22446. Object.defineProperty(Camera.prototype, "rigCameras", {
  22447. get: function () {
  22448. return this._rigCameras;
  22449. },
  22450. enumerable: true,
  22451. configurable: true
  22452. });
  22453. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22454. get: function () {
  22455. return this._rigPostProcess;
  22456. },
  22457. enumerable: true,
  22458. configurable: true
  22459. });
  22460. /**
  22461. * Internal, gets the first post proces.
  22462. * @returns the first post process to be run on this camera.
  22463. */
  22464. Camera.prototype._getFirstPostProcess = function () {
  22465. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22466. if (this._postProcesses[ppIndex] !== null) {
  22467. return this._postProcesses[ppIndex];
  22468. }
  22469. }
  22470. return null;
  22471. };
  22472. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22473. // invalidate framebuffer
  22474. var firstPostProcess = this._getFirstPostProcess();
  22475. if (firstPostProcess) {
  22476. firstPostProcess.markTextureDirty();
  22477. }
  22478. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22479. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22480. var cam = this._rigCameras[i];
  22481. var rigPostProcess = cam._rigPostProcess;
  22482. // for VR rig, there does not have to be a post process
  22483. if (rigPostProcess) {
  22484. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22485. if (isPass) {
  22486. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22487. cam.isIntermediate = this._postProcesses.length === 0;
  22488. }
  22489. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22490. rigPostProcess.markTextureDirty();
  22491. }
  22492. else {
  22493. cam._postProcesses = this._postProcesses.slice(0);
  22494. }
  22495. }
  22496. };
  22497. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22498. if (insertAt === void 0) { insertAt = null; }
  22499. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22500. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22501. return 0;
  22502. }
  22503. if (insertAt == null || insertAt < 0) {
  22504. this._postProcesses.push(postProcess);
  22505. }
  22506. else if (this._postProcesses[insertAt] === null) {
  22507. this._postProcesses[insertAt] = postProcess;
  22508. }
  22509. else {
  22510. this._postProcesses.splice(insertAt, 0, postProcess);
  22511. }
  22512. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22513. return this._postProcesses.indexOf(postProcess);
  22514. };
  22515. Camera.prototype.detachPostProcess = function (postProcess) {
  22516. var idx = this._postProcesses.indexOf(postProcess);
  22517. if (idx !== -1) {
  22518. this._postProcesses[idx] = null;
  22519. }
  22520. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22521. };
  22522. Camera.prototype.getWorldMatrix = function () {
  22523. if (this._isSynchronizedViewMatrix()) {
  22524. return this._worldMatrix;
  22525. }
  22526. // Getting the the view matrix will also compute the world matrix.
  22527. this.getViewMatrix();
  22528. return this._worldMatrix;
  22529. };
  22530. /** @hidden */
  22531. Camera.prototype._getViewMatrix = function () {
  22532. return BABYLON.Matrix.Identity();
  22533. };
  22534. Camera.prototype.getViewMatrix = function (force) {
  22535. if (!force && this._isSynchronizedViewMatrix()) {
  22536. return this._computedViewMatrix;
  22537. }
  22538. this.updateCache();
  22539. this._computedViewMatrix = this._getViewMatrix();
  22540. this._currentRenderId = this.getScene().getRenderId();
  22541. this._childRenderId = this._currentRenderId;
  22542. this._refreshFrustumPlanes = true;
  22543. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22544. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22545. }
  22546. this.onViewMatrixChangedObservable.notifyObservers(this);
  22547. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22548. return this._computedViewMatrix;
  22549. };
  22550. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22551. this._doNotComputeProjectionMatrix = true;
  22552. if (projection !== undefined) {
  22553. this._projectionMatrix = projection;
  22554. }
  22555. };
  22556. ;
  22557. Camera.prototype.unfreezeProjectionMatrix = function () {
  22558. this._doNotComputeProjectionMatrix = false;
  22559. };
  22560. ;
  22561. Camera.prototype.getProjectionMatrix = function (force) {
  22562. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22563. return this._projectionMatrix;
  22564. }
  22565. // Cache
  22566. this._cache.mode = this.mode;
  22567. this._cache.minZ = this.minZ;
  22568. this._cache.maxZ = this.maxZ;
  22569. // Matrix
  22570. this._refreshFrustumPlanes = true;
  22571. var engine = this.getEngine();
  22572. var scene = this.getScene();
  22573. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22574. this._cache.fov = this.fov;
  22575. this._cache.fovMode = this.fovMode;
  22576. this._cache.aspectRatio = engine.getAspectRatio(this);
  22577. if (this.minZ <= 0) {
  22578. this.minZ = 0.1;
  22579. }
  22580. if (scene.useRightHandedSystem) {
  22581. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22582. }
  22583. else {
  22584. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22585. }
  22586. }
  22587. else {
  22588. var halfWidth = engine.getRenderWidth() / 2.0;
  22589. var halfHeight = engine.getRenderHeight() / 2.0;
  22590. if (scene.useRightHandedSystem) {
  22591. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22592. }
  22593. else {
  22594. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22595. }
  22596. this._cache.orthoLeft = this.orthoLeft;
  22597. this._cache.orthoRight = this.orthoRight;
  22598. this._cache.orthoBottom = this.orthoBottom;
  22599. this._cache.orthoTop = this.orthoTop;
  22600. this._cache.renderWidth = engine.getRenderWidth();
  22601. this._cache.renderHeight = engine.getRenderHeight();
  22602. }
  22603. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22604. return this._projectionMatrix;
  22605. };
  22606. /**
  22607. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22608. * @returns a Matrix
  22609. */
  22610. Camera.prototype.getTransformationMatrix = function () {
  22611. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22612. return this._transformMatrix;
  22613. };
  22614. Camera.prototype.updateFrustumPlanes = function () {
  22615. if (!this._refreshFrustumPlanes) {
  22616. return;
  22617. }
  22618. this.getTransformationMatrix();
  22619. if (!this._frustumPlanes) {
  22620. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22621. }
  22622. else {
  22623. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22624. }
  22625. this._refreshFrustumPlanes = false;
  22626. };
  22627. Camera.prototype.isInFrustum = function (target) {
  22628. this.updateFrustumPlanes();
  22629. return target.isInFrustum(this._frustumPlanes);
  22630. };
  22631. Camera.prototype.isCompletelyInFrustum = function (target) {
  22632. this.updateFrustumPlanes();
  22633. return target.isCompletelyInFrustum(this._frustumPlanes);
  22634. };
  22635. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22636. if (length === void 0) { length = 100; }
  22637. if (!transform) {
  22638. transform = this.getWorldMatrix();
  22639. }
  22640. if (!origin) {
  22641. origin = this.position;
  22642. }
  22643. var forward = new BABYLON.Vector3(0, 0, 1);
  22644. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22645. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22646. return new BABYLON.Ray(origin, direction, length);
  22647. };
  22648. /**
  22649. * Releases resources associated with this node.
  22650. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22651. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22652. */
  22653. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22654. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22655. // Observables
  22656. this.onViewMatrixChangedObservable.clear();
  22657. this.onProjectionMatrixChangedObservable.clear();
  22658. this.onAfterCheckInputsObservable.clear();
  22659. this.onRestoreStateObservable.clear();
  22660. // Inputs
  22661. if (this.inputs) {
  22662. this.inputs.clear();
  22663. }
  22664. // Animations
  22665. this.getScene().stopAnimation(this);
  22666. // Remove from scene
  22667. this.getScene().removeCamera(this);
  22668. while (this._rigCameras.length > 0) {
  22669. var camera = this._rigCameras.pop();
  22670. if (camera) {
  22671. camera.dispose();
  22672. }
  22673. }
  22674. // Postprocesses
  22675. if (this._rigPostProcess) {
  22676. this._rigPostProcess.dispose(this);
  22677. this._rigPostProcess = null;
  22678. this._postProcesses = [];
  22679. }
  22680. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22681. this._rigPostProcess = null;
  22682. this._postProcesses = [];
  22683. }
  22684. else {
  22685. var i = this._postProcesses.length;
  22686. while (--i >= 0) {
  22687. var postProcess = this._postProcesses[i];
  22688. if (postProcess) {
  22689. postProcess.dispose(this);
  22690. }
  22691. }
  22692. }
  22693. // Render targets
  22694. var i = this.customRenderTargets.length;
  22695. while (--i >= 0) {
  22696. this.customRenderTargets[i].dispose();
  22697. }
  22698. this.customRenderTargets = [];
  22699. // Active Meshes
  22700. this._activeMeshes.dispose();
  22701. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22702. };
  22703. Object.defineProperty(Camera.prototype, "leftCamera", {
  22704. // ---- Camera rigs section ----
  22705. get: function () {
  22706. if (this._rigCameras.length < 1) {
  22707. return null;
  22708. }
  22709. return this._rigCameras[0];
  22710. },
  22711. enumerable: true,
  22712. configurable: true
  22713. });
  22714. Object.defineProperty(Camera.prototype, "rightCamera", {
  22715. get: function () {
  22716. if (this._rigCameras.length < 2) {
  22717. return null;
  22718. }
  22719. return this._rigCameras[1];
  22720. },
  22721. enumerable: true,
  22722. configurable: true
  22723. });
  22724. Camera.prototype.getLeftTarget = function () {
  22725. if (this._rigCameras.length < 1) {
  22726. return null;
  22727. }
  22728. return this._rigCameras[0].getTarget();
  22729. };
  22730. Camera.prototype.getRightTarget = function () {
  22731. if (this._rigCameras.length < 2) {
  22732. return null;
  22733. }
  22734. return this._rigCameras[1].getTarget();
  22735. };
  22736. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22737. if (this.cameraRigMode === mode) {
  22738. return;
  22739. }
  22740. while (this._rigCameras.length > 0) {
  22741. var camera = this._rigCameras.pop();
  22742. if (camera) {
  22743. camera.dispose();
  22744. }
  22745. }
  22746. this.cameraRigMode = mode;
  22747. this._cameraRigParams = {};
  22748. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22749. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22750. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22751. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22752. // create the rig cameras, unless none
  22753. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22754. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22755. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22756. if (leftCamera && rightCamera) {
  22757. this._rigCameras.push(leftCamera);
  22758. this._rigCameras.push(rightCamera);
  22759. }
  22760. }
  22761. switch (this.cameraRigMode) {
  22762. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22763. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22764. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22765. break;
  22766. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22767. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22768. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22769. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22770. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22771. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22772. break;
  22773. case Camera.RIG_MODE_VR:
  22774. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22775. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22776. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22777. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22778. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22779. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22780. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22781. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22782. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22783. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22784. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22785. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22786. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22787. if (metrics.compensateDistortion) {
  22788. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22789. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22790. }
  22791. break;
  22792. case Camera.RIG_MODE_WEBVR:
  22793. if (rigParams.vrDisplay) {
  22794. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22795. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22796. //Left eye
  22797. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22798. this._rigCameras[0].setCameraRigParameter("left", true);
  22799. //leaving this for future reference
  22800. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22801. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22802. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22803. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22804. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22805. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22806. this._rigCameras[0].parent = this;
  22807. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22808. //Right eye
  22809. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22810. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22811. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22812. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22813. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22814. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22815. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22816. this._rigCameras[1].parent = this;
  22817. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22818. if (Camera.UseAlternateWebVRRendering) {
  22819. this._rigCameras[1]._skipRendering = true;
  22820. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22821. }
  22822. }
  22823. break;
  22824. }
  22825. this._cascadePostProcessesToRigCams();
  22826. this.update();
  22827. };
  22828. Camera.prototype._getVRProjectionMatrix = function () {
  22829. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22830. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22831. return this._projectionMatrix;
  22832. };
  22833. Camera.prototype._updateCameraRotationMatrix = function () {
  22834. //Here for WebVR
  22835. };
  22836. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22837. //Here for WebVR
  22838. };
  22839. /**
  22840. * This function MUST be overwritten by the different WebVR cameras available.
  22841. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22842. */
  22843. Camera.prototype._getWebVRProjectionMatrix = function () {
  22844. return BABYLON.Matrix.Identity();
  22845. };
  22846. /**
  22847. * This function MUST be overwritten by the different WebVR cameras available.
  22848. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22849. */
  22850. Camera.prototype._getWebVRViewMatrix = function () {
  22851. return BABYLON.Matrix.Identity();
  22852. };
  22853. Camera.prototype.setCameraRigParameter = function (name, value) {
  22854. if (!this._cameraRigParams) {
  22855. this._cameraRigParams = {};
  22856. }
  22857. this._cameraRigParams[name] = value;
  22858. //provisionnally:
  22859. if (name === "interaxialDistance") {
  22860. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22861. }
  22862. };
  22863. /**
  22864. * needs to be overridden by children so sub has required properties to be copied
  22865. */
  22866. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22867. return null;
  22868. };
  22869. /**
  22870. * May need to be overridden by children
  22871. * @hidden
  22872. */
  22873. Camera.prototype._updateRigCameras = function () {
  22874. for (var i = 0; i < this._rigCameras.length; i++) {
  22875. this._rigCameras[i].minZ = this.minZ;
  22876. this._rigCameras[i].maxZ = this.maxZ;
  22877. this._rigCameras[i].fov = this.fov;
  22878. }
  22879. // only update viewport when ANAGLYPH
  22880. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22881. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22882. }
  22883. };
  22884. /** @hidden */
  22885. Camera.prototype._setupInputs = function () {
  22886. };
  22887. Camera.prototype.serialize = function () {
  22888. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22889. // Type
  22890. serializationObject.type = this.getClassName();
  22891. // Parent
  22892. if (this.parent) {
  22893. serializationObject.parentId = this.parent.id;
  22894. }
  22895. if (this.inputs) {
  22896. this.inputs.serialize(serializationObject);
  22897. }
  22898. // Animations
  22899. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22900. serializationObject.ranges = this.serializeAnimationRanges();
  22901. return serializationObject;
  22902. };
  22903. Camera.prototype.clone = function (name) {
  22904. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22905. };
  22906. Camera.prototype.getDirection = function (localAxis) {
  22907. var result = BABYLON.Vector3.Zero();
  22908. this.getDirectionToRef(localAxis, result);
  22909. return result;
  22910. };
  22911. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22912. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22913. };
  22914. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22915. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22916. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22917. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22918. interaxial_distance: interaxial_distance,
  22919. isStereoscopicSideBySide: isStereoscopicSideBySide
  22920. });
  22921. if (constructorFunc) {
  22922. return constructorFunc;
  22923. }
  22924. // Default to universal camera
  22925. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22926. };
  22927. Camera.prototype.computeWorldMatrix = function () {
  22928. return this.getWorldMatrix();
  22929. };
  22930. Camera.Parse = function (parsedCamera, scene) {
  22931. var type = parsedCamera.type;
  22932. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22933. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22934. // Parent
  22935. if (parsedCamera.parentId) {
  22936. camera._waitingParentId = parsedCamera.parentId;
  22937. }
  22938. //If camera has an input manager, let it parse inputs settings
  22939. if (camera.inputs) {
  22940. camera.inputs.parse(parsedCamera);
  22941. camera._setupInputs();
  22942. }
  22943. if (camera.setPosition) { // need to force position
  22944. camera.position.copyFromFloats(0, 0, 0);
  22945. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22946. }
  22947. // Target
  22948. if (parsedCamera.target) {
  22949. if (camera.setTarget) {
  22950. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22951. }
  22952. }
  22953. // Apply 3d rig, when found
  22954. if (parsedCamera.cameraRigMode) {
  22955. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22956. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22957. }
  22958. // Animations
  22959. if (parsedCamera.animations) {
  22960. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22961. var parsedAnimation = parsedCamera.animations[animationIndex];
  22962. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22963. }
  22964. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22965. }
  22966. if (parsedCamera.autoAnimate) {
  22967. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22968. }
  22969. return camera;
  22970. };
  22971. // Statics
  22972. Camera._PERSPECTIVE_CAMERA = 0;
  22973. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22974. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22975. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22976. Camera._RIG_MODE_NONE = 0;
  22977. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22978. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22979. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22980. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22981. Camera._RIG_MODE_VR = 20;
  22982. Camera._RIG_MODE_WEBVR = 21;
  22983. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22984. Camera.UseAlternateWebVRRendering = false;
  22985. __decorate([
  22986. BABYLON.serializeAsVector3()
  22987. ], Camera.prototype, "position", void 0);
  22988. __decorate([
  22989. BABYLON.serializeAsVector3()
  22990. ], Camera.prototype, "upVector", void 0);
  22991. __decorate([
  22992. BABYLON.serialize()
  22993. ], Camera.prototype, "orthoLeft", void 0);
  22994. __decorate([
  22995. BABYLON.serialize()
  22996. ], Camera.prototype, "orthoRight", void 0);
  22997. __decorate([
  22998. BABYLON.serialize()
  22999. ], Camera.prototype, "orthoBottom", void 0);
  23000. __decorate([
  23001. BABYLON.serialize()
  23002. ], Camera.prototype, "orthoTop", void 0);
  23003. __decorate([
  23004. BABYLON.serialize()
  23005. ], Camera.prototype, "fov", void 0);
  23006. __decorate([
  23007. BABYLON.serialize()
  23008. ], Camera.prototype, "minZ", void 0);
  23009. __decorate([
  23010. BABYLON.serialize()
  23011. ], Camera.prototype, "maxZ", void 0);
  23012. __decorate([
  23013. BABYLON.serialize()
  23014. ], Camera.prototype, "inertia", void 0);
  23015. __decorate([
  23016. BABYLON.serialize()
  23017. ], Camera.prototype, "mode", void 0);
  23018. __decorate([
  23019. BABYLON.serialize()
  23020. ], Camera.prototype, "layerMask", void 0);
  23021. __decorate([
  23022. BABYLON.serialize()
  23023. ], Camera.prototype, "fovMode", void 0);
  23024. __decorate([
  23025. BABYLON.serialize()
  23026. ], Camera.prototype, "cameraRigMode", void 0);
  23027. __decorate([
  23028. BABYLON.serialize()
  23029. ], Camera.prototype, "interaxialDistance", void 0);
  23030. __decorate([
  23031. BABYLON.serialize()
  23032. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23033. return Camera;
  23034. }(BABYLON.Node));
  23035. BABYLON.Camera = Camera;
  23036. })(BABYLON || (BABYLON = {}));
  23037. //# sourceMappingURL=babylon.camera.js.map
  23038. var BABYLON;
  23039. (function (BABYLON) {
  23040. var RenderingManager = /** @class */ (function () {
  23041. function RenderingManager(scene) {
  23042. /**
  23043. * @hidden
  23044. */
  23045. this._useSceneAutoClearSetup = false;
  23046. this._renderingGroups = new Array();
  23047. this._autoClearDepthStencil = {};
  23048. this._customOpaqueSortCompareFn = {};
  23049. this._customAlphaTestSortCompareFn = {};
  23050. this._customTransparentSortCompareFn = {};
  23051. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23052. this._scene = scene;
  23053. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23054. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23055. }
  23056. }
  23057. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23058. if (depth === void 0) { depth = true; }
  23059. if (stencil === void 0) { stencil = true; }
  23060. if (this._depthStencilBufferAlreadyCleaned) {
  23061. return;
  23062. }
  23063. this._scene.getEngine().clear(null, false, depth, stencil);
  23064. this._depthStencilBufferAlreadyCleaned = true;
  23065. };
  23066. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23067. // Update the observable context (not null as it only goes away on dispose)
  23068. var info = this._renderingGroupInfo;
  23069. info.scene = this._scene;
  23070. info.camera = this._scene.activeCamera;
  23071. // Dispatch sprites
  23072. if (this._scene.spriteManagers && renderSprites) {
  23073. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23074. var manager = this._scene.spriteManagers[index];
  23075. this.dispatchSprites(manager);
  23076. }
  23077. }
  23078. // Render
  23079. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23080. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23081. var renderingGroup = this._renderingGroups[index];
  23082. if (!renderingGroup)
  23083. continue;
  23084. var renderingGroupMask = Math.pow(2, index);
  23085. info.renderingGroupId = index;
  23086. // Before Observable
  23087. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23088. // Clear depth/stencil if needed
  23089. if (RenderingManager.AUTOCLEAR) {
  23090. var autoClear = this._useSceneAutoClearSetup ?
  23091. this._scene.getAutoClearDepthStencilSetup(index) :
  23092. this._autoClearDepthStencil[index];
  23093. if (autoClear && autoClear.autoClear) {
  23094. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23095. }
  23096. }
  23097. // Render
  23098. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23099. var step = _a[_i];
  23100. step.action(index);
  23101. }
  23102. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23103. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23104. var step = _c[_b];
  23105. step.action(index);
  23106. }
  23107. // After Observable
  23108. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23109. }
  23110. };
  23111. RenderingManager.prototype.reset = function () {
  23112. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23113. var renderingGroup = this._renderingGroups[index];
  23114. if (renderingGroup) {
  23115. renderingGroup.prepare();
  23116. }
  23117. }
  23118. };
  23119. RenderingManager.prototype.dispose = function () {
  23120. this.freeRenderingGroups();
  23121. this._renderingGroups.length = 0;
  23122. this._renderingGroupInfo = null;
  23123. };
  23124. /**
  23125. * Clear the info related to rendering groups preventing retention points during dispose.
  23126. */
  23127. RenderingManager.prototype.freeRenderingGroups = function () {
  23128. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23129. var renderingGroup = this._renderingGroups[index];
  23130. if (renderingGroup) {
  23131. renderingGroup.dispose();
  23132. }
  23133. }
  23134. };
  23135. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23136. if (this._renderingGroups[renderingGroupId] === undefined) {
  23137. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23138. }
  23139. };
  23140. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23141. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23142. this._prepareRenderingGroup(renderingGroupId);
  23143. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23144. };
  23145. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23146. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23147. this._prepareRenderingGroup(renderingGroupId);
  23148. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23149. };
  23150. /**
  23151. * @param subMesh The submesh to dispatch
  23152. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23153. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23154. */
  23155. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23156. if (mesh === undefined) {
  23157. mesh = subMesh.getMesh();
  23158. }
  23159. var renderingGroupId = mesh.renderingGroupId || 0;
  23160. this._prepareRenderingGroup(renderingGroupId);
  23161. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23162. };
  23163. /**
  23164. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23165. * This allowed control for front to back rendering or reversly depending of the special needs.
  23166. *
  23167. * @param renderingGroupId The rendering group id corresponding to its index
  23168. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23169. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23170. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23171. */
  23172. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23173. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23174. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23175. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23176. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23177. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23178. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23179. if (this._renderingGroups[renderingGroupId]) {
  23180. var group = this._renderingGroups[renderingGroupId];
  23181. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23182. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23183. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23184. }
  23185. };
  23186. /**
  23187. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23188. *
  23189. * @param renderingGroupId The rendering group id corresponding to its index
  23190. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23191. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23192. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23193. */
  23194. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23195. if (depth === void 0) { depth = true; }
  23196. if (stencil === void 0) { stencil = true; }
  23197. this._autoClearDepthStencil[renderingGroupId] = {
  23198. autoClear: autoClearDepthStencil,
  23199. depth: depth,
  23200. stencil: stencil
  23201. };
  23202. };
  23203. /**
  23204. * Gets the current auto clear configuration for one rendering group of the rendering
  23205. * manager.
  23206. * @param index the rendering group index to get the information for
  23207. * @returns The auto clear setup for the requested rendering group
  23208. */
  23209. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23210. return this._autoClearDepthStencil[index];
  23211. };
  23212. /**
  23213. * The max id used for rendering groups (not included)
  23214. */
  23215. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23216. /**
  23217. * The min id used for rendering groups (included)
  23218. */
  23219. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23220. /**
  23221. * Used to globally prevent autoclearing scenes.
  23222. */
  23223. RenderingManager.AUTOCLEAR = true;
  23224. return RenderingManager;
  23225. }());
  23226. BABYLON.RenderingManager = RenderingManager;
  23227. })(BABYLON || (BABYLON = {}));
  23228. //# sourceMappingURL=babylon.renderingManager.js.map
  23229. var BABYLON;
  23230. (function (BABYLON) {
  23231. var RenderingGroup = /** @class */ (function () {
  23232. /**
  23233. * Creates a new rendering group.
  23234. * @param index The rendering group index
  23235. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23236. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23237. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23238. */
  23239. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23240. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23241. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23242. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23243. this.index = index;
  23244. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23245. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23246. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23247. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23248. this._particleSystems = new BABYLON.SmartArray(256);
  23249. this._spriteManagers = new BABYLON.SmartArray(256);
  23250. this._edgesRenderers = new BABYLON.SmartArray(16);
  23251. this._scene = scene;
  23252. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23253. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23254. this.transparentSortCompareFn = transparentSortCompareFn;
  23255. }
  23256. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23257. /**
  23258. * Set the opaque sort comparison function.
  23259. * If null the sub meshes will be render in the order they were created
  23260. */
  23261. set: function (value) {
  23262. this._opaqueSortCompareFn = value;
  23263. if (value) {
  23264. this._renderOpaque = this.renderOpaqueSorted;
  23265. }
  23266. else {
  23267. this._renderOpaque = RenderingGroup.renderUnsorted;
  23268. }
  23269. },
  23270. enumerable: true,
  23271. configurable: true
  23272. });
  23273. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23274. /**
  23275. * Set the alpha test sort comparison function.
  23276. * If null the sub meshes will be render in the order they were created
  23277. */
  23278. set: function (value) {
  23279. this._alphaTestSortCompareFn = value;
  23280. if (value) {
  23281. this._renderAlphaTest = this.renderAlphaTestSorted;
  23282. }
  23283. else {
  23284. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23285. }
  23286. },
  23287. enumerable: true,
  23288. configurable: true
  23289. });
  23290. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23291. /**
  23292. * Set the transparent sort comparison function.
  23293. * If null the sub meshes will be render in the order they were created
  23294. */
  23295. set: function (value) {
  23296. if (value) {
  23297. this._transparentSortCompareFn = value;
  23298. }
  23299. else {
  23300. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23301. }
  23302. this._renderTransparent = this.renderTransparentSorted;
  23303. },
  23304. enumerable: true,
  23305. configurable: true
  23306. });
  23307. /**
  23308. * Render all the sub meshes contained in the group.
  23309. * @param customRenderFunction Used to override the default render behaviour of the group.
  23310. * @returns true if rendered some submeshes.
  23311. */
  23312. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23313. if (customRenderFunction) {
  23314. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23315. return;
  23316. }
  23317. var engine = this._scene.getEngine();
  23318. // Depth only
  23319. if (this._depthOnlySubMeshes.length !== 0) {
  23320. engine.setColorWrite(false);
  23321. this._renderAlphaTest(this._depthOnlySubMeshes);
  23322. engine.setColorWrite(true);
  23323. }
  23324. // Opaque
  23325. if (this._opaqueSubMeshes.length !== 0) {
  23326. this._renderOpaque(this._opaqueSubMeshes);
  23327. }
  23328. // Alpha test
  23329. if (this._alphaTestSubMeshes.length !== 0) {
  23330. this._renderAlphaTest(this._alphaTestSubMeshes);
  23331. }
  23332. var stencilState = engine.getStencilBuffer();
  23333. engine.setStencilBuffer(false);
  23334. // Sprites
  23335. if (renderSprites) {
  23336. this._renderSprites();
  23337. }
  23338. // Particles
  23339. if (renderParticles) {
  23340. this._renderParticles(activeMeshes);
  23341. }
  23342. if (this.onBeforeTransparentRendering) {
  23343. this.onBeforeTransparentRendering();
  23344. }
  23345. // Transparent
  23346. if (this._transparentSubMeshes.length !== 0) {
  23347. this._renderTransparent(this._transparentSubMeshes);
  23348. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23349. }
  23350. // Set back stencil to false in case it changes before the edge renderer.
  23351. engine.setStencilBuffer(false);
  23352. // Edges
  23353. if (this._edgesRenderers.length) {
  23354. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23355. this._edgesRenderers.data[edgesRendererIndex].render();
  23356. }
  23357. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23358. }
  23359. // Restore Stencil state.
  23360. engine.setStencilBuffer(stencilState);
  23361. };
  23362. /**
  23363. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23364. * @param subMeshes The submeshes to render
  23365. */
  23366. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23367. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23368. };
  23369. /**
  23370. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23371. * @param subMeshes The submeshes to render
  23372. */
  23373. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23374. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23375. };
  23376. /**
  23377. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23378. * @param subMeshes The submeshes to render
  23379. */
  23380. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23381. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23382. };
  23383. /**
  23384. * Renders the submeshes in a specified order.
  23385. * @param subMeshes The submeshes to sort before render
  23386. * @param sortCompareFn The comparison function use to sort
  23387. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23388. * @param transparent Specifies to activate blending if true
  23389. */
  23390. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23391. var subIndex = 0;
  23392. var subMesh;
  23393. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23394. for (; subIndex < subMeshes.length; subIndex++) {
  23395. subMesh = subMeshes.data[subIndex];
  23396. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23397. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23398. }
  23399. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23400. if (sortCompareFn) {
  23401. sortedArray.sort(sortCompareFn);
  23402. }
  23403. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23404. subMesh = sortedArray[subIndex];
  23405. if (transparent) {
  23406. var material = subMesh.getMaterial();
  23407. if (material && material.needDepthPrePass) {
  23408. var engine = material.getScene().getEngine();
  23409. engine.setColorWrite(false);
  23410. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23411. subMesh.render(false);
  23412. engine.setColorWrite(true);
  23413. }
  23414. }
  23415. subMesh.render(transparent);
  23416. }
  23417. };
  23418. /**
  23419. * Renders the submeshes in the order they were dispatched (no sort applied).
  23420. * @param subMeshes The submeshes to render
  23421. */
  23422. RenderingGroup.renderUnsorted = function (subMeshes) {
  23423. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23424. var submesh = subMeshes.data[subIndex];
  23425. submesh.render(false);
  23426. }
  23427. };
  23428. /**
  23429. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23430. * are rendered back to front if in the same alpha index.
  23431. *
  23432. * @param a The first submesh
  23433. * @param b The second submesh
  23434. * @returns The result of the comparison
  23435. */
  23436. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23437. // Alpha index first
  23438. if (a._alphaIndex > b._alphaIndex) {
  23439. return 1;
  23440. }
  23441. if (a._alphaIndex < b._alphaIndex) {
  23442. return -1;
  23443. }
  23444. // Then distance to camera
  23445. return RenderingGroup.backToFrontSortCompare(a, b);
  23446. };
  23447. /**
  23448. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23449. * are rendered back to front.
  23450. *
  23451. * @param a The first submesh
  23452. * @param b The second submesh
  23453. * @returns The result of the comparison
  23454. */
  23455. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23456. // Then distance to camera
  23457. if (a._distanceToCamera < b._distanceToCamera) {
  23458. return 1;
  23459. }
  23460. if (a._distanceToCamera > b._distanceToCamera) {
  23461. return -1;
  23462. }
  23463. return 0;
  23464. };
  23465. /**
  23466. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23467. * are rendered front to back (prevent overdraw).
  23468. *
  23469. * @param a The first submesh
  23470. * @param b The second submesh
  23471. * @returns The result of the comparison
  23472. */
  23473. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23474. // Then distance to camera
  23475. if (a._distanceToCamera < b._distanceToCamera) {
  23476. return -1;
  23477. }
  23478. if (a._distanceToCamera > b._distanceToCamera) {
  23479. return 1;
  23480. }
  23481. return 0;
  23482. };
  23483. /**
  23484. * Resets the different lists of submeshes to prepare a new frame.
  23485. */
  23486. RenderingGroup.prototype.prepare = function () {
  23487. this._opaqueSubMeshes.reset();
  23488. this._transparentSubMeshes.reset();
  23489. this._alphaTestSubMeshes.reset();
  23490. this._depthOnlySubMeshes.reset();
  23491. this._particleSystems.reset();
  23492. this._spriteManagers.reset();
  23493. this._edgesRenderers.reset();
  23494. };
  23495. RenderingGroup.prototype.dispose = function () {
  23496. this._opaqueSubMeshes.dispose();
  23497. this._transparentSubMeshes.dispose();
  23498. this._alphaTestSubMeshes.dispose();
  23499. this._depthOnlySubMeshes.dispose();
  23500. this._particleSystems.dispose();
  23501. this._spriteManagers.dispose();
  23502. this._edgesRenderers.dispose();
  23503. };
  23504. /**
  23505. * Inserts the submesh in its correct queue depending on its material.
  23506. * @param subMesh The submesh to dispatch
  23507. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23508. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23509. */
  23510. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23511. // Get mesh and materials if not provided
  23512. if (mesh === undefined) {
  23513. mesh = subMesh.getMesh();
  23514. }
  23515. if (material === undefined) {
  23516. material = subMesh.getMaterial();
  23517. }
  23518. if (material === null || material === undefined) {
  23519. return;
  23520. }
  23521. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23522. this._transparentSubMeshes.push(subMesh);
  23523. }
  23524. else if (material.needAlphaTesting()) { // Alpha test
  23525. if (material.needDepthPrePass) {
  23526. this._depthOnlySubMeshes.push(subMesh);
  23527. }
  23528. this._alphaTestSubMeshes.push(subMesh);
  23529. }
  23530. else {
  23531. if (material.needDepthPrePass) {
  23532. this._depthOnlySubMeshes.push(subMesh);
  23533. }
  23534. this._opaqueSubMeshes.push(subMesh); // Opaque
  23535. }
  23536. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23537. this._edgesRenderers.push(mesh._edgesRenderer);
  23538. }
  23539. };
  23540. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23541. this._spriteManagers.push(spriteManager);
  23542. };
  23543. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23544. this._particleSystems.push(particleSystem);
  23545. };
  23546. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23547. if (this._particleSystems.length === 0) {
  23548. return;
  23549. }
  23550. // Particles
  23551. var activeCamera = this._scene.activeCamera;
  23552. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23553. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23554. var particleSystem = this._particleSystems.data[particleIndex];
  23555. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23556. continue;
  23557. }
  23558. var emitter = particleSystem.emitter;
  23559. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23560. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23561. }
  23562. }
  23563. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23564. };
  23565. RenderingGroup.prototype._renderSprites = function () {
  23566. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23567. return;
  23568. }
  23569. // Sprites
  23570. var activeCamera = this._scene.activeCamera;
  23571. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23572. for (var id = 0; id < this._spriteManagers.length; id++) {
  23573. var spriteManager = this._spriteManagers.data[id];
  23574. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23575. spriteManager.render();
  23576. }
  23577. }
  23578. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23579. };
  23580. return RenderingGroup;
  23581. }());
  23582. BABYLON.RenderingGroup = RenderingGroup;
  23583. })(BABYLON || (BABYLON = {}));
  23584. //# sourceMappingURL=babylon.renderingGroup.js.map
  23585. var BABYLON;
  23586. (function (BABYLON) {
  23587. /**
  23588. * Groups all the scene component constants in one place to ease maintenance.
  23589. * @hidden
  23590. */
  23591. var SceneComponentConstants = /** @class */ (function () {
  23592. function SceneComponentConstants() {
  23593. }
  23594. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23595. SceneComponentConstants.NAME_LAYER = "Layer";
  23596. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23597. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23598. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23599. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23600. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23601. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23602. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23603. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23604. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23605. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23606. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23607. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23608. SceneComponentConstants.NAME_OCTREE = "Octree";
  23609. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23610. SceneComponentConstants.NAME_AUDIO = "Audio";
  23611. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23612. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23613. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23614. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23615. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23616. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23617. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23618. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23619. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23620. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23621. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23622. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23623. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23624. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23625. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23626. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23627. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23628. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23629. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  23630. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23631. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23632. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23633. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23634. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23635. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23636. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23637. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23638. return SceneComponentConstants;
  23639. }());
  23640. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23641. /**
  23642. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23643. * @hidden
  23644. */
  23645. var Stage = /** @class */ (function (_super) {
  23646. __extends(Stage, _super);
  23647. /**
  23648. * Hide ctor from the rest of the world.
  23649. * @param items The items to add.
  23650. */
  23651. function Stage(items) {
  23652. return _super.apply(this, items) || this;
  23653. }
  23654. /**
  23655. * Creates a new Stage.
  23656. * @returns A new instance of a Stage
  23657. */
  23658. Stage.Create = function () {
  23659. return Object.create(Stage.prototype);
  23660. };
  23661. /**
  23662. * Registers a step in an ordered way in the targeted stage.
  23663. * @param index Defines the position to register the step in
  23664. * @param component Defines the component attached to the step
  23665. * @param action Defines the action to launch during the step
  23666. */
  23667. Stage.prototype.registerStep = function (index, component, action) {
  23668. var i = 0;
  23669. var maxIndex = Number.MAX_VALUE;
  23670. for (; i < this.length && i < maxIndex; i++) {
  23671. var step = this[i];
  23672. maxIndex = step.index;
  23673. }
  23674. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23675. };
  23676. /**
  23677. * Clears all the steps from the stage.
  23678. */
  23679. Stage.prototype.clear = function () {
  23680. this.length = 0;
  23681. };
  23682. return Stage;
  23683. }(Array));
  23684. BABYLON.Stage = Stage;
  23685. })(BABYLON || (BABYLON = {}));
  23686. //# sourceMappingURL=babylon.sceneComponent.js.map
  23687. var BABYLON;
  23688. (function (BABYLON) {
  23689. /**
  23690. * Base class of the scene acting as a container for the different elements composing a scene.
  23691. * This class is dynamically extended by the different components of the scene increasing
  23692. * flexibility and reducing coupling
  23693. */
  23694. var AbstractScene = /** @class */ (function () {
  23695. function AbstractScene() {
  23696. /**
  23697. * Gets the list of root nodes (ie. nodes with no parent)
  23698. */
  23699. this.rootNodes = new Array();
  23700. /** All of the cameras added to this scene
  23701. * @see http://doc.babylonjs.com/babylon101/cameras
  23702. */
  23703. this.cameras = new Array();
  23704. /**
  23705. * All of the lights added to this scene
  23706. * @see http://doc.babylonjs.com/babylon101/lights
  23707. */
  23708. this.lights = new Array();
  23709. /**
  23710. * All of the (abstract) meshes added to this scene
  23711. */
  23712. this.meshes = new Array();
  23713. /**
  23714. * The list of skeletons added to the scene
  23715. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23716. */
  23717. this.skeletons = new Array();
  23718. /**
  23719. * All of the particle systems added to this scene
  23720. * @see http://doc.babylonjs.com/babylon101/particles
  23721. */
  23722. this.particleSystems = new Array();
  23723. /**
  23724. * Gets a list of Animations associated with the scene
  23725. */
  23726. this.animations = [];
  23727. /**
  23728. * All of the animation groups added to this scene
  23729. * @see http://doc.babylonjs.com/how_to/group
  23730. */
  23731. this.animationGroups = new Array();
  23732. /**
  23733. * All of the multi-materials added to this scene
  23734. * @see http://doc.babylonjs.com/how_to/multi_materials
  23735. */
  23736. this.multiMaterials = new Array();
  23737. /**
  23738. * All of the materials added to this scene
  23739. * @see http://doc.babylonjs.com/babylon101/materials
  23740. */
  23741. this.materials = new Array();
  23742. /**
  23743. * The list of morph target managers added to the scene
  23744. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23745. */
  23746. this.morphTargetManagers = new Array();
  23747. /**
  23748. * The list of geometries used in the scene.
  23749. */
  23750. this.geometries = new Array();
  23751. /**
  23752. * All of the tranform nodes added to this scene
  23753. * @see http://doc.babylonjs.com/how_to/transformnode
  23754. */
  23755. this.transformNodes = new Array();
  23756. /**
  23757. * ActionManagers available on the scene.
  23758. */
  23759. this.actionManagers = new Array();
  23760. /**
  23761. * Textures to keep.
  23762. */
  23763. this.textures = new Array();
  23764. }
  23765. /**
  23766. * Adds a parser in the list of available ones
  23767. * @param name Defines the name of the parser
  23768. * @param parser Defines the parser to add
  23769. */
  23770. AbstractScene.AddParser = function (name, parser) {
  23771. this._BabylonFileParsers[name] = parser;
  23772. };
  23773. /**
  23774. * Gets a general parser from the list of avaialble ones
  23775. * @param name Defines the name of the parser
  23776. * @returns the requested parser or null
  23777. */
  23778. AbstractScene.GetParser = function (name) {
  23779. if (this._BabylonFileParsers[name]) {
  23780. return this._BabylonFileParsers[name];
  23781. }
  23782. return null;
  23783. };
  23784. /**
  23785. * Adds n individual parser in the list of available ones
  23786. * @param name Defines the name of the parser
  23787. * @param parser Defines the parser to add
  23788. */
  23789. AbstractScene.AddIndividualParser = function (name, parser) {
  23790. this._IndividualBabylonFileParsers[name] = parser;
  23791. };
  23792. /**
  23793. * Gets an individual parser from the list of avaialble ones
  23794. * @param name Defines the name of the parser
  23795. * @returns the requested parser or null
  23796. */
  23797. AbstractScene.GetIndividualParser = function (name) {
  23798. if (this._IndividualBabylonFileParsers[name]) {
  23799. return this._IndividualBabylonFileParsers[name];
  23800. }
  23801. return null;
  23802. };
  23803. /**
  23804. * Parser json data and populate both a scene and its associated container object
  23805. * @param jsonData Defines the data to parse
  23806. * @param scene Defines the scene to parse the data for
  23807. * @param container Defines the container attached to the parsing sequence
  23808. * @param rootUrl Defines the root url of the data
  23809. */
  23810. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23811. for (var parserName in this._BabylonFileParsers) {
  23812. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23813. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23814. }
  23815. }
  23816. };
  23817. /**
  23818. * Stores the list of available parsers in the application.
  23819. */
  23820. AbstractScene._BabylonFileParsers = {};
  23821. /**
  23822. * Stores the list of available individual parsers in the application.
  23823. */
  23824. AbstractScene._IndividualBabylonFileParsers = {};
  23825. return AbstractScene;
  23826. }());
  23827. BABYLON.AbstractScene = AbstractScene;
  23828. })(BABYLON || (BABYLON = {}));
  23829. //# sourceMappingURL=babylon.abstractScene.js.map
  23830. var BABYLON;
  23831. (function (BABYLON) {
  23832. /** @hidden */
  23833. var ClickInfo = /** @class */ (function () {
  23834. function ClickInfo() {
  23835. this._singleClick = false;
  23836. this._doubleClick = false;
  23837. this._hasSwiped = false;
  23838. this._ignore = false;
  23839. }
  23840. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23841. get: function () {
  23842. return this._singleClick;
  23843. },
  23844. set: function (b) {
  23845. this._singleClick = b;
  23846. },
  23847. enumerable: true,
  23848. configurable: true
  23849. });
  23850. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23851. get: function () {
  23852. return this._doubleClick;
  23853. },
  23854. set: function (b) {
  23855. this._doubleClick = b;
  23856. },
  23857. enumerable: true,
  23858. configurable: true
  23859. });
  23860. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23861. get: function () {
  23862. return this._hasSwiped;
  23863. },
  23864. set: function (b) {
  23865. this._hasSwiped = b;
  23866. },
  23867. enumerable: true,
  23868. configurable: true
  23869. });
  23870. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23871. get: function () {
  23872. return this._ignore;
  23873. },
  23874. set: function (b) {
  23875. this._ignore = b;
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. return ClickInfo;
  23881. }());
  23882. /**
  23883. * This class is used by the onRenderingGroupObservable
  23884. */
  23885. var RenderingGroupInfo = /** @class */ (function () {
  23886. function RenderingGroupInfo() {
  23887. }
  23888. return RenderingGroupInfo;
  23889. }());
  23890. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23891. /**
  23892. * Represents a scene to be rendered by the engine.
  23893. * @see http://doc.babylonjs.com/features/scene
  23894. */
  23895. var Scene = /** @class */ (function (_super) {
  23896. __extends(Scene, _super);
  23897. /**
  23898. * Creates a new Scene
  23899. * @param engine defines the engine to use to render this scene
  23900. */
  23901. function Scene(engine) {
  23902. var _this = _super.call(this) || this;
  23903. // Members
  23904. /**
  23905. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23906. */
  23907. _this.autoClear = true;
  23908. /**
  23909. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23910. */
  23911. _this.autoClearDepthAndStencil = true;
  23912. /**
  23913. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23914. */
  23915. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23916. /**
  23917. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23918. */
  23919. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23920. _this._forceWireframe = false;
  23921. _this._forcePointsCloud = false;
  23922. /**
  23923. * Gets or sets a boolean indicating if animations are enabled
  23924. */
  23925. _this.animationsEnabled = true;
  23926. _this._animationPropertiesOverride = null;
  23927. /**
  23928. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23929. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23930. */
  23931. _this.useConstantAnimationDeltaTime = false;
  23932. /**
  23933. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23934. * Please note that it requires to run a ray cast through the scene on every frame
  23935. */
  23936. _this.constantlyUpdateMeshUnderPointer = false;
  23937. /**
  23938. * Defines the HTML cursor to use when hovering over interactive elements
  23939. */
  23940. _this.hoverCursor = "pointer";
  23941. /**
  23942. * Defines the HTML default cursor to use (empty by default)
  23943. */
  23944. _this.defaultCursor = "";
  23945. /**
  23946. * This is used to call preventDefault() on pointer down
  23947. * in order to block unwanted artifacts like system double clicks
  23948. */
  23949. _this.preventDefaultOnPointerDown = true;
  23950. // Metadata
  23951. /**
  23952. * Gets or sets user defined metadata
  23953. */
  23954. _this.metadata = null;
  23955. /**
  23956. * Use this array to add regular expressions used to disable offline support for specific urls
  23957. */
  23958. _this.disableOfflineSupportExceptionRules = new Array();
  23959. /**
  23960. * An event triggered when the scene is disposed.
  23961. */
  23962. _this.onDisposeObservable = new BABYLON.Observable();
  23963. _this._onDisposeObserver = null;
  23964. /**
  23965. * An event triggered before rendering the scene (right after animations and physics)
  23966. */
  23967. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23968. _this._onBeforeRenderObserver = null;
  23969. /**
  23970. * An event triggered after rendering the scene
  23971. */
  23972. _this.onAfterRenderObservable = new BABYLON.Observable();
  23973. _this._onAfterRenderObserver = null;
  23974. /**
  23975. * An event triggered before animating the scene
  23976. */
  23977. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23978. /**
  23979. * An event triggered after animations processing
  23980. */
  23981. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23982. /**
  23983. * An event triggered before draw calls are ready to be sent
  23984. */
  23985. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23986. /**
  23987. * An event triggered after draw calls have been sent
  23988. */
  23989. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23990. /**
  23991. * An event triggered when the scene is ready
  23992. */
  23993. _this.onReadyObservable = new BABYLON.Observable();
  23994. /**
  23995. * An event triggered before rendering a camera
  23996. */
  23997. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23998. _this._onBeforeCameraRenderObserver = null;
  23999. /**
  24000. * An event triggered after rendering a camera
  24001. */
  24002. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24003. _this._onAfterCameraRenderObserver = null;
  24004. /**
  24005. * An event triggered when active meshes evaluation is about to start
  24006. */
  24007. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24008. /**
  24009. * An event triggered when active meshes evaluation is done
  24010. */
  24011. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24012. /**
  24013. * An event triggered when particles rendering is about to start
  24014. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24015. */
  24016. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24017. /**
  24018. * An event triggered when particles rendering is done
  24019. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24020. */
  24021. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24022. /**
  24023. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24024. */
  24025. _this.onDataLoadedObservable = new BABYLON.Observable();
  24026. /**
  24027. * An event triggered when a camera is created
  24028. */
  24029. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24030. /**
  24031. * An event triggered when a camera is removed
  24032. */
  24033. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24034. /**
  24035. * An event triggered when a light is created
  24036. */
  24037. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24038. /**
  24039. * An event triggered when a light is removed
  24040. */
  24041. _this.onLightRemovedObservable = new BABYLON.Observable();
  24042. /**
  24043. * An event triggered when a geometry is created
  24044. */
  24045. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24046. /**
  24047. * An event triggered when a geometry is removed
  24048. */
  24049. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24050. /**
  24051. * An event triggered when a transform node is created
  24052. */
  24053. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24054. /**
  24055. * An event triggered when a transform node is removed
  24056. */
  24057. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24058. /**
  24059. * An event triggered when a mesh is created
  24060. */
  24061. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24062. /**
  24063. * An event triggered when a mesh is removed
  24064. */
  24065. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24066. /**
  24067. * An event triggered when render targets are about to be rendered
  24068. * Can happen multiple times per frame.
  24069. */
  24070. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24071. /**
  24072. * An event triggered when render targets were rendered.
  24073. * Can happen multiple times per frame.
  24074. */
  24075. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24076. /**
  24077. * An event triggered before calculating deterministic simulation step
  24078. */
  24079. _this.onBeforeStepObservable = new BABYLON.Observable();
  24080. /**
  24081. * An event triggered after calculating deterministic simulation step
  24082. */
  24083. _this.onAfterStepObservable = new BABYLON.Observable();
  24084. /**
  24085. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24086. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24087. * 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)
  24088. */
  24089. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24090. /**
  24091. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24092. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24093. * 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)
  24094. */
  24095. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24096. /**
  24097. * This Observable will when a mesh has been imported into the scene.
  24098. */
  24099. _this.onMeshImportedObservable = new BABYLON.Observable();
  24100. // Animations
  24101. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24102. /**
  24103. * 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).
  24104. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24105. */
  24106. _this.onPrePointerObservable = new BABYLON.Observable();
  24107. /**
  24108. * Observable event triggered each time an input event is received from the rendering canvas
  24109. */
  24110. _this.onPointerObservable = new BABYLON.Observable();
  24111. _this._meshPickProceed = false;
  24112. _this._currentPickResult = null;
  24113. _this._previousPickResult = null;
  24114. _this._totalPointersPressed = 0;
  24115. _this._doubleClickOccured = false;
  24116. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24117. _this.cameraToUseForPointers = null;
  24118. _this._pointerX = 0;
  24119. _this._pointerY = 0;
  24120. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24121. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24122. _this._startingPointerTime = 0;
  24123. _this._previousStartingPointerTime = 0;
  24124. _this._pointerCaptures = {};
  24125. // Deterministic lockstep
  24126. _this._timeAccumulator = 0;
  24127. _this._currentStepId = 0;
  24128. _this._currentInternalStep = 0;
  24129. // Keyboard
  24130. /**
  24131. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24132. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24133. */
  24134. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24135. /**
  24136. * Observable event triggered each time an keyboard event is received from the hosting window
  24137. */
  24138. _this.onKeyboardObservable = new BABYLON.Observable();
  24139. // Coordinates system
  24140. _this._useRightHandedSystem = false;
  24141. // Fog
  24142. _this._fogEnabled = true;
  24143. _this._fogMode = Scene.FOGMODE_NONE;
  24144. /**
  24145. * Gets or sets the fog color to use
  24146. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24147. */
  24148. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24149. /**
  24150. * Gets or sets the fog density to use
  24151. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24152. */
  24153. _this.fogDensity = 0.1;
  24154. /**
  24155. * Gets or sets the fog start distance to use
  24156. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24157. */
  24158. _this.fogStart = 0;
  24159. /**
  24160. * Gets or sets the fog end distance to use
  24161. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24162. */
  24163. _this.fogEnd = 1000.0;
  24164. // Lights
  24165. _this._shadowsEnabled = true;
  24166. _this._lightsEnabled = true;
  24167. /** All of the active cameras added to this scene. */
  24168. _this.activeCameras = new Array();
  24169. // Textures
  24170. _this._texturesEnabled = true;
  24171. // Particles
  24172. /**
  24173. * Gets or sets a boolean indicating if particles are enabled on this scene
  24174. */
  24175. _this.particlesEnabled = true;
  24176. // Sprites
  24177. /**
  24178. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24179. */
  24180. _this.spritesEnabled = true;
  24181. // Skeletons
  24182. _this._skeletonsEnabled = true;
  24183. // Lens flares
  24184. /**
  24185. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24186. */
  24187. _this.lensFlaresEnabled = true;
  24188. // Collisions
  24189. /**
  24190. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24191. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24192. */
  24193. _this.collisionsEnabled = true;
  24194. /**
  24195. * Defines the gravity applied to this scene (used only for collisions)
  24196. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24197. */
  24198. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24199. // Postprocesses
  24200. /**
  24201. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24202. */
  24203. _this.postProcessesEnabled = true;
  24204. /**
  24205. * The list of postprocesses added to the scene
  24206. */
  24207. _this.postProcesses = new Array();
  24208. // Customs render targets
  24209. /**
  24210. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24211. */
  24212. _this.renderTargetsEnabled = true;
  24213. /**
  24214. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24215. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24216. */
  24217. _this.dumpNextRenderTargets = false;
  24218. /**
  24219. * The list of user defined render targets added to the scene
  24220. */
  24221. _this.customRenderTargets = new Array();
  24222. /**
  24223. * Gets the list of meshes imported to the scene through SceneLoader
  24224. */
  24225. _this.importedMeshesFiles = new Array();
  24226. // Probes
  24227. /**
  24228. * Gets or sets a boolean indicating if probes are enabled on this scene
  24229. */
  24230. _this.probesEnabled = true;
  24231. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24232. // Procedural textures
  24233. /**
  24234. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24235. */
  24236. _this.proceduralTexturesEnabled = true;
  24237. // Performance counters
  24238. _this._totalVertices = new BABYLON.PerfCounter();
  24239. /** @hidden */
  24240. _this._activeIndices = new BABYLON.PerfCounter();
  24241. /** @hidden */
  24242. _this._activeParticles = new BABYLON.PerfCounter();
  24243. /** @hidden */
  24244. _this._activeBones = new BABYLON.PerfCounter();
  24245. _this._animationTime = 0;
  24246. /**
  24247. * Gets or sets a general scale for animation speed
  24248. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24249. */
  24250. _this.animationTimeScale = 1;
  24251. _this._renderId = 0;
  24252. _this._frameId = 0;
  24253. _this._executeWhenReadyTimeoutId = -1;
  24254. _this._intermediateRendering = false;
  24255. _this._viewUpdateFlag = -1;
  24256. _this._projectionUpdateFlag = -1;
  24257. _this._alternateViewUpdateFlag = -1;
  24258. _this._alternateProjectionUpdateFlag = -1;
  24259. /** @hidden */
  24260. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24261. _this._activeRequests = new Array();
  24262. _this._pendingData = new Array();
  24263. _this._isDisposed = false;
  24264. /**
  24265. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24266. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24267. */
  24268. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24269. _this._activeMeshes = new BABYLON.SmartArray(256);
  24270. _this._processedMaterials = new BABYLON.SmartArray(256);
  24271. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24272. /** @hidden */
  24273. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24274. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24275. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24276. /** @hidden */
  24277. _this._activeAnimatables = new Array();
  24278. _this._transformMatrix = BABYLON.Matrix.Zero();
  24279. _this._useAlternateCameraConfiguration = false;
  24280. _this._alternateRendering = false;
  24281. /**
  24282. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24283. * This is useful if there are more lights that the maximum simulteanous authorized
  24284. */
  24285. _this.requireLightSorting = false;
  24286. /**
  24287. * @hidden
  24288. * Backing store of defined scene components.
  24289. */
  24290. _this._components = [];
  24291. /**
  24292. * @hidden
  24293. * Backing store of defined scene components.
  24294. */
  24295. _this._serializableComponents = [];
  24296. /**
  24297. * List of components to register on the next registration step.
  24298. */
  24299. _this._transientComponents = [];
  24300. /**
  24301. * @hidden
  24302. * Defines the actions happening before camera updates.
  24303. */
  24304. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24305. /**
  24306. * @hidden
  24307. * Defines the actions happening before clear the canvas.
  24308. */
  24309. _this._beforeClearStage = BABYLON.Stage.Create();
  24310. /**
  24311. * @hidden
  24312. * Defines the actions when collecting render targets for the frame.
  24313. */
  24314. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24315. /**
  24316. * @hidden
  24317. * Defines the actions happening for one camera in the frame.
  24318. */
  24319. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24320. /**
  24321. * @hidden
  24322. * Defines the actions happening during the per mesh ready checks.
  24323. */
  24324. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24325. /**
  24326. * @hidden
  24327. * Defines the actions happening before evaluate active mesh checks.
  24328. */
  24329. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24330. /**
  24331. * @hidden
  24332. * Defines the actions happening during the evaluate sub mesh checks.
  24333. */
  24334. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24335. /**
  24336. * @hidden
  24337. * Defines the actions happening during the active mesh stage.
  24338. */
  24339. _this._activeMeshStage = BABYLON.Stage.Create();
  24340. /**
  24341. * @hidden
  24342. * Defines the actions happening during the per camera render target step.
  24343. */
  24344. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24345. /**
  24346. * @hidden
  24347. * Defines the actions happening just before the active camera is drawing.
  24348. */
  24349. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24350. /**
  24351. * @hidden
  24352. * Defines the actions happening just before a rendering group is drawing.
  24353. */
  24354. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24355. /**
  24356. * @hidden
  24357. * Defines the actions happening just before a mesh is drawing.
  24358. */
  24359. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24360. /**
  24361. * @hidden
  24362. * Defines the actions happening just after a mesh has been drawn.
  24363. */
  24364. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24365. /**
  24366. * @hidden
  24367. * Defines the actions happening just after a rendering group has been drawn.
  24368. */
  24369. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24370. /**
  24371. * @hidden
  24372. * Defines the actions happening just after the active camera has been drawn.
  24373. */
  24374. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24375. /**
  24376. * @hidden
  24377. * Defines the actions happening just after rendering all cameras and computing intersections.
  24378. */
  24379. _this._afterRenderStage = BABYLON.Stage.Create();
  24380. /**
  24381. * @hidden
  24382. * Defines the actions happening when a pointer move event happens.
  24383. */
  24384. _this._pointerMoveStage = BABYLON.Stage.Create();
  24385. /**
  24386. * @hidden
  24387. * Defines the actions happening when a pointer down event happens.
  24388. */
  24389. _this._pointerDownStage = BABYLON.Stage.Create();
  24390. /**
  24391. * @hidden
  24392. * Defines the actions happening when a pointer up event happens.
  24393. */
  24394. _this._pointerUpStage = BABYLON.Stage.Create();
  24395. _this._defaultMeshCandidates = {
  24396. data: [],
  24397. length: 0
  24398. };
  24399. _this._defaultSubMeshCandidates = {
  24400. data: [],
  24401. length: 0
  24402. };
  24403. _this._activeMeshesFrozen = false;
  24404. /** @hidden */
  24405. _this._allowPostProcessClearColor = true;
  24406. /**
  24407. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24408. */
  24409. _this.getDeterministicFrameTime = function () {
  24410. return 1000.0 / 60.0; // frame time in ms
  24411. };
  24412. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24413. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24414. _this.blockMaterialDirtyMechanism = false;
  24415. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24416. _this._engine.scenes.push(_this);
  24417. _this._uid = null;
  24418. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24419. if (BABYLON.PostProcessManager) {
  24420. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24421. }
  24422. if (BABYLON.Tools.IsWindowObjectExist()) {
  24423. _this.attachControl();
  24424. }
  24425. //collision coordinator initialization. For now legacy per default.
  24426. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24427. // Uniform Buffer
  24428. _this._createUbo();
  24429. // Default Image processing definition
  24430. if (BABYLON.ImageProcessingConfiguration) {
  24431. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24432. }
  24433. _this.setDefaultCandidateProviders();
  24434. return _this;
  24435. }
  24436. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24437. /**
  24438. * Texture used in all pbr material as the reflection texture.
  24439. * As in the majority of the scene they are the same (exception for multi room and so on),
  24440. * this is easier to reference from here than from all the materials.
  24441. */
  24442. get: function () {
  24443. return this._environmentTexture;
  24444. },
  24445. /**
  24446. * Texture used in all pbr material as the reflection texture.
  24447. * As in the majority of the scene they are the same (exception for multi room and so on),
  24448. * this is easier to set here than in all the materials.
  24449. */
  24450. set: function (value) {
  24451. if (this._environmentTexture === value) {
  24452. return;
  24453. }
  24454. this._environmentTexture = value;
  24455. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24456. },
  24457. enumerable: true,
  24458. configurable: true
  24459. });
  24460. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24461. /**
  24462. * Default image processing configuration used either in the rendering
  24463. * Forward main pass or through the imageProcessingPostProcess if present.
  24464. * As in the majority of the scene they are the same (exception for multi camera),
  24465. * this is easier to reference from here than from all the materials and post process.
  24466. *
  24467. * No setter as we it is a shared configuration, you can set the values instead.
  24468. */
  24469. get: function () {
  24470. return this._imageProcessingConfiguration;
  24471. },
  24472. enumerable: true,
  24473. configurable: true
  24474. });
  24475. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24476. get: function () {
  24477. return this._forceWireframe;
  24478. },
  24479. /**
  24480. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24481. */
  24482. set: function (value) {
  24483. if (this._forceWireframe === value) {
  24484. return;
  24485. }
  24486. this._forceWireframe = value;
  24487. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24488. },
  24489. enumerable: true,
  24490. configurable: true
  24491. });
  24492. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24493. get: function () {
  24494. return this._forcePointsCloud;
  24495. },
  24496. /**
  24497. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24498. */
  24499. set: function (value) {
  24500. if (this._forcePointsCloud === value) {
  24501. return;
  24502. }
  24503. this._forcePointsCloud = value;
  24504. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24505. },
  24506. enumerable: true,
  24507. configurable: true
  24508. });
  24509. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24510. /**
  24511. * Gets or sets the animation properties override
  24512. */
  24513. get: function () {
  24514. return this._animationPropertiesOverride;
  24515. },
  24516. set: function (value) {
  24517. this._animationPropertiesOverride = value;
  24518. },
  24519. enumerable: true,
  24520. configurable: true
  24521. });
  24522. Object.defineProperty(Scene.prototype, "onDispose", {
  24523. /** Sets a function to be executed when this scene is disposed. */
  24524. set: function (callback) {
  24525. if (this._onDisposeObserver) {
  24526. this.onDisposeObservable.remove(this._onDisposeObserver);
  24527. }
  24528. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24529. },
  24530. enumerable: true,
  24531. configurable: true
  24532. });
  24533. Object.defineProperty(Scene.prototype, "beforeRender", {
  24534. /** Sets a function to be executed before rendering this scene */
  24535. set: function (callback) {
  24536. if (this._onBeforeRenderObserver) {
  24537. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24538. }
  24539. if (callback) {
  24540. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24541. }
  24542. },
  24543. enumerable: true,
  24544. configurable: true
  24545. });
  24546. Object.defineProperty(Scene.prototype, "afterRender", {
  24547. /** Sets a function to be executed after rendering this scene */
  24548. set: function (callback) {
  24549. if (this._onAfterRenderObserver) {
  24550. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24551. }
  24552. if (callback) {
  24553. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24554. }
  24555. },
  24556. enumerable: true,
  24557. configurable: true
  24558. });
  24559. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24560. /** Sets a function to be executed before rendering a camera*/
  24561. set: function (callback) {
  24562. if (this._onBeforeCameraRenderObserver) {
  24563. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24564. }
  24565. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24571. /** Sets a function to be executed after rendering a camera*/
  24572. set: function (callback) {
  24573. if (this._onAfterCameraRenderObserver) {
  24574. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24575. }
  24576. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24577. },
  24578. enumerable: true,
  24579. configurable: true
  24580. });
  24581. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24582. /**
  24583. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24584. */
  24585. get: function () {
  24586. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24587. },
  24588. enumerable: true,
  24589. configurable: true
  24590. });
  24591. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24592. get: function () {
  24593. return this._useRightHandedSystem;
  24594. },
  24595. /**
  24596. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24597. */
  24598. set: function (value) {
  24599. if (this._useRightHandedSystem === value) {
  24600. return;
  24601. }
  24602. this._useRightHandedSystem = value;
  24603. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. /**
  24609. * Sets the step Id used by deterministic lock step
  24610. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24611. * @param newStepId defines the step Id
  24612. */
  24613. Scene.prototype.setStepId = function (newStepId) {
  24614. this._currentStepId = newStepId;
  24615. };
  24616. ;
  24617. /**
  24618. * Gets the step Id used by deterministic lock step
  24619. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24620. * @returns the step Id
  24621. */
  24622. Scene.prototype.getStepId = function () {
  24623. return this._currentStepId;
  24624. };
  24625. ;
  24626. /**
  24627. * Gets the internal step used by deterministic lock step
  24628. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24629. * @returns the internal step
  24630. */
  24631. Scene.prototype.getInternalStep = function () {
  24632. return this._currentInternalStep;
  24633. };
  24634. ;
  24635. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24636. get: function () {
  24637. return this._fogEnabled;
  24638. },
  24639. /**
  24640. * Gets or sets a boolean indicating if fog is enabled on this scene
  24641. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24642. */
  24643. set: function (value) {
  24644. if (this._fogEnabled === value) {
  24645. return;
  24646. }
  24647. this._fogEnabled = value;
  24648. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24649. },
  24650. enumerable: true,
  24651. configurable: true
  24652. });
  24653. Object.defineProperty(Scene.prototype, "fogMode", {
  24654. get: function () {
  24655. return this._fogMode;
  24656. },
  24657. /**
  24658. * Gets or sets the fog mode to use
  24659. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24660. */
  24661. set: function (value) {
  24662. if (this._fogMode === value) {
  24663. return;
  24664. }
  24665. this._fogMode = value;
  24666. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24667. },
  24668. enumerable: true,
  24669. configurable: true
  24670. });
  24671. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24672. get: function () {
  24673. return this._shadowsEnabled;
  24674. },
  24675. /**
  24676. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24677. */
  24678. set: function (value) {
  24679. if (this._shadowsEnabled === value) {
  24680. return;
  24681. }
  24682. this._shadowsEnabled = value;
  24683. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24684. },
  24685. enumerable: true,
  24686. configurable: true
  24687. });
  24688. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24689. get: function () {
  24690. return this._lightsEnabled;
  24691. },
  24692. /**
  24693. * Gets or sets a boolean indicating if lights are enabled on this scene
  24694. */
  24695. set: function (value) {
  24696. if (this._lightsEnabled === value) {
  24697. return;
  24698. }
  24699. this._lightsEnabled = value;
  24700. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24701. },
  24702. enumerable: true,
  24703. configurable: true
  24704. });
  24705. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24706. /** The default material used on meshes when no material is affected */
  24707. get: function () {
  24708. if (!this._defaultMaterial) {
  24709. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24710. }
  24711. return this._defaultMaterial;
  24712. },
  24713. /** The default material used on meshes when no material is affected */
  24714. set: function (value) {
  24715. this._defaultMaterial = value;
  24716. },
  24717. enumerable: true,
  24718. configurable: true
  24719. });
  24720. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24721. get: function () {
  24722. return this._texturesEnabled;
  24723. },
  24724. /**
  24725. * Gets or sets a boolean indicating if textures are enabled on this scene
  24726. */
  24727. set: function (value) {
  24728. if (this._texturesEnabled === value) {
  24729. return;
  24730. }
  24731. this._texturesEnabled = value;
  24732. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24738. get: function () {
  24739. return this._skeletonsEnabled;
  24740. },
  24741. /**
  24742. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24743. */
  24744. set: function (value) {
  24745. if (this._skeletonsEnabled === value) {
  24746. return;
  24747. }
  24748. this._skeletonsEnabled = value;
  24749. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24755. /** @hidden */
  24756. get: function () {
  24757. return this._alternateRendering;
  24758. },
  24759. enumerable: true,
  24760. configurable: true
  24761. });
  24762. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24763. /**
  24764. * Gets the list of frustum planes (built from the active camera)
  24765. */
  24766. get: function () {
  24767. return this._frustumPlanes;
  24768. },
  24769. enumerable: true,
  24770. configurable: true
  24771. });
  24772. /**
  24773. * Registers the transient components if needed.
  24774. */
  24775. Scene.prototype._registerTransientComponents = function () {
  24776. // Register components that have been associated lately to the scene.
  24777. if (this._transientComponents.length > 0) {
  24778. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24779. var component = _a[_i];
  24780. component.register();
  24781. }
  24782. this._transientComponents = [];
  24783. }
  24784. };
  24785. /**
  24786. * @hidden
  24787. * Add a component to the scene.
  24788. * Note that the ccomponent could be registered on th next frame if this is called after
  24789. * the register component stage.
  24790. * @param component Defines the component to add to the scene
  24791. */
  24792. Scene.prototype._addComponent = function (component) {
  24793. this._components.push(component);
  24794. this._transientComponents.push(component);
  24795. var serializableComponent = component;
  24796. if (serializableComponent.addFromContainer) {
  24797. this._serializableComponents.push(serializableComponent);
  24798. }
  24799. };
  24800. /**
  24801. * @hidden
  24802. * Gets a component from the scene.
  24803. * @param name defines the name of the component to retrieve
  24804. * @returns the component or null if not present
  24805. */
  24806. Scene.prototype._getComponent = function (name) {
  24807. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24808. var component = _a[_i];
  24809. if (component.name === name) {
  24810. return component;
  24811. }
  24812. }
  24813. return null;
  24814. };
  24815. /**
  24816. * @hidden
  24817. */
  24818. Scene.prototype._getDefaultMeshCandidates = function () {
  24819. this._defaultMeshCandidates.data = this.meshes;
  24820. this._defaultMeshCandidates.length = this.meshes.length;
  24821. return this._defaultMeshCandidates;
  24822. };
  24823. /**
  24824. * @hidden
  24825. */
  24826. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  24827. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  24828. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  24829. return this._defaultSubMeshCandidates;
  24830. };
  24831. /**
  24832. * Sets the default candidate providers for the scene.
  24833. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  24834. * and getCollidingSubMeshCandidates to their default function
  24835. */
  24836. Scene.prototype.setDefaultCandidateProviders = function () {
  24837. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  24838. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24839. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24840. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24841. };
  24842. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24843. /**
  24844. * Gets a boolean indicating if collisions are processed on a web worker
  24845. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24846. */
  24847. get: function () {
  24848. return this._workerCollisions;
  24849. },
  24850. set: function (enabled) {
  24851. if (!BABYLON.CollisionCoordinatorLegacy) {
  24852. return;
  24853. }
  24854. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24855. this._workerCollisions = enabled;
  24856. if (this.collisionCoordinator) {
  24857. this.collisionCoordinator.destroy();
  24858. }
  24859. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24860. this.collisionCoordinator.init(this);
  24861. },
  24862. enumerable: true,
  24863. configurable: true
  24864. });
  24865. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24866. /**
  24867. * Gets the mesh that is currently under the pointer
  24868. */
  24869. get: function () {
  24870. return this._pointerOverMesh;
  24871. },
  24872. enumerable: true,
  24873. configurable: true
  24874. });
  24875. Object.defineProperty(Scene.prototype, "pointerX", {
  24876. /**
  24877. * Gets the current on-screen X position of the pointer
  24878. */
  24879. get: function () {
  24880. return this._pointerX;
  24881. },
  24882. enumerable: true,
  24883. configurable: true
  24884. });
  24885. Object.defineProperty(Scene.prototype, "pointerY", {
  24886. /**
  24887. * Gets the current on-screen Y position of the pointer
  24888. */
  24889. get: function () {
  24890. return this._pointerY;
  24891. },
  24892. enumerable: true,
  24893. configurable: true
  24894. });
  24895. /**
  24896. * Gets the cached material (ie. the latest rendered one)
  24897. * @returns the cached material
  24898. */
  24899. Scene.prototype.getCachedMaterial = function () {
  24900. return this._cachedMaterial;
  24901. };
  24902. /**
  24903. * Gets the cached effect (ie. the latest rendered one)
  24904. * @returns the cached effect
  24905. */
  24906. Scene.prototype.getCachedEffect = function () {
  24907. return this._cachedEffect;
  24908. };
  24909. /**
  24910. * Gets the cached visibility state (ie. the latest rendered one)
  24911. * @returns the cached visibility state
  24912. */
  24913. Scene.prototype.getCachedVisibility = function () {
  24914. return this._cachedVisibility;
  24915. };
  24916. /**
  24917. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24918. * @param material defines the current material
  24919. * @param effect defines the current effect
  24920. * @param visibility defines the current visibility state
  24921. * @returns true if one parameter is not cached
  24922. */
  24923. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24924. if (visibility === void 0) { visibility = 1; }
  24925. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24926. };
  24927. /**
  24928. * Gets the engine associated with the scene
  24929. * @returns an Engine
  24930. */
  24931. Scene.prototype.getEngine = function () {
  24932. return this._engine;
  24933. };
  24934. /**
  24935. * Gets the total number of vertices rendered per frame
  24936. * @returns the total number of vertices rendered per frame
  24937. */
  24938. Scene.prototype.getTotalVertices = function () {
  24939. return this._totalVertices.current;
  24940. };
  24941. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24942. /**
  24943. * Gets the performance counter for total vertices
  24944. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24945. */
  24946. get: function () {
  24947. return this._totalVertices;
  24948. },
  24949. enumerable: true,
  24950. configurable: true
  24951. });
  24952. /**
  24953. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24954. * @returns the total number of active indices rendered per frame
  24955. */
  24956. Scene.prototype.getActiveIndices = function () {
  24957. return this._activeIndices.current;
  24958. };
  24959. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24960. /**
  24961. * Gets the performance counter for active indices
  24962. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24963. */
  24964. get: function () {
  24965. return this._activeIndices;
  24966. },
  24967. enumerable: true,
  24968. configurable: true
  24969. });
  24970. /**
  24971. * Gets the total number of active particles rendered per frame
  24972. * @returns the total number of active particles rendered per frame
  24973. */
  24974. Scene.prototype.getActiveParticles = function () {
  24975. return this._activeParticles.current;
  24976. };
  24977. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24978. /**
  24979. * Gets the performance counter for active particles
  24980. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24981. */
  24982. get: function () {
  24983. return this._activeParticles;
  24984. },
  24985. enumerable: true,
  24986. configurable: true
  24987. });
  24988. /**
  24989. * Gets the total number of active bones rendered per frame
  24990. * @returns the total number of active bones rendered per frame
  24991. */
  24992. Scene.prototype.getActiveBones = function () {
  24993. return this._activeBones.current;
  24994. };
  24995. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24996. /**
  24997. * Gets the performance counter for active bones
  24998. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24999. */
  25000. get: function () {
  25001. return this._activeBones;
  25002. },
  25003. enumerable: true,
  25004. configurable: true
  25005. });
  25006. /** @hidden */
  25007. Scene.prototype.getInterFramePerfCounter = function () {
  25008. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25009. return 0;
  25010. };
  25011. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25012. /** @hidden */
  25013. get: function () {
  25014. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25015. return null;
  25016. },
  25017. enumerable: true,
  25018. configurable: true
  25019. });
  25020. /** @hidden */
  25021. Scene.prototype.getLastFrameDuration = function () {
  25022. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25023. return 0;
  25024. };
  25025. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25026. /** @hidden */
  25027. get: function () {
  25028. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25029. return null;
  25030. },
  25031. enumerable: true,
  25032. configurable: true
  25033. });
  25034. /** @hidden */
  25035. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25036. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25037. return 0;
  25038. };
  25039. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25040. /** @hidden */
  25041. get: function () {
  25042. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25043. return null;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. /**
  25049. * Gets the array of active meshes
  25050. * @returns an array of AbstractMesh
  25051. */
  25052. Scene.prototype.getActiveMeshes = function () {
  25053. return this._activeMeshes;
  25054. };
  25055. /** @hidden */
  25056. Scene.prototype.getRenderTargetsDuration = function () {
  25057. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25058. return 0;
  25059. };
  25060. /** @hidden */
  25061. Scene.prototype.getRenderDuration = function () {
  25062. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25063. return 0;
  25064. };
  25065. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25066. /** @hidden */
  25067. get: function () {
  25068. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25069. return null;
  25070. },
  25071. enumerable: true,
  25072. configurable: true
  25073. });
  25074. /** @hidden */
  25075. Scene.prototype.getParticlesDuration = function () {
  25076. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25077. return 0;
  25078. };
  25079. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25080. /** @hidden */
  25081. get: function () {
  25082. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25083. return null;
  25084. },
  25085. enumerable: true,
  25086. configurable: true
  25087. });
  25088. /** @hidden */
  25089. Scene.prototype.getSpritesDuration = function () {
  25090. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25091. return 0;
  25092. };
  25093. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25094. /** @hidden */
  25095. get: function () {
  25096. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25097. return null;
  25098. },
  25099. enumerable: true,
  25100. configurable: true
  25101. });
  25102. /**
  25103. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25104. * @returns a number
  25105. */
  25106. Scene.prototype.getAnimationRatio = function () {
  25107. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25108. };
  25109. /**
  25110. * Gets an unique Id for the current render phase
  25111. * @returns a number
  25112. */
  25113. Scene.prototype.getRenderId = function () {
  25114. return this._renderId;
  25115. };
  25116. /**
  25117. * Gets an unique Id for the current frame
  25118. * @returns a number
  25119. */
  25120. Scene.prototype.getFrameId = function () {
  25121. return this._frameId;
  25122. };
  25123. /** Call this function if you want to manually increment the render Id*/
  25124. Scene.prototype.incrementRenderId = function () {
  25125. this._renderId++;
  25126. };
  25127. Scene.prototype._updatePointerPosition = function (evt) {
  25128. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25129. if (!canvasRect) {
  25130. return;
  25131. }
  25132. this._pointerX = evt.clientX - canvasRect.left;
  25133. this._pointerY = evt.clientY - canvasRect.top;
  25134. this._unTranslatedPointerX = this._pointerX;
  25135. this._unTranslatedPointerY = this._pointerY;
  25136. };
  25137. Scene.prototype._createUbo = function () {
  25138. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25139. this._sceneUbo.addUniform("viewProjection", 16);
  25140. this._sceneUbo.addUniform("view", 16);
  25141. };
  25142. Scene.prototype._createAlternateUbo = function () {
  25143. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25144. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25145. this._alternateSceneUbo.addUniform("view", 16);
  25146. };
  25147. // Pointers handling
  25148. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25149. if (pointerInfo.pickInfo) {
  25150. if (!pointerInfo.pickInfo.ray) {
  25151. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25152. }
  25153. }
  25154. };
  25155. /**
  25156. * Use this method to simulate a pointer move on a mesh
  25157. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25158. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25159. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25160. * @returns the current scene
  25161. */
  25162. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25163. var evt = new PointerEvent("pointermove", pointerEventInit);
  25164. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25165. return this;
  25166. }
  25167. return this._processPointerMove(pickResult, evt);
  25168. };
  25169. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25170. var canvas = this._engine.getRenderingCanvas();
  25171. if (!canvas) {
  25172. return this;
  25173. }
  25174. // Restore pointer
  25175. canvas.style.cursor = this.defaultCursor;
  25176. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25177. if (isMeshPicked) {
  25178. this.setPointerOverMesh(pickResult.pickedMesh);
  25179. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25180. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25181. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25182. }
  25183. else {
  25184. canvas.style.cursor = this.hoverCursor;
  25185. }
  25186. }
  25187. }
  25188. else {
  25189. this.setPointerOverMesh(null);
  25190. }
  25191. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25192. var step = _a[_i];
  25193. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25194. }
  25195. if (pickResult) {
  25196. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25197. if (this.onPointerMove) {
  25198. this.onPointerMove(evt, pickResult, type);
  25199. }
  25200. if (this.onPointerObservable.hasObservers()) {
  25201. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25202. this._setRayOnPointerInfo(pi);
  25203. this.onPointerObservable.notifyObservers(pi, type);
  25204. }
  25205. }
  25206. return this;
  25207. };
  25208. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25209. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25210. if (pickResult) {
  25211. pi.ray = pickResult.ray;
  25212. }
  25213. this.onPrePointerObservable.notifyObservers(pi, type);
  25214. if (pi.skipOnPointerObservable) {
  25215. return true;
  25216. }
  25217. else {
  25218. return false;
  25219. }
  25220. };
  25221. /**
  25222. * Use this method to simulate a pointer down on a mesh
  25223. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25224. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25225. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25226. * @returns the current scene
  25227. */
  25228. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25229. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25230. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25231. return this;
  25232. }
  25233. return this._processPointerDown(pickResult, evt);
  25234. };
  25235. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25236. var _this = this;
  25237. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25238. this._pickedDownMesh = pickResult.pickedMesh;
  25239. var actionManager = pickResult.pickedMesh.actionManager;
  25240. if (actionManager) {
  25241. if (actionManager.hasPickTriggers) {
  25242. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25243. switch (evt.button) {
  25244. case 0:
  25245. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25246. break;
  25247. case 1:
  25248. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25249. break;
  25250. case 2:
  25251. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25252. break;
  25253. }
  25254. }
  25255. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25256. window.setTimeout(function () {
  25257. 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);
  25258. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25259. if (_this._totalPointersPressed !== 0 &&
  25260. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25261. !_this._isPointerSwiping()) {
  25262. _this._startingPointerTime = 0;
  25263. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25264. }
  25265. }
  25266. }, Scene.LongPressDelay);
  25267. }
  25268. }
  25269. }
  25270. else {
  25271. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25272. var step = _a[_i];
  25273. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25274. }
  25275. }
  25276. if (pickResult) {
  25277. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25278. if (this.onPointerDown) {
  25279. this.onPointerDown(evt, pickResult, type);
  25280. }
  25281. if (this.onPointerObservable.hasObservers()) {
  25282. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25283. this._setRayOnPointerInfo(pi);
  25284. this.onPointerObservable.notifyObservers(pi, type);
  25285. }
  25286. }
  25287. return this;
  25288. };
  25289. /**
  25290. * Use this method to simulate a pointer up on a mesh
  25291. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25292. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25293. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25294. * @returns the current scene
  25295. */
  25296. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25297. var evt = new PointerEvent("pointerup", pointerEventInit);
  25298. var clickInfo = new ClickInfo();
  25299. clickInfo.singleClick = true;
  25300. clickInfo.ignore = true;
  25301. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25302. return this;
  25303. }
  25304. return this._processPointerUp(pickResult, evt, clickInfo);
  25305. };
  25306. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25307. if (pickResult && pickResult && pickResult.pickedMesh) {
  25308. this._pickedUpMesh = pickResult.pickedMesh;
  25309. if (this._pickedDownMesh === this._pickedUpMesh) {
  25310. if (this.onPointerPick) {
  25311. this.onPointerPick(evt, pickResult);
  25312. }
  25313. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25314. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25315. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25316. this._setRayOnPointerInfo(pi);
  25317. this.onPointerObservable.notifyObservers(pi, type_1);
  25318. }
  25319. }
  25320. if (pickResult.pickedMesh.actionManager) {
  25321. if (clickInfo.ignore) {
  25322. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25323. }
  25324. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25325. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25326. }
  25327. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25328. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25329. }
  25330. }
  25331. }
  25332. else {
  25333. if (!clickInfo.ignore) {
  25334. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25335. var step = _a[_i];
  25336. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25337. }
  25338. }
  25339. }
  25340. if (this._pickedDownMesh &&
  25341. this._pickedDownMesh.actionManager &&
  25342. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25343. this._pickedDownMesh !== this._pickedUpMesh) {
  25344. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25345. }
  25346. var type = BABYLON.PointerEventTypes.POINTERUP;
  25347. if (this.onPointerObservable.hasObservers()) {
  25348. if (!clickInfo.ignore) {
  25349. if (!clickInfo.hasSwiped) {
  25350. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25351. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25352. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25353. this._setRayOnPointerInfo(pi);
  25354. this.onPointerObservable.notifyObservers(pi, type_2);
  25355. }
  25356. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25357. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25358. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25359. this._setRayOnPointerInfo(pi);
  25360. this.onPointerObservable.notifyObservers(pi, type_3);
  25361. }
  25362. }
  25363. }
  25364. else {
  25365. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25366. this._setRayOnPointerInfo(pi);
  25367. this.onPointerObservable.notifyObservers(pi, type);
  25368. }
  25369. }
  25370. if (this.onPointerUp) {
  25371. this.onPointerUp(evt, pickResult, type);
  25372. }
  25373. return this;
  25374. };
  25375. /**
  25376. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25377. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25378. * @returns true if the pointer was captured
  25379. */
  25380. Scene.prototype.isPointerCaptured = function (pointerId) {
  25381. if (pointerId === void 0) { pointerId = 0; }
  25382. return this._pointerCaptures[pointerId];
  25383. };
  25384. /** @hidden */
  25385. Scene.prototype._isPointerSwiping = function () {
  25386. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25387. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25388. };
  25389. /**
  25390. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25391. * @param attachUp defines if you want to attach events to pointerup
  25392. * @param attachDown defines if you want to attach events to pointerdown
  25393. * @param attachMove defines if you want to attach events to pointermove
  25394. */
  25395. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25396. var _this = this;
  25397. if (attachUp === void 0) { attachUp = true; }
  25398. if (attachDown === void 0) { attachDown = true; }
  25399. if (attachMove === void 0) { attachMove = true; }
  25400. this._initActionManager = function (act, clickInfo) {
  25401. if (!_this._meshPickProceed) {
  25402. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25403. _this._currentPickResult = pickResult;
  25404. if (pickResult) {
  25405. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25406. }
  25407. _this._meshPickProceed = true;
  25408. }
  25409. return act;
  25410. };
  25411. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25412. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25413. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25414. btn !== _this._previousButtonPressed) {
  25415. _this._doubleClickOccured = false;
  25416. clickInfo.singleClick = true;
  25417. clickInfo.ignore = false;
  25418. cb(clickInfo, _this._currentPickResult);
  25419. }
  25420. };
  25421. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25422. var clickInfo = new ClickInfo();
  25423. _this._currentPickResult = null;
  25424. var act = null;
  25425. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25426. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25427. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25428. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25429. act = _this._initActionManager(act, clickInfo);
  25430. if (act)
  25431. checkPicking = act.hasPickTriggers;
  25432. }
  25433. if (checkPicking) {
  25434. var btn = evt.button;
  25435. clickInfo.hasSwiped = _this._isPointerSwiping();
  25436. if (!clickInfo.hasSwiped) {
  25437. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25438. if (!checkSingleClickImmediately) {
  25439. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25440. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25441. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25442. act = _this._initActionManager(act, clickInfo);
  25443. if (act)
  25444. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25445. }
  25446. }
  25447. if (checkSingleClickImmediately) {
  25448. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25449. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25450. btn !== _this._previousButtonPressed) {
  25451. clickInfo.singleClick = true;
  25452. cb(clickInfo, _this._currentPickResult);
  25453. }
  25454. }
  25455. // at least one double click is required to be check and exclusive double click is enabled
  25456. else {
  25457. // wait that no double click has been raised during the double click delay
  25458. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25459. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25460. }
  25461. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25462. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25463. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25464. act = _this._initActionManager(act, clickInfo);
  25465. if (act)
  25466. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25467. }
  25468. if (checkDoubleClick) {
  25469. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25470. if (btn === _this._previousButtonPressed &&
  25471. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25472. !_this._doubleClickOccured) {
  25473. // pointer has not moved for 2 clicks, it's a double click
  25474. if (!clickInfo.hasSwiped &&
  25475. !_this._isPointerSwiping()) {
  25476. _this._previousStartingPointerTime = 0;
  25477. _this._doubleClickOccured = true;
  25478. clickInfo.doubleClick = true;
  25479. clickInfo.ignore = false;
  25480. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25481. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25482. }
  25483. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25484. cb(clickInfo, _this._currentPickResult);
  25485. }
  25486. // if the two successive clicks are too far, it's just two simple clicks
  25487. else {
  25488. _this._doubleClickOccured = false;
  25489. _this._previousStartingPointerTime = _this._startingPointerTime;
  25490. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25491. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25492. _this._previousButtonPressed = btn;
  25493. if (Scene.ExclusiveDoubleClickMode) {
  25494. if (_this._previousDelayedSimpleClickTimeout) {
  25495. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25496. }
  25497. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25498. cb(clickInfo, _this._previousPickResult);
  25499. }
  25500. else {
  25501. cb(clickInfo, _this._currentPickResult);
  25502. }
  25503. }
  25504. }
  25505. // just the first click of the double has been raised
  25506. else {
  25507. _this._doubleClickOccured = false;
  25508. _this._previousStartingPointerTime = _this._startingPointerTime;
  25509. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25510. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25511. _this._previousButtonPressed = btn;
  25512. }
  25513. }
  25514. }
  25515. }
  25516. clickInfo.ignore = true;
  25517. cb(clickInfo, _this._currentPickResult);
  25518. };
  25519. this._onPointerMove = function (evt) {
  25520. _this._updatePointerPosition(evt);
  25521. // PreObservable support
  25522. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25523. return;
  25524. }
  25525. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25526. return;
  25527. }
  25528. if (!_this.pointerMovePredicate) {
  25529. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25530. }
  25531. // Meshes
  25532. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25533. _this._processPointerMove(pickResult, evt);
  25534. };
  25535. this._onPointerDown = function (evt) {
  25536. _this._totalPointersPressed++;
  25537. _this._pickedDownMesh = null;
  25538. _this._meshPickProceed = false;
  25539. _this._updatePointerPosition(evt);
  25540. if (_this.preventDefaultOnPointerDown && canvas) {
  25541. evt.preventDefault();
  25542. canvas.focus();
  25543. }
  25544. // PreObservable support
  25545. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25546. return;
  25547. }
  25548. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25549. return;
  25550. }
  25551. _this._pointerCaptures[evt.pointerId] = true;
  25552. _this._startingPointerPosition.x = _this._pointerX;
  25553. _this._startingPointerPosition.y = _this._pointerY;
  25554. _this._startingPointerTime = Date.now();
  25555. if (!_this.pointerDownPredicate) {
  25556. _this.pointerDownPredicate = function (mesh) {
  25557. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25558. };
  25559. }
  25560. // Meshes
  25561. _this._pickedDownMesh = null;
  25562. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25563. _this._processPointerDown(pickResult, evt);
  25564. };
  25565. this._onPointerUp = function (evt) {
  25566. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25567. return; // So we need to test it the pointer down was pressed before.
  25568. }
  25569. _this._totalPointersPressed--;
  25570. _this._pickedUpMesh = null;
  25571. _this._meshPickProceed = false;
  25572. _this._updatePointerPosition(evt);
  25573. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25574. // PreObservable support
  25575. if (_this.onPrePointerObservable.hasObservers()) {
  25576. if (!clickInfo.ignore) {
  25577. if (!clickInfo.hasSwiped) {
  25578. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25579. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25580. return;
  25581. }
  25582. }
  25583. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25584. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25585. return;
  25586. }
  25587. }
  25588. }
  25589. }
  25590. else {
  25591. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25592. return;
  25593. }
  25594. }
  25595. }
  25596. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25597. return;
  25598. }
  25599. _this._pointerCaptures[evt.pointerId] = false;
  25600. if (!_this.pointerUpPredicate) {
  25601. _this.pointerUpPredicate = function (mesh) {
  25602. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25603. };
  25604. }
  25605. // Meshes
  25606. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25607. _this._initActionManager(null, clickInfo);
  25608. }
  25609. if (!pickResult) {
  25610. pickResult = _this._currentPickResult;
  25611. }
  25612. _this._processPointerUp(pickResult, evt, clickInfo);
  25613. _this._previousPickResult = _this._currentPickResult;
  25614. });
  25615. };
  25616. this._onKeyDown = function (evt) {
  25617. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25618. if (_this.onPreKeyboardObservable.hasObservers()) {
  25619. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25620. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25621. if (pi.skipOnPointerObservable) {
  25622. return;
  25623. }
  25624. }
  25625. if (_this.onKeyboardObservable.hasObservers()) {
  25626. var pi = new BABYLON.KeyboardInfo(type, evt);
  25627. _this.onKeyboardObservable.notifyObservers(pi, type);
  25628. }
  25629. if (_this.actionManager) {
  25630. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25631. }
  25632. };
  25633. this._onKeyUp = function (evt) {
  25634. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25635. if (_this.onPreKeyboardObservable.hasObservers()) {
  25636. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25637. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25638. if (pi.skipOnPointerObservable) {
  25639. return;
  25640. }
  25641. }
  25642. if (_this.onKeyboardObservable.hasObservers()) {
  25643. var pi = new BABYLON.KeyboardInfo(type, evt);
  25644. _this.onKeyboardObservable.notifyObservers(pi, type);
  25645. }
  25646. if (_this.actionManager) {
  25647. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25648. }
  25649. };
  25650. var engine = this.getEngine();
  25651. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25652. if (!canvas) {
  25653. return;
  25654. }
  25655. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25656. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25657. });
  25658. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25659. if (!canvas) {
  25660. return;
  25661. }
  25662. canvas.removeEventListener("keydown", _this._onKeyDown);
  25663. canvas.removeEventListener("keyup", _this._onKeyUp);
  25664. });
  25665. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25666. var canvas = this._engine.getRenderingCanvas();
  25667. if (!canvas) {
  25668. return;
  25669. }
  25670. if (attachMove) {
  25671. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25672. // Wheel
  25673. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25674. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25675. }
  25676. if (attachDown) {
  25677. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25678. }
  25679. if (attachUp) {
  25680. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25681. }
  25682. canvas.tabIndex = 1;
  25683. };
  25684. /** Detaches all event handlers*/
  25685. Scene.prototype.detachControl = function () {
  25686. var engine = this.getEngine();
  25687. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25688. var canvas = engine.getRenderingCanvas();
  25689. if (!canvas) {
  25690. return;
  25691. }
  25692. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25693. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25694. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25695. if (this._onCanvasBlurObserver) {
  25696. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25697. }
  25698. if (this._onCanvasFocusObserver) {
  25699. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25700. }
  25701. // Wheel
  25702. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25703. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25704. // Keyboard
  25705. canvas.removeEventListener("keydown", this._onKeyDown);
  25706. canvas.removeEventListener("keyup", this._onKeyUp);
  25707. // Observables
  25708. this.onKeyboardObservable.clear();
  25709. this.onPreKeyboardObservable.clear();
  25710. this.onPointerObservable.clear();
  25711. this.onPrePointerObservable.clear();
  25712. };
  25713. /**
  25714. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25715. * Delay loaded resources are not taking in account
  25716. * @return true if all required resources are ready
  25717. */
  25718. Scene.prototype.isReady = function () {
  25719. if (this._isDisposed) {
  25720. return false;
  25721. }
  25722. if (this._pendingData.length > 0) {
  25723. return false;
  25724. }
  25725. var index;
  25726. var engine = this.getEngine();
  25727. // Geometries
  25728. for (index = 0; index < this.geometries.length; index++) {
  25729. var geometry = this.geometries[index];
  25730. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25731. return false;
  25732. }
  25733. }
  25734. // Meshes
  25735. for (index = 0; index < this.meshes.length; index++) {
  25736. var mesh = this.meshes[index];
  25737. if (!mesh.isEnabled()) {
  25738. continue;
  25739. }
  25740. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25741. continue;
  25742. }
  25743. if (!mesh.isReady(true)) {
  25744. return false;
  25745. }
  25746. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25747. // Is Ready For Mesh
  25748. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25749. var step = _a[_i];
  25750. if (!step.action(mesh, hardwareInstancedRendering)) {
  25751. return false;
  25752. }
  25753. }
  25754. }
  25755. // Post-processes
  25756. if (this.activeCameras && this.activeCameras.length > 0) {
  25757. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25758. var camera = _c[_b];
  25759. if (!camera.isReady(true)) {
  25760. return false;
  25761. }
  25762. }
  25763. }
  25764. else if (this.activeCamera) {
  25765. if (!this.activeCamera.isReady(true)) {
  25766. return false;
  25767. }
  25768. }
  25769. // Particles
  25770. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25771. var particleSystem = _e[_d];
  25772. if (!particleSystem.isReady()) {
  25773. return false;
  25774. }
  25775. }
  25776. return true;
  25777. };
  25778. /** Resets all cached information relative to material (including effect and visibility) */
  25779. Scene.prototype.resetCachedMaterial = function () {
  25780. this._cachedMaterial = null;
  25781. this._cachedEffect = null;
  25782. this._cachedVisibility = null;
  25783. };
  25784. /**
  25785. * Registers a function to be called before every frame render
  25786. * @param func defines the function to register
  25787. */
  25788. Scene.prototype.registerBeforeRender = function (func) {
  25789. this.onBeforeRenderObservable.add(func);
  25790. };
  25791. /**
  25792. * Unregisters a function called before every frame render
  25793. * @param func defines the function to unregister
  25794. */
  25795. Scene.prototype.unregisterBeforeRender = function (func) {
  25796. this.onBeforeRenderObservable.removeCallback(func);
  25797. };
  25798. /**
  25799. * Registers a function to be called after every frame render
  25800. * @param func defines the function to register
  25801. */
  25802. Scene.prototype.registerAfterRender = function (func) {
  25803. this.onAfterRenderObservable.add(func);
  25804. };
  25805. /**
  25806. * Unregisters a function called after every frame render
  25807. * @param func defines the function to unregister
  25808. */
  25809. Scene.prototype.unregisterAfterRender = function (func) {
  25810. this.onAfterRenderObservable.removeCallback(func);
  25811. };
  25812. Scene.prototype._executeOnceBeforeRender = function (func) {
  25813. var _this = this;
  25814. var execFunc = function () {
  25815. func();
  25816. setTimeout(function () {
  25817. _this.unregisterBeforeRender(execFunc);
  25818. });
  25819. };
  25820. this.registerBeforeRender(execFunc);
  25821. };
  25822. /**
  25823. * The provided function will run before render once and will be disposed afterwards.
  25824. * A timeout delay can be provided so that the function will be executed in N ms.
  25825. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25826. * @param func The function to be executed.
  25827. * @param timeout optional delay in ms
  25828. */
  25829. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25830. var _this = this;
  25831. if (timeout !== undefined) {
  25832. setTimeout(function () {
  25833. _this._executeOnceBeforeRender(func);
  25834. }, timeout);
  25835. }
  25836. else {
  25837. this._executeOnceBeforeRender(func);
  25838. }
  25839. };
  25840. /** @hidden */
  25841. Scene.prototype._addPendingData = function (data) {
  25842. this._pendingData.push(data);
  25843. };
  25844. /** @hidden */
  25845. Scene.prototype._removePendingData = function (data) {
  25846. var wasLoading = this.isLoading;
  25847. var index = this._pendingData.indexOf(data);
  25848. if (index !== -1) {
  25849. this._pendingData.splice(index, 1);
  25850. }
  25851. if (wasLoading && !this.isLoading) {
  25852. this.onDataLoadedObservable.notifyObservers(this);
  25853. }
  25854. };
  25855. /**
  25856. * Returns the number of items waiting to be loaded
  25857. * @returns the number of items waiting to be loaded
  25858. */
  25859. Scene.prototype.getWaitingItemsCount = function () {
  25860. return this._pendingData.length;
  25861. };
  25862. Object.defineProperty(Scene.prototype, "isLoading", {
  25863. /**
  25864. * Returns a boolean indicating if the scene is still loading data
  25865. */
  25866. get: function () {
  25867. return this._pendingData.length > 0;
  25868. },
  25869. enumerable: true,
  25870. configurable: true
  25871. });
  25872. /**
  25873. * Registers a function to be executed when the scene is ready
  25874. * @param {Function} func - the function to be executed
  25875. */
  25876. Scene.prototype.executeWhenReady = function (func) {
  25877. var _this = this;
  25878. this.onReadyObservable.add(func);
  25879. if (this._executeWhenReadyTimeoutId !== -1) {
  25880. return;
  25881. }
  25882. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25883. _this._checkIsReady();
  25884. }, 150);
  25885. };
  25886. /**
  25887. * Returns a promise that resolves when the scene is ready
  25888. * @returns A promise that resolves when the scene is ready
  25889. */
  25890. Scene.prototype.whenReadyAsync = function () {
  25891. var _this = this;
  25892. return new Promise(function (resolve) {
  25893. _this.executeWhenReady(function () {
  25894. resolve();
  25895. });
  25896. });
  25897. };
  25898. /** @hidden */
  25899. Scene.prototype._checkIsReady = function () {
  25900. var _this = this;
  25901. this._registerTransientComponents();
  25902. if (this.isReady()) {
  25903. this.onReadyObservable.notifyObservers(this);
  25904. this.onReadyObservable.clear();
  25905. this._executeWhenReadyTimeoutId = -1;
  25906. return;
  25907. }
  25908. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25909. _this._checkIsReady();
  25910. }, 150);
  25911. };
  25912. // Animations
  25913. /**
  25914. * Will start the animation sequence of a given target
  25915. * @param target defines the target
  25916. * @param from defines from which frame should animation start
  25917. * @param to defines until which frame should animation run.
  25918. * @param weight defines the weight to apply to the animation (1.0 by default)
  25919. * @param loop defines if the animation loops
  25920. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25921. * @param onAnimationEnd defines the function to be executed when the animation ends
  25922. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25923. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25924. * @returns the animatable object created for this animation
  25925. */
  25926. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25927. if (weight === void 0) { weight = 1.0; }
  25928. if (speedRatio === void 0) { speedRatio = 1.0; }
  25929. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25930. returnedAnimatable.weight = weight;
  25931. return returnedAnimatable;
  25932. };
  25933. /**
  25934. * Will start the animation sequence of a given target
  25935. * @param target defines the target
  25936. * @param from defines from which frame should animation start
  25937. * @param to defines until which frame should animation run.
  25938. * @param loop defines if the animation loops
  25939. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25940. * @param onAnimationEnd defines the function to be executed when the animation ends
  25941. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25942. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25943. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25944. * @returns the animatable object created for this animation
  25945. */
  25946. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25947. if (speedRatio === void 0) { speedRatio = 1.0; }
  25948. if (stopCurrent === void 0) { stopCurrent = true; }
  25949. if (from > to && speedRatio > 0) {
  25950. speedRatio *= -1;
  25951. }
  25952. if (stopCurrent) {
  25953. this.stopAnimation(target, undefined, targetMask);
  25954. }
  25955. if (!animatable) {
  25956. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25957. }
  25958. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25959. // Local animations
  25960. if (target.animations && shouldRunTargetAnimations) {
  25961. animatable.appendAnimations(target, target.animations);
  25962. }
  25963. // Children animations
  25964. if (target.getAnimatables) {
  25965. var animatables = target.getAnimatables();
  25966. for (var index = 0; index < animatables.length; index++) {
  25967. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25968. }
  25969. }
  25970. animatable.reset();
  25971. return animatable;
  25972. };
  25973. /**
  25974. * Begin a new animation on a given node
  25975. * @param target defines the target where the animation will take place
  25976. * @param animations defines the list of animations to start
  25977. * @param from defines the initial value
  25978. * @param to defines the final value
  25979. * @param loop defines if you want animation to loop (off by default)
  25980. * @param speedRatio defines the speed ratio to apply to all animations
  25981. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25982. * @returns the list of created animatables
  25983. */
  25984. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25985. if (speedRatio === undefined) {
  25986. speedRatio = 1.0;
  25987. }
  25988. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25989. return animatable;
  25990. };
  25991. /**
  25992. * Begin a new animation on a given node and its hierarchy
  25993. * @param target defines the root node where the animation will take place
  25994. * @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.
  25995. * @param animations defines the list of animations to start
  25996. * @param from defines the initial value
  25997. * @param to defines the final value
  25998. * @param loop defines if you want animation to loop (off by default)
  25999. * @param speedRatio defines the speed ratio to apply to all animations
  26000. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26001. * @returns the list of animatables created for all nodes
  26002. */
  26003. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26004. var children = target.getDescendants(directDescendantsOnly);
  26005. var result = [];
  26006. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26007. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26008. var child = children_1[_i];
  26009. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26010. }
  26011. return result;
  26012. };
  26013. /**
  26014. * Gets the animatable associated with a specific target
  26015. * @param target defines the target of the animatable
  26016. * @returns the required animatable if found
  26017. */
  26018. Scene.prototype.getAnimatableByTarget = function (target) {
  26019. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26020. if (this._activeAnimatables[index].target === target) {
  26021. return this._activeAnimatables[index];
  26022. }
  26023. }
  26024. return null;
  26025. };
  26026. /**
  26027. * Gets all animatables associated with a given target
  26028. * @param target defines the target to look animatables for
  26029. * @returns an array of Animatables
  26030. */
  26031. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26032. var result = [];
  26033. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26034. if (this._activeAnimatables[index].target === target) {
  26035. result.push(this._activeAnimatables[index]);
  26036. }
  26037. }
  26038. return result;
  26039. };
  26040. Object.defineProperty(Scene.prototype, "animatables", {
  26041. /**
  26042. * Gets all animatable attached to the scene
  26043. */
  26044. get: function () {
  26045. return this._activeAnimatables;
  26046. },
  26047. enumerable: true,
  26048. configurable: true
  26049. });
  26050. /**
  26051. * Will stop the animation of the given target
  26052. * @param target - the target
  26053. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26054. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  26055. */
  26056. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26057. var animatables = this.getAllAnimatablesByTarget(target);
  26058. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26059. var animatable = animatables_1[_i];
  26060. animatable.stop(animationName, targetMask);
  26061. }
  26062. };
  26063. /**
  26064. * Stops and removes all animations that have been applied to the scene
  26065. */
  26066. Scene.prototype.stopAllAnimations = function () {
  26067. if (this._activeAnimatables) {
  26068. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26069. this._activeAnimatables[i].stop();
  26070. }
  26071. this._activeAnimatables = [];
  26072. }
  26073. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26074. var group = _a[_i];
  26075. group.stop();
  26076. }
  26077. };
  26078. Scene.prototype._animate = function () {
  26079. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26080. return;
  26081. }
  26082. // Getting time
  26083. var now = BABYLON.Tools.Now;
  26084. if (!this._animationTimeLast) {
  26085. if (this._pendingData.length > 0) {
  26086. return;
  26087. }
  26088. this._animationTimeLast = now;
  26089. }
  26090. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26091. this._animationTime += deltaTime;
  26092. this._animationTimeLast = now;
  26093. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26094. this._activeAnimatables[index]._animate(this._animationTime);
  26095. }
  26096. // Late animation bindings
  26097. this._processLateAnimationBindings();
  26098. };
  26099. /** @hidden */
  26100. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26101. var target = runtimeAnimation.target;
  26102. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26103. if (!target._lateAnimationHolders) {
  26104. target._lateAnimationHolders = {};
  26105. }
  26106. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26107. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26108. totalWeight: 0,
  26109. animations: [],
  26110. originalValue: originalValue
  26111. };
  26112. }
  26113. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26114. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26115. };
  26116. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26117. var normalizer = 1.0;
  26118. var finalPosition = BABYLON.Tmp.Vector3[0];
  26119. var finalScaling = BABYLON.Tmp.Vector3[1];
  26120. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26121. var startIndex = 0;
  26122. var originalAnimation = holder.animations[0];
  26123. var originalValue = holder.originalValue;
  26124. var scale = 1;
  26125. if (holder.totalWeight < 1.0) {
  26126. // We need to mix the original value in
  26127. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26128. scale = 1.0 - holder.totalWeight;
  26129. }
  26130. else {
  26131. startIndex = 1;
  26132. // We need to normalize the weights
  26133. normalizer = holder.totalWeight;
  26134. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26135. scale = originalAnimation.weight / normalizer;
  26136. if (scale == 1) {
  26137. return originalAnimation.currentValue;
  26138. }
  26139. }
  26140. finalScaling.scaleInPlace(scale);
  26141. finalPosition.scaleInPlace(scale);
  26142. finalQuaternion.scaleInPlace(scale);
  26143. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26144. var runtimeAnimation = holder.animations[animIndex];
  26145. var scale = runtimeAnimation.weight / normalizer;
  26146. var currentPosition = BABYLON.Tmp.Vector3[2];
  26147. var currentScaling = BABYLON.Tmp.Vector3[3];
  26148. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26149. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26150. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26151. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26152. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26153. }
  26154. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26155. return originalAnimation._workValue;
  26156. };
  26157. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26158. var originalAnimation = holder.animations[0];
  26159. var originalValue = holder.originalValue;
  26160. if (holder.animations.length === 1) {
  26161. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26162. return refQuaternion;
  26163. }
  26164. var normalizer = 1.0;
  26165. var quaternions;
  26166. var weights;
  26167. if (holder.totalWeight < 1.0) {
  26168. var scale = 1.0 - holder.totalWeight;
  26169. quaternions = [];
  26170. weights = [];
  26171. quaternions.push(originalValue);
  26172. weights.push(scale);
  26173. }
  26174. else {
  26175. if (holder.animations.length === 2) { // Slerp as soon as we can
  26176. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26177. return refQuaternion;
  26178. }
  26179. quaternions = [];
  26180. weights = [];
  26181. normalizer = holder.totalWeight;
  26182. }
  26183. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26184. var runtimeAnimation = holder.animations[animIndex];
  26185. quaternions.push(runtimeAnimation.currentValue);
  26186. weights.push(runtimeAnimation.weight / normalizer);
  26187. }
  26188. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26189. var cumulativeAmount = 0;
  26190. var cumulativeQuaternion = null;
  26191. for (var index = 0; index < quaternions.length;) {
  26192. if (!cumulativeQuaternion) {
  26193. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26194. cumulativeQuaternion = refQuaternion;
  26195. cumulativeAmount = weights[index] + weights[index + 1];
  26196. index += 2;
  26197. continue;
  26198. }
  26199. cumulativeAmount += weights[index];
  26200. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26201. index++;
  26202. }
  26203. return cumulativeQuaternion;
  26204. };
  26205. Scene.prototype._processLateAnimationBindings = function () {
  26206. if (!this._registeredForLateAnimationBindings.length) {
  26207. return;
  26208. }
  26209. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26210. var target = this._registeredForLateAnimationBindings.data[index];
  26211. for (var path in target._lateAnimationHolders) {
  26212. var holder = target._lateAnimationHolders[path];
  26213. var originalAnimation = holder.animations[0];
  26214. var originalValue = holder.originalValue;
  26215. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26216. var finalValue = target[path];
  26217. if (matrixDecomposeMode) {
  26218. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26219. }
  26220. else {
  26221. var quaternionMode = originalValue.w !== undefined;
  26222. if (quaternionMode) {
  26223. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26224. }
  26225. else {
  26226. var startIndex = 0;
  26227. var normalizer = 1.0;
  26228. if (holder.totalWeight < 1.0) {
  26229. // We need to mix the original value in
  26230. if (originalValue.scale) {
  26231. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26232. }
  26233. else {
  26234. finalValue = originalValue * (1.0 - holder.totalWeight);
  26235. }
  26236. }
  26237. else {
  26238. // We need to normalize the weights
  26239. normalizer = holder.totalWeight;
  26240. var scale_1 = originalAnimation.weight / normalizer;
  26241. if (scale_1 !== 1) {
  26242. if (originalAnimation.currentValue.scale) {
  26243. finalValue = originalAnimation.currentValue.scale(scale_1);
  26244. }
  26245. else {
  26246. finalValue = originalAnimation.currentValue * scale_1;
  26247. }
  26248. }
  26249. else {
  26250. finalValue = originalAnimation.currentValue;
  26251. }
  26252. startIndex = 1;
  26253. }
  26254. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26255. var runtimeAnimation = holder.animations[animIndex];
  26256. var scale = runtimeAnimation.weight / normalizer;
  26257. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26258. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26259. }
  26260. else {
  26261. finalValue += runtimeAnimation.currentValue * scale;
  26262. }
  26263. }
  26264. }
  26265. }
  26266. target[path] = finalValue;
  26267. }
  26268. target._lateAnimationHolders = {};
  26269. }
  26270. this._registeredForLateAnimationBindings.reset();
  26271. };
  26272. // Matrix
  26273. /** @hidden */
  26274. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26275. this._useAlternateCameraConfiguration = active;
  26276. };
  26277. /**
  26278. * Gets the current view matrix
  26279. * @returns a Matrix
  26280. */
  26281. Scene.prototype.getViewMatrix = function () {
  26282. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26283. };
  26284. /**
  26285. * Gets the current projection matrix
  26286. * @returns a Matrix
  26287. */
  26288. Scene.prototype.getProjectionMatrix = function () {
  26289. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26290. };
  26291. /**
  26292. * Gets the current transform matrix
  26293. * @returns a Matrix made of View * Projection
  26294. */
  26295. Scene.prototype.getTransformMatrix = function () {
  26296. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26297. };
  26298. /**
  26299. * Sets the current transform matrix
  26300. * @param view defines the View matrix to use
  26301. * @param projection defines the Projection matrix to use
  26302. */
  26303. Scene.prototype.setTransformMatrix = function (view, projection) {
  26304. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26305. return;
  26306. }
  26307. this._viewUpdateFlag = view.updateFlag;
  26308. this._projectionUpdateFlag = projection.updateFlag;
  26309. this._viewMatrix = view;
  26310. this._projectionMatrix = projection;
  26311. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26312. // Update frustum
  26313. if (!this._frustumPlanes) {
  26314. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26315. }
  26316. else {
  26317. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26318. }
  26319. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26320. var otherCamera = this.activeCamera._alternateCamera;
  26321. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26322. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26323. }
  26324. if (this._sceneUbo.useUbo) {
  26325. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26326. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26327. this._sceneUbo.update();
  26328. }
  26329. };
  26330. /** @hidden */
  26331. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26332. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26333. return;
  26334. }
  26335. this._alternateViewUpdateFlag = view.updateFlag;
  26336. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26337. this._alternateViewMatrix = view;
  26338. this._alternateProjectionMatrix = projection;
  26339. if (!this._alternateTransformMatrix) {
  26340. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26341. }
  26342. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26343. if (!this._alternateSceneUbo) {
  26344. this._createAlternateUbo();
  26345. }
  26346. if (this._alternateSceneUbo.useUbo) {
  26347. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26348. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26349. this._alternateSceneUbo.update();
  26350. }
  26351. };
  26352. /**
  26353. * Gets the uniform buffer used to store scene data
  26354. * @returns a UniformBuffer
  26355. */
  26356. Scene.prototype.getSceneUniformBuffer = function () {
  26357. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26358. };
  26359. /**
  26360. * Gets an unique (relatively to the current scene) Id
  26361. * @returns an unique number for the scene
  26362. */
  26363. Scene.prototype.getUniqueId = function () {
  26364. var result = Scene._uniqueIdCounter;
  26365. Scene._uniqueIdCounter++;
  26366. return result;
  26367. };
  26368. /**
  26369. * Add a mesh to the list of scene's meshes
  26370. * @param newMesh defines the mesh to add
  26371. * @param recursive if all child meshes should also be added to the scene
  26372. */
  26373. Scene.prototype.addMesh = function (newMesh, recursive) {
  26374. var _this = this;
  26375. if (recursive === void 0) { recursive = false; }
  26376. this.meshes.push(newMesh);
  26377. //notify the collision coordinator
  26378. if (this.collisionCoordinator) {
  26379. this.collisionCoordinator.onMeshAdded(newMesh);
  26380. }
  26381. newMesh._resyncLightSources();
  26382. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26383. if (recursive) {
  26384. newMesh.getChildMeshes().forEach(function (m) {
  26385. _this.addMesh(m);
  26386. });
  26387. }
  26388. };
  26389. /**
  26390. * Remove a mesh for the list of scene's meshes
  26391. * @param toRemove defines the mesh to remove
  26392. * @param recursive if all child meshes should also be removed from the scene
  26393. * @returns the index where the mesh was in the mesh list
  26394. */
  26395. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26396. var _this = this;
  26397. if (recursive === void 0) { recursive = false; }
  26398. var index = this.meshes.indexOf(toRemove);
  26399. if (index !== -1) {
  26400. // Remove from the scene if mesh found
  26401. this.meshes.splice(index, 1);
  26402. }
  26403. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26404. if (recursive) {
  26405. toRemove.getChildMeshes().forEach(function (m) {
  26406. _this.removeMesh(m);
  26407. });
  26408. }
  26409. return index;
  26410. };
  26411. /**
  26412. * Add a transform node to the list of scene's transform nodes
  26413. * @param newTransformNode defines the transform node to add
  26414. */
  26415. Scene.prototype.addTransformNode = function (newTransformNode) {
  26416. this.transformNodes.push(newTransformNode);
  26417. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26418. };
  26419. /**
  26420. * Remove a transform node for the list of scene's transform nodes
  26421. * @param toRemove defines the transform node to remove
  26422. * @returns the index where the transform node was in the transform node list
  26423. */
  26424. Scene.prototype.removeTransformNode = function (toRemove) {
  26425. var index = this.transformNodes.indexOf(toRemove);
  26426. if (index !== -1) {
  26427. // Remove from the scene if found
  26428. this.transformNodes.splice(index, 1);
  26429. }
  26430. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26431. return index;
  26432. };
  26433. /**
  26434. * Remove a skeleton for the list of scene's skeletons
  26435. * @param toRemove defines the skeleton to remove
  26436. * @returns the index where the skeleton was in the skeleton list
  26437. */
  26438. Scene.prototype.removeSkeleton = function (toRemove) {
  26439. var index = this.skeletons.indexOf(toRemove);
  26440. if (index !== -1) {
  26441. // Remove from the scene if found
  26442. this.skeletons.splice(index, 1);
  26443. }
  26444. return index;
  26445. };
  26446. /**
  26447. * Remove a morph target for the list of scene's morph targets
  26448. * @param toRemove defines the morph target to remove
  26449. * @returns the index where the morph target was in the morph target list
  26450. */
  26451. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26452. var index = this.morphTargetManagers.indexOf(toRemove);
  26453. if (index !== -1) {
  26454. // Remove from the scene if found
  26455. this.morphTargetManagers.splice(index, 1);
  26456. }
  26457. return index;
  26458. };
  26459. /**
  26460. * Remove a light for the list of scene's lights
  26461. * @param toRemove defines the light to remove
  26462. * @returns the index where the light was in the light list
  26463. */
  26464. Scene.prototype.removeLight = function (toRemove) {
  26465. var index = this.lights.indexOf(toRemove);
  26466. if (index !== -1) {
  26467. // Remove from meshes
  26468. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26469. var mesh = _a[_i];
  26470. mesh._removeLightSource(toRemove);
  26471. }
  26472. // Remove from the scene if mesh found
  26473. this.lights.splice(index, 1);
  26474. this.sortLightsByPriority();
  26475. }
  26476. this.onLightRemovedObservable.notifyObservers(toRemove);
  26477. return index;
  26478. };
  26479. /**
  26480. * Remove a camera for the list of scene's cameras
  26481. * @param toRemove defines the camera to remove
  26482. * @returns the index where the camera was in the camera list
  26483. */
  26484. Scene.prototype.removeCamera = function (toRemove) {
  26485. var index = this.cameras.indexOf(toRemove);
  26486. if (index !== -1) {
  26487. // Remove from the scene if mesh found
  26488. this.cameras.splice(index, 1);
  26489. }
  26490. // Remove from activeCameras
  26491. var index2 = this.activeCameras.indexOf(toRemove);
  26492. if (index2 !== -1) {
  26493. // Remove from the scene if mesh found
  26494. this.activeCameras.splice(index2, 1);
  26495. }
  26496. // Reset the activeCamera
  26497. if (this.activeCamera === toRemove) {
  26498. if (this.cameras.length > 0) {
  26499. this.activeCamera = this.cameras[0];
  26500. }
  26501. else {
  26502. this.activeCamera = null;
  26503. }
  26504. }
  26505. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26506. return index;
  26507. };
  26508. /**
  26509. * Remove a particle system for the list of scene's particle systems
  26510. * @param toRemove defines the particle system to remove
  26511. * @returns the index where the particle system was in the particle system list
  26512. */
  26513. Scene.prototype.removeParticleSystem = function (toRemove) {
  26514. var index = this.particleSystems.indexOf(toRemove);
  26515. if (index !== -1) {
  26516. this.particleSystems.splice(index, 1);
  26517. }
  26518. return index;
  26519. };
  26520. /**
  26521. * Remove a animation for the list of scene's animations
  26522. * @param toRemove defines the animation to remove
  26523. * @returns the index where the animation was in the animation list
  26524. */
  26525. Scene.prototype.removeAnimation = function (toRemove) {
  26526. var index = this.animations.indexOf(toRemove);
  26527. if (index !== -1) {
  26528. this.animations.splice(index, 1);
  26529. }
  26530. return index;
  26531. };
  26532. /**
  26533. * Removes the given animation group from this scene.
  26534. * @param toRemove The animation group to remove
  26535. * @returns The index of the removed animation group
  26536. */
  26537. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26538. var index = this.animationGroups.indexOf(toRemove);
  26539. if (index !== -1) {
  26540. this.animationGroups.splice(index, 1);
  26541. }
  26542. return index;
  26543. };
  26544. /**
  26545. * Removes the given multi-material from this scene.
  26546. * @param toRemove The multi-material to remove
  26547. * @returns The index of the removed multi-material
  26548. */
  26549. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26550. var index = this.multiMaterials.indexOf(toRemove);
  26551. if (index !== -1) {
  26552. this.multiMaterials.splice(index, 1);
  26553. }
  26554. return index;
  26555. };
  26556. /**
  26557. * Removes the given material from this scene.
  26558. * @param toRemove The material to remove
  26559. * @returns The index of the removed material
  26560. */
  26561. Scene.prototype.removeMaterial = function (toRemove) {
  26562. var index = this.materials.indexOf(toRemove);
  26563. if (index !== -1) {
  26564. this.materials.splice(index, 1);
  26565. }
  26566. return index;
  26567. };
  26568. /**
  26569. * Removes the given action manager from this scene.
  26570. * @param toRemove The action manager to remove
  26571. * @returns The index of the removed action manager
  26572. */
  26573. Scene.prototype.removeActionManager = function (toRemove) {
  26574. var index = this.actionManagers.indexOf(toRemove);
  26575. if (index !== -1) {
  26576. this.actionManagers.splice(index, 1);
  26577. }
  26578. return index;
  26579. };
  26580. /**
  26581. * Removes the given texture from this scene.
  26582. * @param toRemove The texture to remove
  26583. * @returns The index of the removed texture
  26584. */
  26585. Scene.prototype.removeTexture = function (toRemove) {
  26586. var index = this.textures.indexOf(toRemove);
  26587. if (index !== -1) {
  26588. this.textures.splice(index, 1);
  26589. }
  26590. return index;
  26591. };
  26592. /**
  26593. * Adds the given light to this scene
  26594. * @param newLight The light to add
  26595. */
  26596. Scene.prototype.addLight = function (newLight) {
  26597. this.lights.push(newLight);
  26598. this.sortLightsByPriority();
  26599. // Add light to all meshes (To support if the light is removed and then readded)
  26600. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26601. var mesh = _a[_i];
  26602. if (mesh._lightSources.indexOf(newLight) === -1) {
  26603. mesh._lightSources.push(newLight);
  26604. mesh._resyncLightSources();
  26605. }
  26606. }
  26607. this.onNewLightAddedObservable.notifyObservers(newLight);
  26608. };
  26609. /**
  26610. * Sorts the list list based on light priorities
  26611. */
  26612. Scene.prototype.sortLightsByPriority = function () {
  26613. if (this.requireLightSorting) {
  26614. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26615. }
  26616. };
  26617. /**
  26618. * Adds the given camera to this scene
  26619. * @param newCamera The camera to add
  26620. */
  26621. Scene.prototype.addCamera = function (newCamera) {
  26622. this.cameras.push(newCamera);
  26623. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26624. };
  26625. /**
  26626. * Adds the given skeleton to this scene
  26627. * @param newSkeleton The skeleton to add
  26628. */
  26629. Scene.prototype.addSkeleton = function (newSkeleton) {
  26630. this.skeletons.push(newSkeleton);
  26631. };
  26632. /**
  26633. * Adds the given particle system to this scene
  26634. * @param newParticleSystem The particle system to add
  26635. */
  26636. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26637. this.particleSystems.push(newParticleSystem);
  26638. };
  26639. /**
  26640. * Adds the given animation to this scene
  26641. * @param newAnimation The animation to add
  26642. */
  26643. Scene.prototype.addAnimation = function (newAnimation) {
  26644. this.animations.push(newAnimation);
  26645. };
  26646. /**
  26647. * Adds the given animation group to this scene.
  26648. * @param newAnimationGroup The animation group to add
  26649. */
  26650. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26651. this.animationGroups.push(newAnimationGroup);
  26652. };
  26653. /**
  26654. * Adds the given multi-material to this scene
  26655. * @param newMultiMaterial The multi-material to add
  26656. */
  26657. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26658. this.multiMaterials.push(newMultiMaterial);
  26659. };
  26660. /**
  26661. * Adds the given material to this scene
  26662. * @param newMaterial The material to add
  26663. */
  26664. Scene.prototype.addMaterial = function (newMaterial) {
  26665. this.materials.push(newMaterial);
  26666. };
  26667. /**
  26668. * Adds the given morph target to this scene
  26669. * @param newMorphTargetManager The morph target to add
  26670. */
  26671. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26672. this.morphTargetManagers.push(newMorphTargetManager);
  26673. };
  26674. /**
  26675. * Adds the given geometry to this scene
  26676. * @param newGeometry The geometry to add
  26677. */
  26678. Scene.prototype.addGeometry = function (newGeometry) {
  26679. this.geometries.push(newGeometry);
  26680. };
  26681. /**
  26682. * Adds the given action manager to this scene
  26683. * @param newActionManager The action manager to add
  26684. */
  26685. Scene.prototype.addActionManager = function (newActionManager) {
  26686. this.actionManagers.push(newActionManager);
  26687. };
  26688. /**
  26689. * Adds the given texture to this scene.
  26690. * @param newTexture The texture to add
  26691. */
  26692. Scene.prototype.addTexture = function (newTexture) {
  26693. this.textures.push(newTexture);
  26694. };
  26695. /**
  26696. * Switch active camera
  26697. * @param newCamera defines the new active camera
  26698. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26699. */
  26700. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26701. if (attachControl === void 0) { attachControl = true; }
  26702. var canvas = this._engine.getRenderingCanvas();
  26703. if (!canvas) {
  26704. return;
  26705. }
  26706. if (this.activeCamera) {
  26707. this.activeCamera.detachControl(canvas);
  26708. }
  26709. this.activeCamera = newCamera;
  26710. if (attachControl) {
  26711. newCamera.attachControl(canvas);
  26712. }
  26713. };
  26714. /**
  26715. * sets the active camera of the scene using its ID
  26716. * @param id defines the camera's ID
  26717. * @return the new active camera or null if none found.
  26718. */
  26719. Scene.prototype.setActiveCameraByID = function (id) {
  26720. var camera = this.getCameraByID(id);
  26721. if (camera) {
  26722. this.activeCamera = camera;
  26723. return camera;
  26724. }
  26725. return null;
  26726. };
  26727. /**
  26728. * sets the active camera of the scene using its name
  26729. * @param name defines the camera's name
  26730. * @returns the new active camera or null if none found.
  26731. */
  26732. Scene.prototype.setActiveCameraByName = function (name) {
  26733. var camera = this.getCameraByName(name);
  26734. if (camera) {
  26735. this.activeCamera = camera;
  26736. return camera;
  26737. }
  26738. return null;
  26739. };
  26740. /**
  26741. * get an animation group using its name
  26742. * @param name defines the material's name
  26743. * @return the animation group or null if none found.
  26744. */
  26745. Scene.prototype.getAnimationGroupByName = function (name) {
  26746. for (var index = 0; index < this.animationGroups.length; index++) {
  26747. if (this.animationGroups[index].name === name) {
  26748. return this.animationGroups[index];
  26749. }
  26750. }
  26751. return null;
  26752. };
  26753. /**
  26754. * get a material using its id
  26755. * @param id defines the material's ID
  26756. * @return the material or null if none found.
  26757. */
  26758. Scene.prototype.getMaterialByID = function (id) {
  26759. for (var index = 0; index < this.materials.length; index++) {
  26760. if (this.materials[index].id === id) {
  26761. return this.materials[index];
  26762. }
  26763. }
  26764. return null;
  26765. };
  26766. /**
  26767. * Gets a material using its name
  26768. * @param name defines the material's name
  26769. * @return the material or null if none found.
  26770. */
  26771. Scene.prototype.getMaterialByName = function (name) {
  26772. for (var index = 0; index < this.materials.length; index++) {
  26773. if (this.materials[index].name === name) {
  26774. return this.materials[index];
  26775. }
  26776. }
  26777. return null;
  26778. };
  26779. /**
  26780. * Gets a camera using its id
  26781. * @param id defines the id to look for
  26782. * @returns the camera or null if not found
  26783. */
  26784. Scene.prototype.getCameraByID = function (id) {
  26785. for (var index = 0; index < this.cameras.length; index++) {
  26786. if (this.cameras[index].id === id) {
  26787. return this.cameras[index];
  26788. }
  26789. }
  26790. return null;
  26791. };
  26792. /**
  26793. * Gets a camera using its unique id
  26794. * @param uniqueId defines the unique id to look for
  26795. * @returns the camera or null if not found
  26796. */
  26797. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26798. for (var index = 0; index < this.cameras.length; index++) {
  26799. if (this.cameras[index].uniqueId === uniqueId) {
  26800. return this.cameras[index];
  26801. }
  26802. }
  26803. return null;
  26804. };
  26805. /**
  26806. * Gets a camera using its name
  26807. * @param name defines the camera's name
  26808. * @return the camera or null if none found.
  26809. */
  26810. Scene.prototype.getCameraByName = function (name) {
  26811. for (var index = 0; index < this.cameras.length; index++) {
  26812. if (this.cameras[index].name === name) {
  26813. return this.cameras[index];
  26814. }
  26815. }
  26816. return null;
  26817. };
  26818. /**
  26819. * Gets a bone using its id
  26820. * @param id defines the bone's id
  26821. * @return the bone or null if not found
  26822. */
  26823. Scene.prototype.getBoneByID = function (id) {
  26824. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26825. var skeleton = this.skeletons[skeletonIndex];
  26826. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26827. if (skeleton.bones[boneIndex].id === id) {
  26828. return skeleton.bones[boneIndex];
  26829. }
  26830. }
  26831. }
  26832. return null;
  26833. };
  26834. /**
  26835. * Gets a bone using its id
  26836. * @param name defines the bone's name
  26837. * @return the bone or null if not found
  26838. */
  26839. Scene.prototype.getBoneByName = function (name) {
  26840. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26841. var skeleton = this.skeletons[skeletonIndex];
  26842. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26843. if (skeleton.bones[boneIndex].name === name) {
  26844. return skeleton.bones[boneIndex];
  26845. }
  26846. }
  26847. }
  26848. return null;
  26849. };
  26850. /**
  26851. * Gets a light node using its name
  26852. * @param name defines the the light's name
  26853. * @return the light or null if none found.
  26854. */
  26855. Scene.prototype.getLightByName = function (name) {
  26856. for (var index = 0; index < this.lights.length; index++) {
  26857. if (this.lights[index].name === name) {
  26858. return this.lights[index];
  26859. }
  26860. }
  26861. return null;
  26862. };
  26863. /**
  26864. * Gets a light node using its id
  26865. * @param id defines the light's id
  26866. * @return the light or null if none found.
  26867. */
  26868. Scene.prototype.getLightByID = function (id) {
  26869. for (var index = 0; index < this.lights.length; index++) {
  26870. if (this.lights[index].id === id) {
  26871. return this.lights[index];
  26872. }
  26873. }
  26874. return null;
  26875. };
  26876. /**
  26877. * Gets a light node using its scene-generated unique ID
  26878. * @param uniqueId defines the light's unique id
  26879. * @return the light or null if none found.
  26880. */
  26881. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26882. for (var index = 0; index < this.lights.length; index++) {
  26883. if (this.lights[index].uniqueId === uniqueId) {
  26884. return this.lights[index];
  26885. }
  26886. }
  26887. return null;
  26888. };
  26889. /**
  26890. * Gets a particle system by id
  26891. * @param id defines the particle system id
  26892. * @return the corresponding system or null if none found
  26893. */
  26894. Scene.prototype.getParticleSystemByID = function (id) {
  26895. for (var index = 0; index < this.particleSystems.length; index++) {
  26896. if (this.particleSystems[index].id === id) {
  26897. return this.particleSystems[index];
  26898. }
  26899. }
  26900. return null;
  26901. };
  26902. /**
  26903. * Gets a geometry using its ID
  26904. * @param id defines the geometry's id
  26905. * @return the geometry or null if none found.
  26906. */
  26907. Scene.prototype.getGeometryByID = function (id) {
  26908. for (var index = 0; index < this.geometries.length; index++) {
  26909. if (this.geometries[index].id === id) {
  26910. return this.geometries[index];
  26911. }
  26912. }
  26913. return null;
  26914. };
  26915. /**
  26916. * Add a new geometry to this scene
  26917. * @param geometry defines the geometry to be added to the scene.
  26918. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26919. * @return a boolean defining if the geometry was added or not
  26920. */
  26921. Scene.prototype.pushGeometry = function (geometry, force) {
  26922. if (!force && this.getGeometryByID(geometry.id)) {
  26923. return false;
  26924. }
  26925. this.geometries.push(geometry);
  26926. //notify the collision coordinator
  26927. if (this.collisionCoordinator) {
  26928. this.collisionCoordinator.onGeometryAdded(geometry);
  26929. }
  26930. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26931. return true;
  26932. };
  26933. /**
  26934. * Removes an existing geometry
  26935. * @param geometry defines the geometry to be removed from the scene
  26936. * @return a boolean defining if the geometry was removed or not
  26937. */
  26938. Scene.prototype.removeGeometry = function (geometry) {
  26939. var index = this.geometries.indexOf(geometry);
  26940. if (index > -1) {
  26941. this.geometries.splice(index, 1);
  26942. //notify the collision coordinator
  26943. if (this.collisionCoordinator) {
  26944. this.collisionCoordinator.onGeometryDeleted(geometry);
  26945. }
  26946. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26947. return true;
  26948. }
  26949. return false;
  26950. };
  26951. /**
  26952. * Gets the list of geometries attached to the scene
  26953. * @returns an array of Geometry
  26954. */
  26955. Scene.prototype.getGeometries = function () {
  26956. return this.geometries;
  26957. };
  26958. /**
  26959. * Gets the first added mesh found of a given ID
  26960. * @param id defines the id to search for
  26961. * @return the mesh found or null if not found at all
  26962. */
  26963. Scene.prototype.getMeshByID = function (id) {
  26964. for (var index = 0; index < this.meshes.length; index++) {
  26965. if (this.meshes[index].id === id) {
  26966. return this.meshes[index];
  26967. }
  26968. }
  26969. return null;
  26970. };
  26971. /**
  26972. * Gets a list of meshes using their id
  26973. * @param id defines the id to search for
  26974. * @returns a list of meshes
  26975. */
  26976. Scene.prototype.getMeshesByID = function (id) {
  26977. return this.meshes.filter(function (m) {
  26978. return m.id === id;
  26979. });
  26980. };
  26981. /**
  26982. * Gets the first added transform node found of a given ID
  26983. * @param id defines the id to search for
  26984. * @return the found transform node or null if not found at all.
  26985. */
  26986. Scene.prototype.getTransformNodeByID = function (id) {
  26987. for (var index = 0; index < this.transformNodes.length; index++) {
  26988. if (this.transformNodes[index].id === id) {
  26989. return this.transformNodes[index];
  26990. }
  26991. }
  26992. return null;
  26993. };
  26994. /**
  26995. * Gets a list of transform nodes using their id
  26996. * @param id defines the id to search for
  26997. * @returns a list of transform nodes
  26998. */
  26999. Scene.prototype.getTransformNodesByID = function (id) {
  27000. return this.transformNodes.filter(function (m) {
  27001. return m.id === id;
  27002. });
  27003. };
  27004. /**
  27005. * Gets a mesh with its auto-generated unique id
  27006. * @param uniqueId defines the unique id to search for
  27007. * @return the found mesh or null if not found at all.
  27008. */
  27009. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27010. for (var index = 0; index < this.meshes.length; index++) {
  27011. if (this.meshes[index].uniqueId === uniqueId) {
  27012. return this.meshes[index];
  27013. }
  27014. }
  27015. return null;
  27016. };
  27017. /**
  27018. * Gets a the last added mesh using a given id
  27019. * @param id defines the id to search for
  27020. * @return the found mesh or null if not found at all.
  27021. */
  27022. Scene.prototype.getLastMeshByID = function (id) {
  27023. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27024. if (this.meshes[index].id === id) {
  27025. return this.meshes[index];
  27026. }
  27027. }
  27028. return null;
  27029. };
  27030. /**
  27031. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27032. * @param id defines the id to search for
  27033. * @return the found node or null if not found at all
  27034. */
  27035. Scene.prototype.getLastEntryByID = function (id) {
  27036. var index;
  27037. for (index = this.meshes.length - 1; index >= 0; index--) {
  27038. if (this.meshes[index].id === id) {
  27039. return this.meshes[index];
  27040. }
  27041. }
  27042. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27043. if (this.transformNodes[index].id === id) {
  27044. return this.transformNodes[index];
  27045. }
  27046. }
  27047. for (index = this.cameras.length - 1; index >= 0; index--) {
  27048. if (this.cameras[index].id === id) {
  27049. return this.cameras[index];
  27050. }
  27051. }
  27052. for (index = this.lights.length - 1; index >= 0; index--) {
  27053. if (this.lights[index].id === id) {
  27054. return this.lights[index];
  27055. }
  27056. }
  27057. return null;
  27058. };
  27059. /**
  27060. * Gets a node (Mesh, Camera, Light) using a given id
  27061. * @param id defines the id to search for
  27062. * @return the found node or null if not found at all
  27063. */
  27064. Scene.prototype.getNodeByID = function (id) {
  27065. var mesh = this.getMeshByID(id);
  27066. if (mesh) {
  27067. return mesh;
  27068. }
  27069. var light = this.getLightByID(id);
  27070. if (light) {
  27071. return light;
  27072. }
  27073. var camera = this.getCameraByID(id);
  27074. if (camera) {
  27075. return camera;
  27076. }
  27077. var bone = this.getBoneByID(id);
  27078. return bone;
  27079. };
  27080. /**
  27081. * Gets a node (Mesh, Camera, Light) using a given name
  27082. * @param name defines the name to search for
  27083. * @return the found node or null if not found at all.
  27084. */
  27085. Scene.prototype.getNodeByName = function (name) {
  27086. var mesh = this.getMeshByName(name);
  27087. if (mesh) {
  27088. return mesh;
  27089. }
  27090. var light = this.getLightByName(name);
  27091. if (light) {
  27092. return light;
  27093. }
  27094. var camera = this.getCameraByName(name);
  27095. if (camera) {
  27096. return camera;
  27097. }
  27098. var bone = this.getBoneByName(name);
  27099. return bone;
  27100. };
  27101. /**
  27102. * Gets a mesh using a given name
  27103. * @param name defines the name to search for
  27104. * @return the found mesh or null if not found at all.
  27105. */
  27106. Scene.prototype.getMeshByName = function (name) {
  27107. for (var index = 0; index < this.meshes.length; index++) {
  27108. if (this.meshes[index].name === name) {
  27109. return this.meshes[index];
  27110. }
  27111. }
  27112. return null;
  27113. };
  27114. /**
  27115. * Gets a transform node using a given name
  27116. * @param name defines the name to search for
  27117. * @return the found transform node or null if not found at all.
  27118. */
  27119. Scene.prototype.getTransformNodeByName = function (name) {
  27120. for (var index = 0; index < this.transformNodes.length; index++) {
  27121. if (this.transformNodes[index].name === name) {
  27122. return this.transformNodes[index];
  27123. }
  27124. }
  27125. return null;
  27126. };
  27127. /**
  27128. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27129. * @param id defines the id to search for
  27130. * @return the found skeleton or null if not found at all.
  27131. */
  27132. Scene.prototype.getLastSkeletonByID = function (id) {
  27133. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27134. if (this.skeletons[index].id === id) {
  27135. return this.skeletons[index];
  27136. }
  27137. }
  27138. return null;
  27139. };
  27140. /**
  27141. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27142. * @param id defines the id to search for
  27143. * @return the found skeleton or null if not found at all.
  27144. */
  27145. Scene.prototype.getSkeletonById = function (id) {
  27146. for (var index = 0; index < this.skeletons.length; index++) {
  27147. if (this.skeletons[index].id === id) {
  27148. return this.skeletons[index];
  27149. }
  27150. }
  27151. return null;
  27152. };
  27153. /**
  27154. * Gets a skeleton using a given name
  27155. * @param name defines the name to search for
  27156. * @return the found skeleton or null if not found at all.
  27157. */
  27158. Scene.prototype.getSkeletonByName = function (name) {
  27159. for (var index = 0; index < this.skeletons.length; index++) {
  27160. if (this.skeletons[index].name === name) {
  27161. return this.skeletons[index];
  27162. }
  27163. }
  27164. return null;
  27165. };
  27166. /**
  27167. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27168. * @param id defines the id to search for
  27169. * @return the found morph target manager or null if not found at all.
  27170. */
  27171. Scene.prototype.getMorphTargetManagerById = function (id) {
  27172. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27173. if (this.morphTargetManagers[index].uniqueId === id) {
  27174. return this.morphTargetManagers[index];
  27175. }
  27176. }
  27177. return null;
  27178. };
  27179. /**
  27180. * Gets a boolean indicating if the given mesh is active
  27181. * @param mesh defines the mesh to look for
  27182. * @returns true if the mesh is in the active list
  27183. */
  27184. Scene.prototype.isActiveMesh = function (mesh) {
  27185. return (this._activeMeshes.indexOf(mesh) !== -1);
  27186. };
  27187. Object.defineProperty(Scene.prototype, "uid", {
  27188. /**
  27189. * Return a unique id as a string which can serve as an identifier for the scene
  27190. */
  27191. get: function () {
  27192. if (!this._uid) {
  27193. this._uid = BABYLON.Tools.RandomId();
  27194. }
  27195. return this._uid;
  27196. },
  27197. enumerable: true,
  27198. configurable: true
  27199. });
  27200. /**
  27201. * Add an externaly attached data from its key.
  27202. * This method call will fail and return false, if such key already exists.
  27203. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27204. * @param key the unique key that identifies the data
  27205. * @param data the data object to associate to the key for this Engine instance
  27206. * @return true if no such key were already present and the data was added successfully, false otherwise
  27207. */
  27208. Scene.prototype.addExternalData = function (key, data) {
  27209. if (!this._externalData) {
  27210. this._externalData = new BABYLON.StringDictionary();
  27211. }
  27212. return this._externalData.add(key, data);
  27213. };
  27214. /**
  27215. * Get an externaly attached data from its key
  27216. * @param key the unique key that identifies the data
  27217. * @return the associated data, if present (can be null), or undefined if not present
  27218. */
  27219. Scene.prototype.getExternalData = function (key) {
  27220. if (!this._externalData) {
  27221. return null;
  27222. }
  27223. return this._externalData.get(key);
  27224. };
  27225. /**
  27226. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27227. * @param key the unique key that identifies the data
  27228. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27229. * @return the associated data, can be null if the factory returned null.
  27230. */
  27231. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27232. if (!this._externalData) {
  27233. this._externalData = new BABYLON.StringDictionary();
  27234. }
  27235. return this._externalData.getOrAddWithFactory(key, factory);
  27236. };
  27237. /**
  27238. * Remove an externaly attached data from the Engine instance
  27239. * @param key the unique key that identifies the data
  27240. * @return true if the data was successfully removed, false if it doesn't exist
  27241. */
  27242. Scene.prototype.removeExternalData = function (key) {
  27243. return this._externalData.remove(key);
  27244. };
  27245. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27246. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27247. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27248. var step = _a[_i];
  27249. step.action(mesh, subMesh);
  27250. }
  27251. var material = subMesh.getMaterial();
  27252. if (material !== null && material !== undefined) {
  27253. // Render targets
  27254. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27255. if (this._processedMaterials.indexOf(material) === -1) {
  27256. this._processedMaterials.push(material);
  27257. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27258. }
  27259. }
  27260. // Dispatch
  27261. this._activeIndices.addCount(subMesh.indexCount, false);
  27262. this._renderingManager.dispatch(subMesh, mesh, material);
  27263. }
  27264. }
  27265. };
  27266. /**
  27267. * Clear the processed materials smart array preventing retention point in material dispose.
  27268. */
  27269. Scene.prototype.freeProcessedMaterials = function () {
  27270. this._processedMaterials.dispose();
  27271. };
  27272. /**
  27273. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27274. */
  27275. Scene.prototype.freeActiveMeshes = function () {
  27276. this._activeMeshes.dispose();
  27277. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27278. this.activeCamera._activeMeshes.dispose();
  27279. }
  27280. if (this.activeCameras) {
  27281. for (var i = 0; i < this.activeCameras.length; i++) {
  27282. var activeCamera = this.activeCameras[i];
  27283. if (activeCamera && activeCamera._activeMeshes) {
  27284. activeCamera._activeMeshes.dispose();
  27285. }
  27286. }
  27287. }
  27288. };
  27289. /**
  27290. * Clear the info related to rendering groups preventing retention points during dispose.
  27291. */
  27292. Scene.prototype.freeRenderingGroups = function () {
  27293. if (this._renderingManager) {
  27294. this._renderingManager.freeRenderingGroups();
  27295. }
  27296. if (this.textures) {
  27297. for (var i = 0; i < this.textures.length; i++) {
  27298. var texture = this.textures[i];
  27299. if (texture && texture.renderList) {
  27300. texture.freeRenderingGroups();
  27301. }
  27302. }
  27303. }
  27304. };
  27305. /** @hidden */
  27306. Scene.prototype._isInIntermediateRendering = function () {
  27307. return this._intermediateRendering;
  27308. };
  27309. /**
  27310. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27311. * @returns the current scene
  27312. */
  27313. Scene.prototype.freezeActiveMeshes = function () {
  27314. if (!this.activeCamera) {
  27315. return this;
  27316. }
  27317. if (!this._frustumPlanes) {
  27318. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27319. }
  27320. this._evaluateActiveMeshes();
  27321. this._activeMeshesFrozen = true;
  27322. return this;
  27323. };
  27324. /**
  27325. * Use this function to restart evaluating active meshes on every frame
  27326. * @returns the current scene
  27327. */
  27328. Scene.prototype.unfreezeActiveMeshes = function () {
  27329. this._activeMeshesFrozen = false;
  27330. return this;
  27331. };
  27332. Scene.prototype._evaluateActiveMeshes = function () {
  27333. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27334. return;
  27335. }
  27336. if (!this.activeCamera) {
  27337. return;
  27338. }
  27339. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27340. this.activeCamera._activeMeshes.reset();
  27341. this._activeMeshes.reset();
  27342. this._renderingManager.reset();
  27343. this._processedMaterials.reset();
  27344. this._activeParticleSystems.reset();
  27345. this._activeSkeletons.reset();
  27346. this._softwareSkinnedMeshes.reset();
  27347. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27348. var step = _a[_i];
  27349. step.action();
  27350. }
  27351. // Determine mesh candidates
  27352. var meshes = this.getActiveMeshCandidates();
  27353. // Check each mesh
  27354. var len = meshes.length;
  27355. for (var i = 0; i < len; i++) {
  27356. var mesh = meshes.data[i];
  27357. if (mesh.isBlocked) {
  27358. continue;
  27359. }
  27360. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27361. if (!mesh.isReady() || !mesh.isEnabled()) {
  27362. continue;
  27363. }
  27364. mesh.computeWorldMatrix();
  27365. // Intersections
  27366. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27367. this._meshesForIntersections.pushNoDuplicate(mesh);
  27368. }
  27369. // Switch to current LOD
  27370. var meshLOD = mesh.getLOD(this.activeCamera);
  27371. if (meshLOD === undefined || meshLOD === null) {
  27372. continue;
  27373. }
  27374. mesh._preActivate();
  27375. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27376. this._activeMeshes.push(mesh);
  27377. this.activeCamera._activeMeshes.push(mesh);
  27378. mesh._activate(this._renderId);
  27379. if (meshLOD !== mesh) {
  27380. meshLOD._activate(this._renderId);
  27381. }
  27382. this._activeMesh(mesh, meshLOD);
  27383. }
  27384. }
  27385. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27386. // Particle systems
  27387. if (this.particlesEnabled) {
  27388. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27389. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27390. var particleSystem = this.particleSystems[particleIndex];
  27391. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27392. continue;
  27393. }
  27394. var emitter = particleSystem.emitter;
  27395. if (!emitter.position || emitter.isEnabled()) {
  27396. this._activeParticleSystems.push(particleSystem);
  27397. particleSystem.animate();
  27398. this._renderingManager.dispatchParticles(particleSystem);
  27399. }
  27400. }
  27401. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27402. }
  27403. };
  27404. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27405. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27406. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27407. mesh.skeleton.prepare();
  27408. }
  27409. if (!mesh.computeBonesUsingShaders) {
  27410. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27411. }
  27412. }
  27413. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27414. var step = _a[_i];
  27415. step.action(sourceMesh, mesh);
  27416. }
  27417. if (mesh !== undefined && mesh !== null
  27418. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27419. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27420. var len = subMeshes.length;
  27421. for (var i = 0; i < len; i++) {
  27422. var subMesh = subMeshes.data[i];
  27423. this._evaluateSubMesh(subMesh, mesh);
  27424. }
  27425. }
  27426. };
  27427. /**
  27428. * Update the transform matrix to update from the current active camera
  27429. * @param force defines a boolean used to force the update even if cache is up to date
  27430. */
  27431. Scene.prototype.updateTransformMatrix = function (force) {
  27432. if (!this.activeCamera) {
  27433. return;
  27434. }
  27435. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27436. };
  27437. /**
  27438. * 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)
  27439. * @param alternateCamera defines the camera to use
  27440. */
  27441. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27442. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27443. };
  27444. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27445. if (camera && camera._skipRendering) {
  27446. return;
  27447. }
  27448. var engine = this._engine;
  27449. this.activeCamera = camera;
  27450. if (!this.activeCamera)
  27451. throw new Error("Active camera not set");
  27452. // Viewport
  27453. engine.setViewport(this.activeCamera.viewport);
  27454. // Camera
  27455. this.resetCachedMaterial();
  27456. this._renderId++;
  27457. this.updateTransformMatrix();
  27458. if (camera._alternateCamera) {
  27459. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27460. this._alternateRendering = true;
  27461. }
  27462. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27463. // Meshes
  27464. this._evaluateActiveMeshes();
  27465. // Software skinning
  27466. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27467. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27468. mesh.applySkeleton(mesh.skeleton);
  27469. }
  27470. // Render targets
  27471. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27472. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27473. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27474. }
  27475. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27476. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27477. }
  27478. // Collects render targets from external components.
  27479. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27480. var step = _a[_i];
  27481. step.action(this._renderTargets);
  27482. }
  27483. if (this.renderTargetsEnabled) {
  27484. this._intermediateRendering = true;
  27485. if (this._renderTargets.length > 0) {
  27486. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27487. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27488. var renderTarget = this._renderTargets.data[renderIndex];
  27489. if (renderTarget._shouldRender()) {
  27490. this._renderId++;
  27491. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27492. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27493. }
  27494. }
  27495. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27496. this._renderId++;
  27497. }
  27498. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27499. var step = _c[_b];
  27500. step.action(this.activeCamera);
  27501. }
  27502. this._intermediateRendering = false;
  27503. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27504. }
  27505. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27506. // Prepare Frame
  27507. if (this.postProcessManager) {
  27508. this.postProcessManager._prepareFrame();
  27509. }
  27510. // Before Camera Draw
  27511. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27512. var step = _e[_d];
  27513. step.action(this.activeCamera);
  27514. }
  27515. // Render
  27516. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27517. this._renderingManager.render(null, null, true, true);
  27518. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27519. // After Camera Draw
  27520. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27521. var step = _g[_f];
  27522. step.action(this.activeCamera);
  27523. }
  27524. // Finalize frame
  27525. if (this.postProcessManager) {
  27526. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27527. }
  27528. // Reset some special arrays
  27529. this._renderTargets.reset();
  27530. this._alternateRendering = false;
  27531. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27532. };
  27533. Scene.prototype._processSubCameras = function (camera) {
  27534. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27535. this._renderForCamera(camera);
  27536. return;
  27537. }
  27538. // rig cameras
  27539. for (var index = 0; index < camera._rigCameras.length; index++) {
  27540. this._renderForCamera(camera._rigCameras[index], camera);
  27541. }
  27542. this.activeCamera = camera;
  27543. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27544. };
  27545. Scene.prototype._checkIntersections = function () {
  27546. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27547. var sourceMesh = this._meshesForIntersections.data[index];
  27548. if (!sourceMesh.actionManager) {
  27549. continue;
  27550. }
  27551. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27552. var action = sourceMesh.actionManager.actions[actionIndex];
  27553. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27554. var parameters = action.getTriggerParameter();
  27555. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27556. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27557. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27558. if (areIntersecting && currentIntersectionInProgress === -1) {
  27559. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27560. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27561. sourceMesh._intersectionsInProgress.push(otherMesh);
  27562. }
  27563. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27564. sourceMesh._intersectionsInProgress.push(otherMesh);
  27565. }
  27566. }
  27567. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27568. //They intersected, and now they don't.
  27569. //is this trigger an exit trigger? execute an event.
  27570. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27571. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27572. }
  27573. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27574. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27575. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27576. return otherMesh === parameterMesh;
  27577. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27578. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27579. }
  27580. }
  27581. }
  27582. }
  27583. }
  27584. };
  27585. /** @hidden */
  27586. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27587. // Do nothing. Code will be replaced if physics engine component is referenced
  27588. };
  27589. /**
  27590. * Render the scene
  27591. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27592. */
  27593. Scene.prototype.render = function (updateCameras) {
  27594. if (updateCameras === void 0) { updateCameras = true; }
  27595. if (this.isDisposed) {
  27596. return;
  27597. }
  27598. this._frameId++;
  27599. // Register components that have been associated lately to the scene.
  27600. this._registerTransientComponents();
  27601. this._activeParticles.fetchNewFrame();
  27602. this._totalVertices.fetchNewFrame();
  27603. this._activeIndices.fetchNewFrame();
  27604. this._activeBones.fetchNewFrame();
  27605. this._meshesForIntersections.reset();
  27606. this.resetCachedMaterial();
  27607. this.onBeforeAnimationsObservable.notifyObservers(this);
  27608. // Actions
  27609. if (this.actionManager) {
  27610. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27611. }
  27612. if (this._engine.isDeterministicLockStep()) {
  27613. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27614. var defaultFPS = (60.0 / 1000.0);
  27615. var defaultFrameTime = this.getDeterministicFrameTime();
  27616. var stepsTaken = 0;
  27617. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27618. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27619. internalSteps = Math.min(internalSteps, maxSubSteps);
  27620. do {
  27621. this.onBeforeStepObservable.notifyObservers(this);
  27622. // Animations
  27623. this._animationRatio = defaultFrameTime * defaultFPS;
  27624. this._animate();
  27625. this.onAfterAnimationsObservable.notifyObservers(this);
  27626. // Physics
  27627. this._advancePhysicsEngineStep(defaultFrameTime);
  27628. this.onAfterStepObservable.notifyObservers(this);
  27629. this._currentStepId++;
  27630. stepsTaken++;
  27631. deltaTime -= defaultFrameTime;
  27632. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27633. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27634. }
  27635. else {
  27636. // Animations
  27637. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27638. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27639. this._animate();
  27640. this.onAfterAnimationsObservable.notifyObservers(this);
  27641. // Physics
  27642. this._advancePhysicsEngineStep(deltaTime);
  27643. }
  27644. // Before camera update steps
  27645. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27646. var step = _a[_i];
  27647. step.action();
  27648. }
  27649. // Update Cameras
  27650. if (updateCameras) {
  27651. if (this.activeCameras.length > 0) {
  27652. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27653. var camera = this.activeCameras[cameraIndex];
  27654. camera.update();
  27655. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27656. // rig cameras
  27657. for (var index = 0; index < camera._rigCameras.length; index++) {
  27658. camera._rigCameras[index].update();
  27659. }
  27660. }
  27661. }
  27662. }
  27663. else if (this.activeCamera) {
  27664. this.activeCamera.update();
  27665. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27666. // rig cameras
  27667. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27668. this.activeCamera._rigCameras[index].update();
  27669. }
  27670. }
  27671. }
  27672. }
  27673. // Before render
  27674. this.onBeforeRenderObservable.notifyObservers(this);
  27675. // Customs render targets
  27676. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27677. var engine = this.getEngine();
  27678. var currentActiveCamera = this.activeCamera;
  27679. if (this.renderTargetsEnabled) {
  27680. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27681. this._intermediateRendering = true;
  27682. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27683. var renderTarget = this.customRenderTargets[customIndex];
  27684. if (renderTarget._shouldRender()) {
  27685. this._renderId++;
  27686. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27687. if (!this.activeCamera)
  27688. throw new Error("Active camera not set");
  27689. // Viewport
  27690. engine.setViewport(this.activeCamera.viewport);
  27691. // Camera
  27692. this.updateTransformMatrix();
  27693. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27694. }
  27695. }
  27696. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27697. this._intermediateRendering = false;
  27698. this._renderId++;
  27699. }
  27700. // Restore back buffer
  27701. if (this.customRenderTargets.length > 0) {
  27702. engine.restoreDefaultFramebuffer();
  27703. }
  27704. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27705. this.activeCamera = currentActiveCamera;
  27706. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27707. var step = _c[_b];
  27708. step.action();
  27709. }
  27710. // Clear
  27711. if (this.autoClearDepthAndStencil || this.autoClear) {
  27712. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27713. }
  27714. // Collects render targets from external components.
  27715. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27716. var step = _e[_d];
  27717. step.action(this._renderTargets);
  27718. }
  27719. // Multi-cameras?
  27720. if (this.activeCameras.length > 0) {
  27721. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27722. if (cameraIndex > 0) {
  27723. this._engine.clear(null, false, true, true);
  27724. }
  27725. this._processSubCameras(this.activeCameras[cameraIndex]);
  27726. }
  27727. }
  27728. else {
  27729. if (!this.activeCamera) {
  27730. throw new Error("No camera defined");
  27731. }
  27732. this._processSubCameras(this.activeCamera);
  27733. }
  27734. // Intersection checks
  27735. this._checkIntersections();
  27736. // Executes the after render stage actions.
  27737. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  27738. var step = _g[_f];
  27739. step.action();
  27740. }
  27741. // After render
  27742. if (this.afterRender) {
  27743. this.afterRender();
  27744. }
  27745. this.onAfterRenderObservable.notifyObservers(this);
  27746. // Cleaning
  27747. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27748. var data = this._toBeDisposed.data[index];
  27749. if (data) {
  27750. data.dispose();
  27751. }
  27752. }
  27753. this._toBeDisposed.reset();
  27754. if (this.dumpNextRenderTargets) {
  27755. this.dumpNextRenderTargets = false;
  27756. }
  27757. this._activeBones.addCount(0, true);
  27758. this._activeIndices.addCount(0, true);
  27759. this._activeParticles.addCount(0, true);
  27760. };
  27761. /**
  27762. * Freeze all materials
  27763. * A frozen material will not be updatable but should be faster to render
  27764. */
  27765. Scene.prototype.freezeMaterials = function () {
  27766. for (var i = 0; i < this.materials.length; i++) {
  27767. this.materials[i].freeze();
  27768. }
  27769. };
  27770. /**
  27771. * Unfreeze all materials
  27772. * A frozen material will not be updatable but should be faster to render
  27773. */
  27774. Scene.prototype.unfreezeMaterials = function () {
  27775. for (var i = 0; i < this.materials.length; i++) {
  27776. this.materials[i].unfreeze();
  27777. }
  27778. };
  27779. /**
  27780. * Releases all held ressources
  27781. */
  27782. Scene.prototype.dispose = function () {
  27783. this.beforeRender = null;
  27784. this.afterRender = null;
  27785. this.skeletons = [];
  27786. this.morphTargetManagers = [];
  27787. this._transientComponents = [];
  27788. this._isReadyForMeshStage.clear();
  27789. this._beforeEvaluateActiveMeshStage.clear();
  27790. this._evaluateSubMeshStage.clear();
  27791. this._activeMeshStage.clear();
  27792. this._cameraDrawRenderTargetStage.clear();
  27793. this._beforeCameraDrawStage.clear();
  27794. this._beforeRenderingGroupDrawStage.clear();
  27795. this._beforeRenderingMeshStage.clear();
  27796. this._afterRenderingMeshStage.clear();
  27797. this._afterRenderingGroupDrawStage.clear();
  27798. this._afterCameraDrawStage.clear();
  27799. this._afterRenderStage.clear();
  27800. this._beforeCameraUpdateStage.clear();
  27801. this._beforeClearStage.clear();
  27802. this._gatherRenderTargetsStage.clear();
  27803. this._gatherActiveCameraRenderTargetsStage.clear();
  27804. this._pointerMoveStage.clear();
  27805. this._pointerDownStage.clear();
  27806. this._pointerUpStage.clear();
  27807. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27808. var component = _a[_i];
  27809. component.dispose();
  27810. }
  27811. this.importedMeshesFiles = new Array();
  27812. this.stopAllAnimations();
  27813. this.resetCachedMaterial();
  27814. // Smart arrays
  27815. if (this.activeCamera) {
  27816. this.activeCamera._activeMeshes.dispose();
  27817. this.activeCamera = null;
  27818. }
  27819. this._activeMeshes.dispose();
  27820. this._renderingManager.dispose();
  27821. this._processedMaterials.dispose();
  27822. this._activeParticleSystems.dispose();
  27823. this._activeSkeletons.dispose();
  27824. this._softwareSkinnedMeshes.dispose();
  27825. this._renderTargets.dispose();
  27826. this._registeredForLateAnimationBindings.dispose();
  27827. this._meshesForIntersections.dispose();
  27828. this._toBeDisposed.dispose();
  27829. // Abort active requests
  27830. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27831. var request = _c[_b];
  27832. request.abort();
  27833. }
  27834. // Events
  27835. this.onDisposeObservable.notifyObservers(this);
  27836. this.onDisposeObservable.clear();
  27837. this.onBeforeRenderObservable.clear();
  27838. this.onAfterRenderObservable.clear();
  27839. this.onBeforeRenderTargetsRenderObservable.clear();
  27840. this.onAfterRenderTargetsRenderObservable.clear();
  27841. this.onAfterStepObservable.clear();
  27842. this.onBeforeStepObservable.clear();
  27843. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27844. this.onAfterActiveMeshesEvaluationObservable.clear();
  27845. this.onBeforeParticlesRenderingObservable.clear();
  27846. this.onAfterParticlesRenderingObservable.clear();
  27847. this.onBeforeDrawPhaseObservable.clear();
  27848. this.onAfterDrawPhaseObservable.clear();
  27849. this.onBeforeAnimationsObservable.clear();
  27850. this.onAfterAnimationsObservable.clear();
  27851. this.onDataLoadedObservable.clear();
  27852. this.onBeforeRenderingGroupObservable.clear();
  27853. this.onAfterRenderingGroupObservable.clear();
  27854. this.onMeshImportedObservable.clear();
  27855. this.detachControl();
  27856. // Detach cameras
  27857. var canvas = this._engine.getRenderingCanvas();
  27858. if (canvas) {
  27859. var index;
  27860. for (index = 0; index < this.cameras.length; index++) {
  27861. this.cameras[index].detachControl(canvas);
  27862. }
  27863. }
  27864. // Release animation groups
  27865. while (this.animationGroups.length) {
  27866. this.animationGroups[0].dispose();
  27867. }
  27868. // Release lights
  27869. while (this.lights.length) {
  27870. this.lights[0].dispose();
  27871. }
  27872. // Release meshes
  27873. while (this.meshes.length) {
  27874. this.meshes[0].dispose(true);
  27875. }
  27876. while (this.transformNodes.length) {
  27877. this.removeTransformNode(this.transformNodes[0]);
  27878. }
  27879. // Release cameras
  27880. while (this.cameras.length) {
  27881. this.cameras[0].dispose();
  27882. }
  27883. // Release materials
  27884. if (this.defaultMaterial) {
  27885. this.defaultMaterial.dispose();
  27886. }
  27887. while (this.multiMaterials.length) {
  27888. this.multiMaterials[0].dispose();
  27889. }
  27890. while (this.materials.length) {
  27891. this.materials[0].dispose();
  27892. }
  27893. // Release particles
  27894. while (this.particleSystems.length) {
  27895. this.particleSystems[0].dispose();
  27896. }
  27897. // Release postProcesses
  27898. while (this.postProcesses.length) {
  27899. this.postProcesses[0].dispose();
  27900. }
  27901. // Release textures
  27902. while (this.textures.length) {
  27903. this.textures[0].dispose();
  27904. }
  27905. // Release UBO
  27906. this._sceneUbo.dispose();
  27907. if (this._alternateSceneUbo) {
  27908. this._alternateSceneUbo.dispose();
  27909. }
  27910. // Post-processes
  27911. this.postProcessManager.dispose();
  27912. // Remove from engine
  27913. index = this._engine.scenes.indexOf(this);
  27914. if (index > -1) {
  27915. this._engine.scenes.splice(index, 1);
  27916. }
  27917. this._engine.wipeCaches(true);
  27918. this._isDisposed = true;
  27919. };
  27920. Object.defineProperty(Scene.prototype, "isDisposed", {
  27921. /**
  27922. * Gets if the scene is already disposed
  27923. */
  27924. get: function () {
  27925. return this._isDisposed;
  27926. },
  27927. enumerable: true,
  27928. configurable: true
  27929. });
  27930. /**
  27931. * Call this function to reduce memory footprint of the scene.
  27932. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  27933. */
  27934. Scene.prototype.clearCachedVertexData = function () {
  27935. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27936. var mesh = this.meshes[meshIndex];
  27937. var geometry = mesh.geometry;
  27938. if (geometry) {
  27939. geometry._indices = [];
  27940. for (var vbName in geometry._vertexBuffers) {
  27941. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  27942. continue;
  27943. }
  27944. geometry._vertexBuffers[vbName]._buffer._data = null;
  27945. }
  27946. }
  27947. }
  27948. };
  27949. /**
  27950. * This function will remove the local cached buffer data from texture.
  27951. * It will save memory but will prevent the texture from being rebuilt
  27952. */
  27953. Scene.prototype.cleanCachedTextureBuffer = function () {
  27954. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27955. var baseTexture = _a[_i];
  27956. var buffer = baseTexture._buffer;
  27957. if (buffer) {
  27958. baseTexture._buffer = null;
  27959. }
  27960. }
  27961. };
  27962. /**
  27963. * Get the world extend vectors with an optional filter
  27964. *
  27965. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27966. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27967. */
  27968. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27969. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27970. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27971. filterPredicate = filterPredicate || (function () { return true; });
  27972. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27973. mesh.computeWorldMatrix(true);
  27974. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27975. return;
  27976. }
  27977. var boundingInfo = mesh.getBoundingInfo();
  27978. var minBox = boundingInfo.boundingBox.minimumWorld;
  27979. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27980. BABYLON.Tools.CheckExtends(minBox, min, max);
  27981. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27982. });
  27983. return {
  27984. min: min,
  27985. max: max
  27986. };
  27987. };
  27988. // Picking
  27989. /**
  27990. * Creates a ray that can be used to pick in the scene
  27991. * @param x defines the x coordinate of the origin (on-screen)
  27992. * @param y defines the y coordinate of the origin (on-screen)
  27993. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27994. * @param camera defines the camera to use for the picking
  27995. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27996. * @returns a Ray
  27997. */
  27998. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27999. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28000. var result = BABYLON.Ray.Zero();
  28001. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28002. return result;
  28003. };
  28004. /**
  28005. * Creates a ray that can be used to pick in the scene
  28006. * @param x defines the x coordinate of the origin (on-screen)
  28007. * @param y defines the y coordinate of the origin (on-screen)
  28008. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28009. * @param result defines the ray where to store the picking ray
  28010. * @param camera defines the camera to use for the picking
  28011. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28012. * @returns the current scene
  28013. */
  28014. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28015. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28016. var engine = this._engine;
  28017. if (!camera) {
  28018. if (!this.activeCamera)
  28019. throw new Error("Active camera not set");
  28020. camera = this.activeCamera;
  28021. }
  28022. var cameraViewport = camera.viewport;
  28023. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28024. // Moving coordinates to local viewport world
  28025. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28026. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28027. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28028. return this;
  28029. };
  28030. /**
  28031. * Creates a ray that can be used to pick in the scene
  28032. * @param x defines the x coordinate of the origin (on-screen)
  28033. * @param y defines the y coordinate of the origin (on-screen)
  28034. * @param camera defines the camera to use for the picking
  28035. * @returns a Ray
  28036. */
  28037. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28038. var result = BABYLON.Ray.Zero();
  28039. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28040. return result;
  28041. };
  28042. /**
  28043. * Creates a ray that can be used to pick in the scene
  28044. * @param x defines the x coordinate of the origin (on-screen)
  28045. * @param y defines the y coordinate of the origin (on-screen)
  28046. * @param result defines the ray where to store the picking ray
  28047. * @param camera defines the camera to use for the picking
  28048. * @returns the current scene
  28049. */
  28050. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28051. if (!BABYLON.PickingInfo) {
  28052. return this;
  28053. }
  28054. var engine = this._engine;
  28055. if (!camera) {
  28056. if (!this.activeCamera)
  28057. throw new Error("Active camera not set");
  28058. camera = this.activeCamera;
  28059. }
  28060. var cameraViewport = camera.viewport;
  28061. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28062. var identity = BABYLON.Matrix.Identity();
  28063. // Moving coordinates to local viewport world
  28064. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28065. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28066. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28067. return this;
  28068. };
  28069. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28070. if (!BABYLON.PickingInfo) {
  28071. return null;
  28072. }
  28073. var pickingInfo = null;
  28074. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28075. var mesh = this.meshes[meshIndex];
  28076. if (predicate) {
  28077. if (!predicate(mesh)) {
  28078. continue;
  28079. }
  28080. }
  28081. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28082. continue;
  28083. }
  28084. var world = mesh.getWorldMatrix();
  28085. var ray = rayFunction(world);
  28086. var result = mesh.intersects(ray, fastCheck);
  28087. if (!result || !result.hit)
  28088. continue;
  28089. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28090. continue;
  28091. pickingInfo = result;
  28092. if (fastCheck) {
  28093. break;
  28094. }
  28095. }
  28096. return pickingInfo || new BABYLON.PickingInfo();
  28097. };
  28098. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28099. if (!BABYLON.PickingInfo) {
  28100. return null;
  28101. }
  28102. var pickingInfos = new Array();
  28103. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28104. var mesh = this.meshes[meshIndex];
  28105. if (predicate) {
  28106. if (!predicate(mesh)) {
  28107. continue;
  28108. }
  28109. }
  28110. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28111. continue;
  28112. }
  28113. var world = mesh.getWorldMatrix();
  28114. var ray = rayFunction(world);
  28115. var result = mesh.intersects(ray, false);
  28116. if (!result || !result.hit)
  28117. continue;
  28118. pickingInfos.push(result);
  28119. }
  28120. return pickingInfos;
  28121. };
  28122. /** Launch a ray to try to pick a mesh in the scene
  28123. * @param x position on screen
  28124. * @param y position on screen
  28125. * @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
  28126. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28127. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28128. * @returns a PickingInfo
  28129. */
  28130. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28131. var _this = this;
  28132. if (!BABYLON.PickingInfo) {
  28133. return null;
  28134. }
  28135. var result = this._internalPick(function (world) {
  28136. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28137. return _this._tempPickingRay;
  28138. }, predicate, fastCheck);
  28139. if (result) {
  28140. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28141. }
  28142. return result;
  28143. };
  28144. /** Use the given ray to pick a mesh in the scene
  28145. * @param ray The ray to use to pick meshes
  28146. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  28147. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28148. * @returns a PickingInfo
  28149. */
  28150. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28151. var _this = this;
  28152. var result = this._internalPick(function (world) {
  28153. if (!_this._pickWithRayInverseMatrix) {
  28154. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28155. }
  28156. world.invertToRef(_this._pickWithRayInverseMatrix);
  28157. if (!_this._cachedRayForTransform) {
  28158. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28159. }
  28160. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28161. return _this._cachedRayForTransform;
  28162. }, predicate, fastCheck);
  28163. if (result) {
  28164. result.ray = ray;
  28165. }
  28166. return result;
  28167. };
  28168. /**
  28169. * Launch a ray to try to pick a mesh in the scene
  28170. * @param x X position on screen
  28171. * @param y Y position on screen
  28172. * @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
  28173. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28174. * @returns an array of PickingInfo
  28175. */
  28176. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28177. var _this = this;
  28178. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28179. };
  28180. /**
  28181. * Launch a ray to try to pick a mesh in the scene
  28182. * @param ray Ray to use
  28183. * @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
  28184. * @returns an array of PickingInfo
  28185. */
  28186. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28187. var _this = this;
  28188. return this._internalMultiPick(function (world) {
  28189. if (!_this._pickWithRayInverseMatrix) {
  28190. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28191. }
  28192. world.invertToRef(_this._pickWithRayInverseMatrix);
  28193. if (!_this._cachedRayForTransform) {
  28194. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28195. }
  28196. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28197. return _this._cachedRayForTransform;
  28198. }, predicate);
  28199. };
  28200. /**
  28201. * Force the value of meshUnderPointer
  28202. * @param mesh defines the mesh to use
  28203. */
  28204. Scene.prototype.setPointerOverMesh = function (mesh) {
  28205. if (this._pointerOverMesh === mesh) {
  28206. return;
  28207. }
  28208. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28209. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28210. }
  28211. this._pointerOverMesh = mesh;
  28212. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28213. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28214. }
  28215. };
  28216. /**
  28217. * Gets the mesh under the pointer
  28218. * @returns a Mesh or null if no mesh is under the pointer
  28219. */
  28220. Scene.prototype.getPointerOverMesh = function () {
  28221. return this._pointerOverMesh;
  28222. };
  28223. // Misc.
  28224. /** @hidden */
  28225. Scene.prototype._rebuildGeometries = function () {
  28226. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28227. var geometry = _a[_i];
  28228. geometry._rebuild();
  28229. }
  28230. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28231. var mesh = _c[_b];
  28232. mesh._rebuild();
  28233. }
  28234. if (this.postProcessManager) {
  28235. this.postProcessManager._rebuild();
  28236. }
  28237. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28238. var component = _e[_d];
  28239. component.rebuild();
  28240. }
  28241. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28242. var system = _g[_f];
  28243. system.rebuild();
  28244. }
  28245. };
  28246. /** @hidden */
  28247. Scene.prototype._rebuildTextures = function () {
  28248. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28249. var texture = _a[_i];
  28250. texture._rebuild();
  28251. }
  28252. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28253. };
  28254. // Tags
  28255. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28256. if (tagsQuery === undefined) {
  28257. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28258. return list;
  28259. }
  28260. var listByTags = [];
  28261. forEach = forEach || (function (item) { return; });
  28262. for (var i in list) {
  28263. var item = list[i];
  28264. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28265. listByTags.push(item);
  28266. forEach(item);
  28267. }
  28268. }
  28269. return listByTags;
  28270. };
  28271. /**
  28272. * Get a list of meshes by tags
  28273. * @param tagsQuery defines the tags query to use
  28274. * @param forEach defines a predicate used to filter results
  28275. * @returns an array of Mesh
  28276. */
  28277. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28278. return this._getByTags(this.meshes, tagsQuery, forEach);
  28279. };
  28280. /**
  28281. * Get a list of cameras by tags
  28282. * @param tagsQuery defines the tags query to use
  28283. * @param forEach defines a predicate used to filter results
  28284. * @returns an array of Camera
  28285. */
  28286. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28287. return this._getByTags(this.cameras, tagsQuery, forEach);
  28288. };
  28289. /**
  28290. * Get a list of lights by tags
  28291. * @param tagsQuery defines the tags query to use
  28292. * @param forEach defines a predicate used to filter results
  28293. * @returns an array of Light
  28294. */
  28295. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28296. return this._getByTags(this.lights, tagsQuery, forEach);
  28297. };
  28298. /**
  28299. * Get a list of materials by tags
  28300. * @param tagsQuery defines the tags query to use
  28301. * @param forEach defines a predicate used to filter results
  28302. * @returns an array of Material
  28303. */
  28304. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28305. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28306. };
  28307. /**
  28308. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28309. * This allowed control for front to back rendering or reversly depending of the special needs.
  28310. *
  28311. * @param renderingGroupId The rendering group id corresponding to its index
  28312. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28313. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28314. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28315. */
  28316. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28317. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28318. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28319. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28320. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28321. };
  28322. /**
  28323. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28324. *
  28325. * @param renderingGroupId The rendering group id corresponding to its index
  28326. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28327. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28328. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28329. */
  28330. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28331. if (depth === void 0) { depth = true; }
  28332. if (stencil === void 0) { stencil = true; }
  28333. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28334. };
  28335. /**
  28336. * Gets the current auto clear configuration for one rendering group of the rendering
  28337. * manager.
  28338. * @param index the rendering group index to get the information for
  28339. * @returns The auto clear setup for the requested rendering group
  28340. */
  28341. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28342. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28343. };
  28344. /**
  28345. * Will flag all materials as dirty to trigger new shader compilation
  28346. * @param flag defines the flag used to specify which material part must be marked as dirty
  28347. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28348. */
  28349. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28350. if (this.blockMaterialDirtyMechanism) {
  28351. return;
  28352. }
  28353. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28354. var material = _a[_i];
  28355. if (predicate && !predicate(material)) {
  28356. continue;
  28357. }
  28358. material.markAsDirty(flag);
  28359. }
  28360. };
  28361. /** @hidden */
  28362. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28363. var _this = this;
  28364. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28365. this._activeRequests.push(request);
  28366. request.onCompleteObservable.add(function (request) {
  28367. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28368. });
  28369. return request;
  28370. };
  28371. /** @hidden */
  28372. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28373. var _this = this;
  28374. return new Promise(function (resolve, reject) {
  28375. _this._loadFile(url, function (data) {
  28376. resolve(data);
  28377. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28378. reject(exception);
  28379. });
  28380. });
  28381. };
  28382. // Statics
  28383. Scene._uniqueIdCounter = 0;
  28384. /** The fog is deactivated */
  28385. Scene.FOGMODE_NONE = 0;
  28386. /** The fog density is following an exponential function */
  28387. Scene.FOGMODE_EXP = 1;
  28388. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28389. Scene.FOGMODE_EXP2 = 2;
  28390. /** The fog density is following a linear function. */
  28391. Scene.FOGMODE_LINEAR = 3;
  28392. /**
  28393. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28394. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28395. */
  28396. Scene.MinDeltaTime = 1.0;
  28397. /**
  28398. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28399. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28400. */
  28401. Scene.MaxDeltaTime = 1000.0;
  28402. /** The distance in pixel that you have to move to prevent some events */
  28403. Scene.DragMovementThreshold = 10; // in pixels
  28404. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28405. Scene.LongPressDelay = 500; // in milliseconds
  28406. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28407. Scene.DoubleClickDelay = 300; // in milliseconds
  28408. /** If you need to check double click without raising a single click at first click, enable this flag */
  28409. Scene.ExclusiveDoubleClickMode = false;
  28410. return Scene;
  28411. }(BABYLON.AbstractScene));
  28412. BABYLON.Scene = Scene;
  28413. })(BABYLON || (BABYLON = {}));
  28414. //# sourceMappingURL=babylon.scene.js.map
  28415. var BABYLON;
  28416. (function (BABYLON) {
  28417. /**
  28418. * Set of assets to keep when moving a scene into an asset container.
  28419. */
  28420. var KeepAssets = /** @class */ (function (_super) {
  28421. __extends(KeepAssets, _super);
  28422. function KeepAssets() {
  28423. return _super !== null && _super.apply(this, arguments) || this;
  28424. }
  28425. return KeepAssets;
  28426. }(BABYLON.AbstractScene));
  28427. BABYLON.KeepAssets = KeepAssets;
  28428. /**
  28429. * Container with a set of assets that can be added or removed from a scene.
  28430. */
  28431. var AssetContainer = /** @class */ (function (_super) {
  28432. __extends(AssetContainer, _super);
  28433. /**
  28434. * Instantiates an AssetContainer.
  28435. * @param scene The scene the AssetContainer belongs to.
  28436. */
  28437. function AssetContainer(scene) {
  28438. var _this = _super.call(this) || this;
  28439. _this.scene = scene;
  28440. return _this;
  28441. }
  28442. /**
  28443. * Adds all the assets from the container to the scene.
  28444. */
  28445. AssetContainer.prototype.addAllToScene = function () {
  28446. var _this = this;
  28447. this.cameras.forEach(function (o) {
  28448. _this.scene.addCamera(o);
  28449. });
  28450. this.lights.forEach(function (o) {
  28451. _this.scene.addLight(o);
  28452. });
  28453. this.meshes.forEach(function (o) {
  28454. _this.scene.addMesh(o);
  28455. });
  28456. this.skeletons.forEach(function (o) {
  28457. _this.scene.addSkeleton(o);
  28458. });
  28459. this.animations.forEach(function (o) {
  28460. _this.scene.addAnimation(o);
  28461. });
  28462. this.animationGroups.forEach(function (o) {
  28463. _this.scene.addAnimationGroup(o);
  28464. });
  28465. this.multiMaterials.forEach(function (o) {
  28466. _this.scene.addMultiMaterial(o);
  28467. });
  28468. this.materials.forEach(function (o) {
  28469. _this.scene.addMaterial(o);
  28470. });
  28471. this.morphTargetManagers.forEach(function (o) {
  28472. _this.scene.addMorphTargetManager(o);
  28473. });
  28474. this.geometries.forEach(function (o) {
  28475. _this.scene.addGeometry(o);
  28476. });
  28477. this.transformNodes.forEach(function (o) {
  28478. _this.scene.addTransformNode(o);
  28479. });
  28480. this.actionManagers.forEach(function (o) {
  28481. _this.scene.addActionManager(o);
  28482. });
  28483. this.textures.forEach(function (o) {
  28484. _this.scene.addTexture(o);
  28485. });
  28486. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28487. var component = _a[_i];
  28488. component.addFromContainer(this.scene);
  28489. }
  28490. };
  28491. /**
  28492. * Removes all the assets in the container from the scene
  28493. */
  28494. AssetContainer.prototype.removeAllFromScene = function () {
  28495. var _this = this;
  28496. this.cameras.forEach(function (o) {
  28497. _this.scene.removeCamera(o);
  28498. });
  28499. this.lights.forEach(function (o) {
  28500. _this.scene.removeLight(o);
  28501. });
  28502. this.meshes.forEach(function (o) {
  28503. _this.scene.removeMesh(o);
  28504. });
  28505. this.skeletons.forEach(function (o) {
  28506. _this.scene.removeSkeleton(o);
  28507. });
  28508. this.animations.forEach(function (o) {
  28509. _this.scene.removeAnimation(o);
  28510. });
  28511. this.animationGroups.forEach(function (o) {
  28512. _this.scene.removeAnimationGroup(o);
  28513. });
  28514. this.multiMaterials.forEach(function (o) {
  28515. _this.scene.removeMultiMaterial(o);
  28516. });
  28517. this.materials.forEach(function (o) {
  28518. _this.scene.removeMaterial(o);
  28519. });
  28520. this.morphTargetManagers.forEach(function (o) {
  28521. _this.scene.removeMorphTargetManager(o);
  28522. });
  28523. this.geometries.forEach(function (o) {
  28524. _this.scene.removeGeometry(o);
  28525. });
  28526. this.transformNodes.forEach(function (o) {
  28527. _this.scene.removeTransformNode(o);
  28528. });
  28529. this.actionManagers.forEach(function (o) {
  28530. _this.scene.removeActionManager(o);
  28531. });
  28532. this.textures.forEach(function (o) {
  28533. _this.scene.removeTexture(o);
  28534. });
  28535. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28536. var component = _a[_i];
  28537. component.removeFromContainer(this.scene);
  28538. }
  28539. };
  28540. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28541. if (!sourceAssets) {
  28542. return;
  28543. }
  28544. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28545. var asset = sourceAssets_1[_i];
  28546. var move = true;
  28547. if (keepAssets) {
  28548. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28549. var keepAsset = keepAssets_1[_a];
  28550. if (asset === keepAsset) {
  28551. move = false;
  28552. break;
  28553. }
  28554. }
  28555. }
  28556. if (move) {
  28557. targetAssets.push(asset);
  28558. }
  28559. }
  28560. };
  28561. /**
  28562. * Removes all the assets contained in the scene and adds them to the container.
  28563. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28564. */
  28565. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28566. if (keepAssets === undefined) {
  28567. keepAssets = new KeepAssets();
  28568. }
  28569. for (var key in this) {
  28570. if (this.hasOwnProperty(key)) {
  28571. this[key] = this[key] || [];
  28572. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28573. }
  28574. }
  28575. this.removeAllFromScene();
  28576. };
  28577. /**
  28578. * 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.
  28579. * @returns the root mesh
  28580. */
  28581. AssetContainer.prototype.createRootMesh = function () {
  28582. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28583. this.meshes.forEach(function (m) {
  28584. if (!m.parent) {
  28585. rootMesh.addChild(m);
  28586. }
  28587. });
  28588. this.meshes.unshift(rootMesh);
  28589. return rootMesh;
  28590. };
  28591. return AssetContainer;
  28592. }(BABYLON.AbstractScene));
  28593. BABYLON.AssetContainer = AssetContainer;
  28594. })(BABYLON || (BABYLON = {}));
  28595. //# sourceMappingURL=babylon.assetContainer.js.map
  28596. var BABYLON;
  28597. (function (BABYLON) {
  28598. var Buffer = /** @class */ (function () {
  28599. /**
  28600. * Constructor
  28601. * @param engine the engine
  28602. * @param data the data to use for this buffer
  28603. * @param updatable whether the data is updatable
  28604. * @param stride the stride (optional)
  28605. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28606. * @param instanced whether the buffer is instanced (optional)
  28607. * @param useBytes set to true if the stride in in bytes (optional)
  28608. */
  28609. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28610. if (stride === void 0) { stride = 0; }
  28611. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28612. if (instanced === void 0) { instanced = false; }
  28613. if (useBytes === void 0) { useBytes = false; }
  28614. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28615. this._engine = engine.getScene().getEngine();
  28616. }
  28617. else {
  28618. this._engine = engine;
  28619. }
  28620. this._updatable = updatable;
  28621. this._instanced = instanced;
  28622. this._data = data;
  28623. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28624. if (!postponeInternalCreation) { // by default
  28625. this.create();
  28626. }
  28627. }
  28628. /**
  28629. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28630. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28631. * @param offset defines offset in the buffer (0 by default)
  28632. * @param size defines the size in floats of attributes (position is 3 for instance)
  28633. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28634. * @param instanced defines if the vertex buffer contains indexed data
  28635. * @param useBytes defines if the offset and stride are in bytes
  28636. * @returns the new vertex buffer
  28637. */
  28638. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28639. if (useBytes === void 0) { useBytes = false; }
  28640. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28641. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28642. // a lot of these parameters are ignored as they are overriden by the buffer
  28643. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28644. };
  28645. // Properties
  28646. Buffer.prototype.isUpdatable = function () {
  28647. return this._updatable;
  28648. };
  28649. Buffer.prototype.getData = function () {
  28650. return this._data;
  28651. };
  28652. Buffer.prototype.getBuffer = function () {
  28653. return this._buffer;
  28654. };
  28655. /**
  28656. * Gets the stride in float32 units (i.e. byte stride / 4).
  28657. * May not be an integer if the byte stride is not divisible by 4.
  28658. * DEPRECATED. Use byteStride instead.
  28659. * @returns the stride in float32 units
  28660. */
  28661. Buffer.prototype.getStrideSize = function () {
  28662. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28663. };
  28664. // Methods
  28665. Buffer.prototype.create = function (data) {
  28666. if (data === void 0) { data = null; }
  28667. if (!data && this._buffer) {
  28668. return; // nothing to do
  28669. }
  28670. data = data || this._data;
  28671. if (!data) {
  28672. return;
  28673. }
  28674. if (!this._buffer) { // create buffer
  28675. if (this._updatable) {
  28676. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28677. this._data = data;
  28678. }
  28679. else {
  28680. this._buffer = this._engine.createVertexBuffer(data);
  28681. }
  28682. }
  28683. else if (this._updatable) { // update buffer
  28684. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28685. this._data = data;
  28686. }
  28687. };
  28688. /** @hidden */
  28689. Buffer.prototype._rebuild = function () {
  28690. this._buffer = null;
  28691. this.create(this._data);
  28692. };
  28693. Buffer.prototype.update = function (data) {
  28694. this.create(data);
  28695. };
  28696. /**
  28697. * Updates the data directly.
  28698. * @param data the new data
  28699. * @param offset the new offset
  28700. * @param vertexCount the vertex count (optional)
  28701. * @param useBytes set to true if the offset is in bytes
  28702. */
  28703. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28704. if (useBytes === void 0) { useBytes = false; }
  28705. if (!this._buffer) {
  28706. return;
  28707. }
  28708. if (this._updatable) { // update buffer
  28709. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28710. this._data = null;
  28711. }
  28712. };
  28713. Buffer.prototype.dispose = function () {
  28714. if (!this._buffer) {
  28715. return;
  28716. }
  28717. if (this._engine._releaseBuffer(this._buffer)) {
  28718. this._buffer = null;
  28719. }
  28720. };
  28721. return Buffer;
  28722. }());
  28723. BABYLON.Buffer = Buffer;
  28724. })(BABYLON || (BABYLON = {}));
  28725. //# sourceMappingURL=babylon.buffer.js.map
  28726. var BABYLON;
  28727. (function (BABYLON) {
  28728. var VertexBuffer = /** @class */ (function () {
  28729. /**
  28730. * Constructor
  28731. * @param engine the engine
  28732. * @param data the data to use for this vertex buffer
  28733. * @param kind the vertex buffer kind
  28734. * @param updatable whether the data is updatable
  28735. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28736. * @param stride the stride (optional)
  28737. * @param instanced whether the buffer is instanced (optional)
  28738. * @param offset the offset of the data (optional)
  28739. * @param size the number of components (optional)
  28740. * @param type the type of the component (optional)
  28741. * @param normalized whether the data contains normalized data (optional)
  28742. * @param useBytes set to true if stride and offset are in bytes (optional)
  28743. */
  28744. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28745. if (normalized === void 0) { normalized = false; }
  28746. if (useBytes === void 0) { useBytes = false; }
  28747. if (data instanceof BABYLON.Buffer) {
  28748. this._buffer = data;
  28749. this._ownsBuffer = false;
  28750. }
  28751. else {
  28752. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28753. this._ownsBuffer = true;
  28754. }
  28755. this._kind = kind;
  28756. if (type == undefined) {
  28757. var data_1 = this.getData();
  28758. this.type = VertexBuffer.FLOAT;
  28759. if (data_1 instanceof Int8Array)
  28760. this.type = VertexBuffer.BYTE;
  28761. else if (data_1 instanceof Uint8Array)
  28762. this.type = VertexBuffer.UNSIGNED_BYTE;
  28763. else if (data_1 instanceof Int16Array)
  28764. this.type = VertexBuffer.SHORT;
  28765. else if (data_1 instanceof Uint16Array)
  28766. this.type = VertexBuffer.UNSIGNED_SHORT;
  28767. else if (data_1 instanceof Int32Array)
  28768. this.type = VertexBuffer.INT;
  28769. else if (data_1 instanceof Uint32Array)
  28770. this.type = VertexBuffer.UNSIGNED_INT;
  28771. }
  28772. else {
  28773. this.type = type;
  28774. }
  28775. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28776. if (useBytes) {
  28777. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28778. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28779. this.byteOffset = offset || 0;
  28780. }
  28781. else {
  28782. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28783. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28784. this.byteOffset = (offset || 0) * typeByteLength;
  28785. }
  28786. this.normalized = normalized;
  28787. this._instanced = instanced !== undefined ? instanced : false;
  28788. this._instanceDivisor = instanced ? 1 : 0;
  28789. }
  28790. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28791. /**
  28792. * Gets or sets the instance divisor when in instanced mode
  28793. */
  28794. get: function () {
  28795. return this._instanceDivisor;
  28796. },
  28797. set: function (value) {
  28798. this._instanceDivisor = value;
  28799. if (value == 0) {
  28800. this._instanced = false;
  28801. }
  28802. else {
  28803. this._instanced = true;
  28804. }
  28805. },
  28806. enumerable: true,
  28807. configurable: true
  28808. });
  28809. /** @hidden */
  28810. VertexBuffer.prototype._rebuild = function () {
  28811. if (!this._buffer) {
  28812. return;
  28813. }
  28814. this._buffer._rebuild();
  28815. };
  28816. /**
  28817. * Returns the kind of the VertexBuffer (string).
  28818. */
  28819. VertexBuffer.prototype.getKind = function () {
  28820. return this._kind;
  28821. };
  28822. // Properties
  28823. /**
  28824. * Boolean : is the VertexBuffer updatable ?
  28825. */
  28826. VertexBuffer.prototype.isUpdatable = function () {
  28827. return this._buffer.isUpdatable();
  28828. };
  28829. /**
  28830. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28831. */
  28832. VertexBuffer.prototype.getData = function () {
  28833. return this._buffer.getData();
  28834. };
  28835. /**
  28836. * Returns the WebGLBuffer associated to the VertexBuffer.
  28837. */
  28838. VertexBuffer.prototype.getBuffer = function () {
  28839. return this._buffer.getBuffer();
  28840. };
  28841. /**
  28842. * Returns the stride as a multiple of the type byte length.
  28843. * DEPRECATED. Use byteStride instead.
  28844. */
  28845. VertexBuffer.prototype.getStrideSize = function () {
  28846. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28847. };
  28848. /**
  28849. * Returns the offset as a multiple of the type byte length.
  28850. * DEPRECATED. Use byteOffset instead.
  28851. */
  28852. VertexBuffer.prototype.getOffset = function () {
  28853. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28854. };
  28855. /**
  28856. * Returns the number of components per vertex attribute (integer).
  28857. */
  28858. VertexBuffer.prototype.getSize = function () {
  28859. return this._size;
  28860. };
  28861. /**
  28862. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28863. */
  28864. VertexBuffer.prototype.getIsInstanced = function () {
  28865. return this._instanced;
  28866. };
  28867. /**
  28868. * Returns the instancing divisor, zero for non-instanced (integer).
  28869. */
  28870. VertexBuffer.prototype.getInstanceDivisor = function () {
  28871. return this._instanceDivisor;
  28872. };
  28873. // Methods
  28874. /**
  28875. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28876. * Returns the created WebGLBuffer.
  28877. */
  28878. VertexBuffer.prototype.create = function (data) {
  28879. return this._buffer.create(data);
  28880. };
  28881. /**
  28882. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28883. * This function will create a new buffer if the current one is not updatable
  28884. * Returns the updated WebGLBuffer.
  28885. */
  28886. VertexBuffer.prototype.update = function (data) {
  28887. return this._buffer.update(data);
  28888. };
  28889. /**
  28890. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28891. * Returns the directly updated WebGLBuffer.
  28892. * @param data the new data
  28893. * @param offset the new offset
  28894. * @param useBytes set to true if the offset is in bytes
  28895. */
  28896. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  28897. if (useBytes === void 0) { useBytes = false; }
  28898. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  28899. };
  28900. /**
  28901. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28902. */
  28903. VertexBuffer.prototype.dispose = function () {
  28904. if (this._ownsBuffer) {
  28905. this._buffer.dispose();
  28906. }
  28907. };
  28908. /**
  28909. * Enumerates each value of this vertex buffer as numbers.
  28910. * @param count the number of values to enumerate
  28911. * @param callback the callback function called for each value
  28912. */
  28913. VertexBuffer.prototype.forEach = function (count, callback) {
  28914. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28915. };
  28916. Object.defineProperty(VertexBuffer, "PositionKind", {
  28917. get: function () {
  28918. return VertexBuffer._PositionKind;
  28919. },
  28920. enumerable: true,
  28921. configurable: true
  28922. });
  28923. Object.defineProperty(VertexBuffer, "NormalKind", {
  28924. get: function () {
  28925. return VertexBuffer._NormalKind;
  28926. },
  28927. enumerable: true,
  28928. configurable: true
  28929. });
  28930. Object.defineProperty(VertexBuffer, "TangentKind", {
  28931. get: function () {
  28932. return VertexBuffer._TangentKind;
  28933. },
  28934. enumerable: true,
  28935. configurable: true
  28936. });
  28937. Object.defineProperty(VertexBuffer, "UVKind", {
  28938. get: function () {
  28939. return VertexBuffer._UVKind;
  28940. },
  28941. enumerable: true,
  28942. configurable: true
  28943. });
  28944. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28945. get: function () {
  28946. return VertexBuffer._UV2Kind;
  28947. },
  28948. enumerable: true,
  28949. configurable: true
  28950. });
  28951. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28952. get: function () {
  28953. return VertexBuffer._UV3Kind;
  28954. },
  28955. enumerable: true,
  28956. configurable: true
  28957. });
  28958. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28959. get: function () {
  28960. return VertexBuffer._UV4Kind;
  28961. },
  28962. enumerable: true,
  28963. configurable: true
  28964. });
  28965. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28966. get: function () {
  28967. return VertexBuffer._UV5Kind;
  28968. },
  28969. enumerable: true,
  28970. configurable: true
  28971. });
  28972. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28973. get: function () {
  28974. return VertexBuffer._UV6Kind;
  28975. },
  28976. enumerable: true,
  28977. configurable: true
  28978. });
  28979. Object.defineProperty(VertexBuffer, "ColorKind", {
  28980. get: function () {
  28981. return VertexBuffer._ColorKind;
  28982. },
  28983. enumerable: true,
  28984. configurable: true
  28985. });
  28986. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28987. get: function () {
  28988. return VertexBuffer._MatricesIndicesKind;
  28989. },
  28990. enumerable: true,
  28991. configurable: true
  28992. });
  28993. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  28994. get: function () {
  28995. return VertexBuffer._MatricesWeightsKind;
  28996. },
  28997. enumerable: true,
  28998. configurable: true
  28999. });
  29000. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29001. get: function () {
  29002. return VertexBuffer._MatricesIndicesExtraKind;
  29003. },
  29004. enumerable: true,
  29005. configurable: true
  29006. });
  29007. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29008. get: function () {
  29009. return VertexBuffer._MatricesWeightsExtraKind;
  29010. },
  29011. enumerable: true,
  29012. configurable: true
  29013. });
  29014. /**
  29015. * Deduces the stride given a kind.
  29016. * @param kind The kind string to deduce
  29017. * @returns The deduced stride
  29018. */
  29019. VertexBuffer.DeduceStride = function (kind) {
  29020. switch (kind) {
  29021. case VertexBuffer.UVKind:
  29022. case VertexBuffer.UV2Kind:
  29023. case VertexBuffer.UV3Kind:
  29024. case VertexBuffer.UV4Kind:
  29025. case VertexBuffer.UV5Kind:
  29026. case VertexBuffer.UV6Kind:
  29027. return 2;
  29028. case VertexBuffer.NormalKind:
  29029. case VertexBuffer.PositionKind:
  29030. return 3;
  29031. case VertexBuffer.ColorKind:
  29032. case VertexBuffer.MatricesIndicesKind:
  29033. case VertexBuffer.MatricesIndicesExtraKind:
  29034. case VertexBuffer.MatricesWeightsKind:
  29035. case VertexBuffer.MatricesWeightsExtraKind:
  29036. case VertexBuffer.TangentKind:
  29037. return 4;
  29038. default:
  29039. throw new Error("Invalid kind '" + kind + "'");
  29040. }
  29041. };
  29042. /**
  29043. * Gets the byte length of the given type.
  29044. * @param type the type
  29045. * @returns the number of bytes
  29046. */
  29047. VertexBuffer.GetTypeByteLength = function (type) {
  29048. switch (type) {
  29049. case VertexBuffer.BYTE:
  29050. case VertexBuffer.UNSIGNED_BYTE:
  29051. return 1;
  29052. case VertexBuffer.SHORT:
  29053. case VertexBuffer.UNSIGNED_SHORT:
  29054. return 2;
  29055. case VertexBuffer.INT:
  29056. case VertexBuffer.FLOAT:
  29057. return 4;
  29058. default:
  29059. throw new Error("Invalid type '" + type + "'");
  29060. }
  29061. };
  29062. /**
  29063. * Enumerates each value of the given parameters as numbers.
  29064. * @param data the data to enumerate
  29065. * @param byteOffset the byte offset of the data
  29066. * @param byteStride the byte stride of the data
  29067. * @param componentCount the number of components per element
  29068. * @param componentType the type of the component
  29069. * @param count the total number of components
  29070. * @param normalized whether the data is normalized
  29071. * @param callback the callback function called for each value
  29072. */
  29073. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29074. if (data instanceof Array) {
  29075. var offset = byteOffset / 4;
  29076. var stride = byteStride / 4;
  29077. for (var index = 0; index < count; index += componentCount) {
  29078. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29079. callback(data[offset + componentIndex], index + componentIndex);
  29080. }
  29081. offset += stride;
  29082. }
  29083. }
  29084. else {
  29085. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29086. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29087. for (var index = 0; index < count; index += componentCount) {
  29088. var componentByteOffset = byteOffset;
  29089. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29090. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29091. callback(value, index + componentIndex);
  29092. componentByteOffset += componentByteLength;
  29093. }
  29094. byteOffset += byteStride;
  29095. }
  29096. }
  29097. };
  29098. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29099. switch (type) {
  29100. case VertexBuffer.BYTE: {
  29101. var value = dataView.getInt8(byteOffset);
  29102. if (normalized) {
  29103. value = Math.max(value / 127, -1);
  29104. }
  29105. return value;
  29106. }
  29107. case VertexBuffer.UNSIGNED_BYTE: {
  29108. var value = dataView.getUint8(byteOffset);
  29109. if (normalized) {
  29110. value = value / 255;
  29111. }
  29112. return value;
  29113. }
  29114. case VertexBuffer.SHORT: {
  29115. var value = dataView.getInt16(byteOffset, true);
  29116. if (normalized) {
  29117. value = Math.max(value / 16383, -1);
  29118. }
  29119. return value;
  29120. }
  29121. case VertexBuffer.UNSIGNED_SHORT: {
  29122. var value = dataView.getUint16(byteOffset, true);
  29123. if (normalized) {
  29124. value = value / 65535;
  29125. }
  29126. return value;
  29127. }
  29128. case VertexBuffer.FLOAT: {
  29129. return dataView.getFloat32(byteOffset, true);
  29130. }
  29131. default: {
  29132. throw new Error("Invalid component type " + type);
  29133. }
  29134. }
  29135. };
  29136. /**
  29137. * The byte type.
  29138. */
  29139. VertexBuffer.BYTE = 5120;
  29140. /**
  29141. * The unsigned byte type.
  29142. */
  29143. VertexBuffer.UNSIGNED_BYTE = 5121;
  29144. /**
  29145. * The short type.
  29146. */
  29147. VertexBuffer.SHORT = 5122;
  29148. /**
  29149. * The unsigned short type.
  29150. */
  29151. VertexBuffer.UNSIGNED_SHORT = 5123;
  29152. /**
  29153. * The integer type.
  29154. */
  29155. VertexBuffer.INT = 5124;
  29156. /**
  29157. * The unsigned integer type.
  29158. */
  29159. VertexBuffer.UNSIGNED_INT = 5125;
  29160. /**
  29161. * The float type.
  29162. */
  29163. VertexBuffer.FLOAT = 5126;
  29164. // Enums
  29165. VertexBuffer._PositionKind = "position";
  29166. VertexBuffer._NormalKind = "normal";
  29167. VertexBuffer._TangentKind = "tangent";
  29168. VertexBuffer._UVKind = "uv";
  29169. VertexBuffer._UV2Kind = "uv2";
  29170. VertexBuffer._UV3Kind = "uv3";
  29171. VertexBuffer._UV4Kind = "uv4";
  29172. VertexBuffer._UV5Kind = "uv5";
  29173. VertexBuffer._UV6Kind = "uv6";
  29174. VertexBuffer._ColorKind = "color";
  29175. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29176. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29177. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29178. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29179. return VertexBuffer;
  29180. }());
  29181. BABYLON.VertexBuffer = VertexBuffer;
  29182. })(BABYLON || (BABYLON = {}));
  29183. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29184. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29185. var BABYLON;
  29186. (function (BABYLON) {
  29187. /**
  29188. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29189. */
  29190. var DummyInternalTextureTracker = /** @class */ (function () {
  29191. function DummyInternalTextureTracker() {
  29192. /**
  29193. * Gets or set the previous tracker in the list
  29194. */
  29195. this.previous = null;
  29196. /**
  29197. * Gets or set the next tracker in the list
  29198. */
  29199. this.next = null;
  29200. }
  29201. return DummyInternalTextureTracker;
  29202. }());
  29203. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29204. })(BABYLON || (BABYLON = {}));
  29205. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29206. var BABYLON;
  29207. (function (BABYLON) {
  29208. /**
  29209. * Class used to store data associated with WebGL texture data for the engine
  29210. * This class should not be used directly
  29211. */
  29212. var InternalTexture = /** @class */ (function () {
  29213. /**
  29214. * Creates a new InternalTexture
  29215. * @param engine defines the engine to use
  29216. * @param dataSource defines the type of data that will be used
  29217. */
  29218. function InternalTexture(engine, dataSource) {
  29219. /**
  29220. * Observable called when the texture is loaded
  29221. */
  29222. this.onLoadedObservable = new BABYLON.Observable();
  29223. /**
  29224. * Gets or set the previous tracker in the list
  29225. */
  29226. this.previous = null;
  29227. /**
  29228. * Gets or set the next tracker in the list
  29229. */
  29230. this.next = null;
  29231. // Private
  29232. /** @hidden */
  29233. this._initialSlot = -1;
  29234. /** @hidden */
  29235. this._designatedSlot = -1;
  29236. /** @hidden */
  29237. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29238. /** @hidden */
  29239. this._comparisonFunction = 0;
  29240. /** @hidden */
  29241. this._sphericalPolynomial = null;
  29242. /** @hidden */
  29243. this._lodGenerationScale = 0;
  29244. /** @hidden */
  29245. this._lodGenerationOffset = 0;
  29246. /** @hidden */
  29247. this._isRGBD = false;
  29248. /** @hidden */
  29249. this._references = 1;
  29250. this._engine = engine;
  29251. this._dataSource = dataSource;
  29252. this._webGLTexture = engine._createTexture();
  29253. }
  29254. /**
  29255. * Gets the Engine the texture belongs to.
  29256. * @returns The babylon engine
  29257. */
  29258. InternalTexture.prototype.getEngine = function () {
  29259. return this._engine;
  29260. };
  29261. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29262. /**
  29263. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29264. */
  29265. get: function () {
  29266. return this._dataSource;
  29267. },
  29268. enumerable: true,
  29269. configurable: true
  29270. });
  29271. /**
  29272. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29273. */
  29274. InternalTexture.prototype.incrementReferences = function () {
  29275. this._references++;
  29276. };
  29277. /**
  29278. * Change the size of the texture (not the size of the content)
  29279. * @param width defines the new width
  29280. * @param height defines the new height
  29281. * @param depth defines the new depth (1 by default)
  29282. */
  29283. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29284. if (depth === void 0) { depth = 1; }
  29285. this.width = width;
  29286. this.height = height;
  29287. this.depth = depth;
  29288. this.baseWidth = width;
  29289. this.baseHeight = height;
  29290. this.baseDepth = depth;
  29291. this._size = width * height * depth;
  29292. };
  29293. /** @hidden */
  29294. InternalTexture.prototype._rebuild = function () {
  29295. var _this = this;
  29296. var proxy;
  29297. this.isReady = false;
  29298. this._cachedCoordinatesMode = null;
  29299. this._cachedWrapU = null;
  29300. this._cachedWrapV = null;
  29301. this._cachedAnisotropicFilteringLevel = null;
  29302. switch (this._dataSource) {
  29303. case InternalTexture.DATASOURCE_TEMP:
  29304. return;
  29305. case InternalTexture.DATASOURCE_URL:
  29306. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29307. _this.isReady = true;
  29308. }, null, this._buffer, undefined, this.format);
  29309. proxy._swapAndDie(this);
  29310. return;
  29311. case InternalTexture.DATASOURCE_RAW:
  29312. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29313. proxy._swapAndDie(this);
  29314. this.isReady = true;
  29315. return;
  29316. case InternalTexture.DATASOURCE_RAW3D:
  29317. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29318. proxy._swapAndDie(this);
  29319. this.isReady = true;
  29320. return;
  29321. case InternalTexture.DATASOURCE_DYNAMIC:
  29322. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29323. proxy._swapAndDie(this);
  29324. // The engine will make sure to update content so no need to flag it as isReady = true
  29325. return;
  29326. case InternalTexture.DATASOURCE_RENDERTARGET:
  29327. var options = new BABYLON.RenderTargetCreationOptions();
  29328. options.generateDepthBuffer = this._generateDepthBuffer;
  29329. options.generateMipMaps = this.generateMipMaps;
  29330. options.generateStencilBuffer = this._generateStencilBuffer;
  29331. options.samplingMode = this.samplingMode;
  29332. options.type = this.type;
  29333. if (this.isCube) {
  29334. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29335. }
  29336. else {
  29337. var size = {
  29338. width: this.width,
  29339. height: this.height
  29340. };
  29341. proxy = this._engine.createRenderTargetTexture(size, options);
  29342. }
  29343. proxy._swapAndDie(this);
  29344. this.isReady = true;
  29345. return;
  29346. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29347. var depthTextureOptions = {
  29348. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29349. comparisonFunction: this._comparisonFunction,
  29350. generateStencil: this._generateStencilBuffer,
  29351. isCube: this.isCube
  29352. };
  29353. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29354. proxy._swapAndDie(this);
  29355. this.isReady = true;
  29356. return;
  29357. case InternalTexture.DATASOURCE_CUBE:
  29358. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29359. _this.isReady = true;
  29360. }, null, this.format, this._extension);
  29361. proxy._swapAndDie(this);
  29362. return;
  29363. case InternalTexture.DATASOURCE_CUBERAW:
  29364. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29365. proxy._swapAndDie(this);
  29366. this.isReady = true;
  29367. return;
  29368. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29369. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29370. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29371. _this.isReady = true;
  29372. });
  29373. proxy._swapAndDie(this);
  29374. return;
  29375. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29376. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29377. if (proxy) {
  29378. proxy._swapAndDie(_this);
  29379. }
  29380. _this.isReady = true;
  29381. }, null, this.format, this._extension);
  29382. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29383. return;
  29384. }
  29385. };
  29386. /** @hidden */
  29387. InternalTexture.prototype._swapAndDie = function (target) {
  29388. target._webGLTexture = this._webGLTexture;
  29389. if (this._framebuffer) {
  29390. target._framebuffer = this._framebuffer;
  29391. }
  29392. if (this._depthStencilBuffer) {
  29393. target._depthStencilBuffer = this._depthStencilBuffer;
  29394. }
  29395. if (this._lodTextureHigh) {
  29396. if (target._lodTextureHigh) {
  29397. target._lodTextureHigh.dispose();
  29398. }
  29399. target._lodTextureHigh = this._lodTextureHigh;
  29400. }
  29401. if (this._lodTextureMid) {
  29402. if (target._lodTextureMid) {
  29403. target._lodTextureMid.dispose();
  29404. }
  29405. target._lodTextureMid = this._lodTextureMid;
  29406. }
  29407. if (this._lodTextureLow) {
  29408. if (target._lodTextureLow) {
  29409. target._lodTextureLow.dispose();
  29410. }
  29411. target._lodTextureLow = this._lodTextureLow;
  29412. }
  29413. var cache = this._engine.getLoadedTexturesCache();
  29414. var index = cache.indexOf(this);
  29415. if (index !== -1) {
  29416. cache.splice(index, 1);
  29417. }
  29418. };
  29419. /**
  29420. * Dispose the current allocated resources
  29421. */
  29422. InternalTexture.prototype.dispose = function () {
  29423. if (!this._webGLTexture) {
  29424. return;
  29425. }
  29426. this._references--;
  29427. if (this._references === 0) {
  29428. this._engine._releaseTexture(this);
  29429. this._webGLTexture = null;
  29430. this.previous = null;
  29431. this.next = null;
  29432. }
  29433. };
  29434. /**
  29435. * The source of the texture data is unknown
  29436. */
  29437. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29438. /**
  29439. * Texture data comes from an URL
  29440. */
  29441. InternalTexture.DATASOURCE_URL = 1;
  29442. /**
  29443. * Texture data is only used for temporary storage
  29444. */
  29445. InternalTexture.DATASOURCE_TEMP = 2;
  29446. /**
  29447. * Texture data comes from raw data (ArrayBuffer)
  29448. */
  29449. InternalTexture.DATASOURCE_RAW = 3;
  29450. /**
  29451. * Texture content is dynamic (video or dynamic texture)
  29452. */
  29453. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29454. /**
  29455. * Texture content is generated by rendering to it
  29456. */
  29457. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29458. /**
  29459. * Texture content is part of a multi render target process
  29460. */
  29461. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29462. /**
  29463. * Texture data comes from a cube data file
  29464. */
  29465. InternalTexture.DATASOURCE_CUBE = 7;
  29466. /**
  29467. * Texture data comes from a raw cube data
  29468. */
  29469. InternalTexture.DATASOURCE_CUBERAW = 8;
  29470. /**
  29471. * Texture data come from a prefiltered cube data file
  29472. */
  29473. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29474. /**
  29475. * Texture content is raw 3D data
  29476. */
  29477. InternalTexture.DATASOURCE_RAW3D = 10;
  29478. /**
  29479. * Texture content is a depth texture
  29480. */
  29481. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29482. /**
  29483. * Texture data comes from a raw cube data encoded with RGBD
  29484. */
  29485. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29486. return InternalTexture;
  29487. }());
  29488. BABYLON.InternalTexture = InternalTexture;
  29489. })(BABYLON || (BABYLON = {}));
  29490. //# sourceMappingURL=babylon.internalTexture.js.map
  29491. var BABYLON;
  29492. (function (BABYLON) {
  29493. var BaseTexture = /** @class */ (function () {
  29494. function BaseTexture(scene) {
  29495. this._hasAlpha = false;
  29496. this.getAlphaFromRGB = false;
  29497. this.level = 1;
  29498. this.coordinatesIndex = 0;
  29499. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29500. /**
  29501. * | Value | Type | Description |
  29502. * | ----- | ------------------ | ----------- |
  29503. * | 0 | CLAMP_ADDRESSMODE | |
  29504. * | 1 | WRAP_ADDRESSMODE | |
  29505. * | 2 | MIRROR_ADDRESSMODE | |
  29506. */
  29507. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29508. /**
  29509. * | Value | Type | Description |
  29510. * | ----- | ------------------ | ----------- |
  29511. * | 0 | CLAMP_ADDRESSMODE | |
  29512. * | 1 | WRAP_ADDRESSMODE | |
  29513. * | 2 | MIRROR_ADDRESSMODE | |
  29514. */
  29515. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29516. /**
  29517. * | Value | Type | Description |
  29518. * | ----- | ------------------ | ----------- |
  29519. * | 0 | CLAMP_ADDRESSMODE | |
  29520. * | 1 | WRAP_ADDRESSMODE | |
  29521. * | 2 | MIRROR_ADDRESSMODE | |
  29522. */
  29523. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29524. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29525. this.isCube = false;
  29526. this.is3D = false;
  29527. this.gammaSpace = true;
  29528. this.invertZ = false;
  29529. this.lodLevelInAlpha = false;
  29530. this.isRenderTarget = false;
  29531. this.animations = new Array();
  29532. /**
  29533. * An event triggered when the texture is disposed.
  29534. */
  29535. this.onDisposeObservable = new BABYLON.Observable();
  29536. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29537. this._cachedSize = BABYLON.Size.Zero();
  29538. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29539. if (this._scene) {
  29540. this._scene.textures.push(this);
  29541. }
  29542. this._uid = null;
  29543. }
  29544. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29545. get: function () {
  29546. return this._hasAlpha;
  29547. },
  29548. set: function (value) {
  29549. if (this._hasAlpha === value) {
  29550. return;
  29551. }
  29552. this._hasAlpha = value;
  29553. if (this._scene) {
  29554. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29555. }
  29556. },
  29557. enumerable: true,
  29558. configurable: true
  29559. });
  29560. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29561. get: function () {
  29562. return this._coordinatesMode;
  29563. },
  29564. /**
  29565. * How a texture is mapped.
  29566. *
  29567. * | Value | Type | Description |
  29568. * | ----- | ----------------------------------- | ----------- |
  29569. * | 0 | EXPLICIT_MODE | |
  29570. * | 1 | SPHERICAL_MODE | |
  29571. * | 2 | PLANAR_MODE | |
  29572. * | 3 | CUBIC_MODE | |
  29573. * | 4 | PROJECTION_MODE | |
  29574. * | 5 | SKYBOX_MODE | |
  29575. * | 6 | INVCUBIC_MODE | |
  29576. * | 7 | EQUIRECTANGULAR_MODE | |
  29577. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29578. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29579. */
  29580. set: function (value) {
  29581. if (this._coordinatesMode === value) {
  29582. return;
  29583. }
  29584. this._coordinatesMode = value;
  29585. if (this._scene) {
  29586. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29587. }
  29588. },
  29589. enumerable: true,
  29590. configurable: true
  29591. });
  29592. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29593. /**
  29594. * Gets whether or not the texture contains RGBD data.
  29595. */
  29596. get: function () {
  29597. return this._texture != null && this._texture._isRGBD;
  29598. },
  29599. enumerable: true,
  29600. configurable: true
  29601. });
  29602. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29603. get: function () {
  29604. if (this._texture)
  29605. return this._texture._lodGenerationOffset;
  29606. return 0.0;
  29607. },
  29608. set: function (value) {
  29609. if (this._texture)
  29610. this._texture._lodGenerationOffset = value;
  29611. },
  29612. enumerable: true,
  29613. configurable: true
  29614. });
  29615. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29616. get: function () {
  29617. if (this._texture)
  29618. return this._texture._lodGenerationScale;
  29619. return 0.0;
  29620. },
  29621. set: function (value) {
  29622. if (this._texture)
  29623. this._texture._lodGenerationScale = value;
  29624. },
  29625. enumerable: true,
  29626. configurable: true
  29627. });
  29628. Object.defineProperty(BaseTexture.prototype, "uid", {
  29629. get: function () {
  29630. if (!this._uid) {
  29631. this._uid = BABYLON.Tools.RandomId();
  29632. }
  29633. return this._uid;
  29634. },
  29635. enumerable: true,
  29636. configurable: true
  29637. });
  29638. BaseTexture.prototype.toString = function () {
  29639. return this.name;
  29640. };
  29641. BaseTexture.prototype.getClassName = function () {
  29642. return "BaseTexture";
  29643. };
  29644. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29645. set: function (callback) {
  29646. if (this._onDisposeObserver) {
  29647. this.onDisposeObservable.remove(this._onDisposeObserver);
  29648. }
  29649. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29650. },
  29651. enumerable: true,
  29652. configurable: true
  29653. });
  29654. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29655. get: function () {
  29656. return true;
  29657. },
  29658. enumerable: true,
  29659. configurable: true
  29660. });
  29661. BaseTexture.prototype.getScene = function () {
  29662. return this._scene;
  29663. };
  29664. BaseTexture.prototype.getTextureMatrix = function () {
  29665. return BABYLON.Matrix.IdentityReadOnly;
  29666. };
  29667. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29668. return BABYLON.Matrix.IdentityReadOnly;
  29669. };
  29670. BaseTexture.prototype.getInternalTexture = function () {
  29671. return this._texture;
  29672. };
  29673. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29674. return !this.isBlocking || this.isReady();
  29675. };
  29676. BaseTexture.prototype.isReady = function () {
  29677. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29678. this.delayLoad();
  29679. return false;
  29680. }
  29681. if (this._texture) {
  29682. return this._texture.isReady;
  29683. }
  29684. return false;
  29685. };
  29686. BaseTexture.prototype.getSize = function () {
  29687. if (this._texture) {
  29688. if (this._texture.width) {
  29689. this._cachedSize.width = this._texture.width;
  29690. this._cachedSize.height = this._texture.height;
  29691. return this._cachedSize;
  29692. }
  29693. if (this._texture._size) {
  29694. this._cachedSize.width = this._texture._size;
  29695. this._cachedSize.height = this._texture._size;
  29696. return this._cachedSize;
  29697. }
  29698. }
  29699. return this._cachedSize;
  29700. };
  29701. BaseTexture.prototype.getBaseSize = function () {
  29702. if (!this.isReady() || !this._texture)
  29703. return BABYLON.Size.Zero();
  29704. if (this._texture._size) {
  29705. return new BABYLON.Size(this._texture._size, this._texture._size);
  29706. }
  29707. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29708. };
  29709. BaseTexture.prototype.scale = function (ratio) {
  29710. };
  29711. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29712. get: function () {
  29713. return false;
  29714. },
  29715. enumerable: true,
  29716. configurable: true
  29717. });
  29718. /** @hidden */
  29719. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29720. if (!this._scene) {
  29721. return null;
  29722. }
  29723. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29724. for (var index = 0; index < texturesCache.length; index++) {
  29725. var texturesCacheEntry = texturesCache[index];
  29726. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29727. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29728. texturesCacheEntry.incrementReferences();
  29729. return texturesCacheEntry;
  29730. }
  29731. }
  29732. }
  29733. return null;
  29734. };
  29735. /** @hidden */
  29736. BaseTexture.prototype._rebuild = function () {
  29737. };
  29738. BaseTexture.prototype.delayLoad = function () {
  29739. };
  29740. BaseTexture.prototype.clone = function () {
  29741. return null;
  29742. };
  29743. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29744. get: function () {
  29745. if (!this._texture) {
  29746. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29747. }
  29748. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29749. },
  29750. enumerable: true,
  29751. configurable: true
  29752. });
  29753. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29754. get: function () {
  29755. if (!this._texture) {
  29756. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29757. }
  29758. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29759. },
  29760. enumerable: true,
  29761. configurable: true
  29762. });
  29763. /**
  29764. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  29765. * This will returns an RGBA array buffer containing either in values (0-255) or
  29766. * float values (0-1) depending of the underlying buffer type.
  29767. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  29768. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  29769. * @param buffer defines a user defined buffer to fill with data (can be null)
  29770. * @returns The Array buffer containing the pixels data.
  29771. */
  29772. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  29773. if (faceIndex === void 0) { faceIndex = 0; }
  29774. if (level === void 0) { level = 0; }
  29775. if (buffer === void 0) { buffer = null; }
  29776. if (!this._texture) {
  29777. return null;
  29778. }
  29779. var size = this.getSize();
  29780. var width = size.width;
  29781. var height = size.height;
  29782. var scene = this.getScene();
  29783. if (!scene) {
  29784. return null;
  29785. }
  29786. var engine = scene.getEngine();
  29787. if (level != 0) {
  29788. width = width / Math.pow(2, level);
  29789. height = height / Math.pow(2, level);
  29790. width = Math.round(width);
  29791. height = Math.round(height);
  29792. }
  29793. if (this._texture.isCube) {
  29794. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  29795. }
  29796. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  29797. };
  29798. BaseTexture.prototype.releaseInternalTexture = function () {
  29799. if (this._texture) {
  29800. this._texture.dispose();
  29801. this._texture = null;
  29802. }
  29803. };
  29804. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29805. get: function () {
  29806. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29807. return null;
  29808. }
  29809. if (!this._texture._sphericalPolynomial) {
  29810. this._texture._sphericalPolynomial =
  29811. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29812. }
  29813. return this._texture._sphericalPolynomial;
  29814. },
  29815. set: function (value) {
  29816. if (this._texture) {
  29817. this._texture._sphericalPolynomial = value;
  29818. }
  29819. },
  29820. enumerable: true,
  29821. configurable: true
  29822. });
  29823. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29824. get: function () {
  29825. if (this._texture) {
  29826. return this._texture._lodTextureHigh;
  29827. }
  29828. return null;
  29829. },
  29830. enumerable: true,
  29831. configurable: true
  29832. });
  29833. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29834. get: function () {
  29835. if (this._texture) {
  29836. return this._texture._lodTextureMid;
  29837. }
  29838. return null;
  29839. },
  29840. enumerable: true,
  29841. configurable: true
  29842. });
  29843. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29844. get: function () {
  29845. if (this._texture) {
  29846. return this._texture._lodTextureLow;
  29847. }
  29848. return null;
  29849. },
  29850. enumerable: true,
  29851. configurable: true
  29852. });
  29853. BaseTexture.prototype.dispose = function () {
  29854. if (!this._scene) {
  29855. return;
  29856. }
  29857. // Animations
  29858. this._scene.stopAnimation(this);
  29859. // Remove from scene
  29860. this._scene._removePendingData(this);
  29861. var index = this._scene.textures.indexOf(this);
  29862. if (index >= 0) {
  29863. this._scene.textures.splice(index, 1);
  29864. }
  29865. if (this._texture === undefined) {
  29866. return;
  29867. }
  29868. // Release
  29869. this.releaseInternalTexture();
  29870. // Callback
  29871. this.onDisposeObservable.notifyObservers(this);
  29872. this.onDisposeObservable.clear();
  29873. };
  29874. BaseTexture.prototype.serialize = function () {
  29875. if (!this.name) {
  29876. return null;
  29877. }
  29878. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29879. // Animations
  29880. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29881. return serializationObject;
  29882. };
  29883. BaseTexture.WhenAllReady = function (textures, callback) {
  29884. var numRemaining = textures.length;
  29885. if (numRemaining === 0) {
  29886. callback();
  29887. return;
  29888. }
  29889. var _loop_1 = function () {
  29890. texture = textures[i];
  29891. if (texture.isReady()) {
  29892. if (--numRemaining === 0) {
  29893. callback();
  29894. }
  29895. }
  29896. else {
  29897. onLoadObservable = texture.onLoadObservable;
  29898. var onLoadCallback_1 = function () {
  29899. onLoadObservable.removeCallback(onLoadCallback_1);
  29900. if (--numRemaining === 0) {
  29901. callback();
  29902. }
  29903. };
  29904. onLoadObservable.add(onLoadCallback_1);
  29905. }
  29906. };
  29907. var texture, onLoadObservable;
  29908. for (var i = 0; i < textures.length; i++) {
  29909. _loop_1();
  29910. }
  29911. };
  29912. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29913. __decorate([
  29914. BABYLON.serialize()
  29915. ], BaseTexture.prototype, "name", void 0);
  29916. __decorate([
  29917. BABYLON.serialize("hasAlpha")
  29918. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29919. __decorate([
  29920. BABYLON.serialize()
  29921. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29922. __decorate([
  29923. BABYLON.serialize()
  29924. ], BaseTexture.prototype, "level", void 0);
  29925. __decorate([
  29926. BABYLON.serialize()
  29927. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29928. __decorate([
  29929. BABYLON.serialize("coordinatesMode")
  29930. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29931. __decorate([
  29932. BABYLON.serialize()
  29933. ], BaseTexture.prototype, "wrapU", void 0);
  29934. __decorate([
  29935. BABYLON.serialize()
  29936. ], BaseTexture.prototype, "wrapV", void 0);
  29937. __decorate([
  29938. BABYLON.serialize()
  29939. ], BaseTexture.prototype, "wrapR", void 0);
  29940. __decorate([
  29941. BABYLON.serialize()
  29942. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29943. __decorate([
  29944. BABYLON.serialize()
  29945. ], BaseTexture.prototype, "isCube", void 0);
  29946. __decorate([
  29947. BABYLON.serialize()
  29948. ], BaseTexture.prototype, "is3D", void 0);
  29949. __decorate([
  29950. BABYLON.serialize()
  29951. ], BaseTexture.prototype, "gammaSpace", void 0);
  29952. __decorate([
  29953. BABYLON.serialize()
  29954. ], BaseTexture.prototype, "invertZ", void 0);
  29955. __decorate([
  29956. BABYLON.serialize()
  29957. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29958. __decorate([
  29959. BABYLON.serialize()
  29960. ], BaseTexture.prototype, "lodGenerationOffset", null);
  29961. __decorate([
  29962. BABYLON.serialize()
  29963. ], BaseTexture.prototype, "lodGenerationScale", null);
  29964. __decorate([
  29965. BABYLON.serialize()
  29966. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29967. return BaseTexture;
  29968. }());
  29969. BABYLON.BaseTexture = BaseTexture;
  29970. })(BABYLON || (BABYLON = {}));
  29971. //# sourceMappingURL=babylon.baseTexture.js.map
  29972. var BABYLON;
  29973. (function (BABYLON) {
  29974. var Texture = /** @class */ (function (_super) {
  29975. __extends(Texture, _super);
  29976. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29977. if (noMipmap === void 0) { noMipmap = false; }
  29978. if (invertY === void 0) { invertY = true; }
  29979. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29980. if (onLoad === void 0) { onLoad = null; }
  29981. if (onError === void 0) { onError = null; }
  29982. if (buffer === void 0) { buffer = null; }
  29983. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29984. var _this = _super.call(this, scene) || this;
  29985. _this.uOffset = 0;
  29986. _this.vOffset = 0;
  29987. _this.uScale = 1.0;
  29988. _this.vScale = 1.0;
  29989. _this.uAng = 0;
  29990. _this.vAng = 0;
  29991. _this.wAng = 0;
  29992. /**
  29993. * Defines the center of rotation (U)
  29994. */
  29995. _this.uRotationCenter = 0.5;
  29996. /**
  29997. * Defines the center of rotation (V)
  29998. */
  29999. _this.vRotationCenter = 0.5;
  30000. /**
  30001. * Defines the center of rotation (W)
  30002. */
  30003. _this.wRotationCenter = 0.5;
  30004. _this._isBlocking = true;
  30005. _this.name = url || "";
  30006. _this.url = url;
  30007. _this._noMipmap = noMipmap;
  30008. _this._invertY = invertY;
  30009. _this._samplingMode = samplingMode;
  30010. _this._buffer = buffer;
  30011. _this._deleteBuffer = deleteBuffer;
  30012. if (format) {
  30013. _this._format = format;
  30014. }
  30015. scene = _this.getScene();
  30016. if (!scene) {
  30017. return _this;
  30018. }
  30019. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30020. var load = function () {
  30021. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30022. _this.onLoadObservable.notifyObservers(_this);
  30023. }
  30024. if (onLoad) {
  30025. onLoad();
  30026. }
  30027. if (!_this.isBlocking && scene) {
  30028. scene.resetCachedMaterial();
  30029. }
  30030. };
  30031. if (!_this.url) {
  30032. _this._delayedOnLoad = load;
  30033. _this._delayedOnError = onError;
  30034. return _this;
  30035. }
  30036. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30037. if (!_this._texture) {
  30038. if (!scene.useDelayedTextureLoading) {
  30039. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30040. if (deleteBuffer) {
  30041. delete _this._buffer;
  30042. }
  30043. }
  30044. else {
  30045. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30046. _this._delayedOnLoad = load;
  30047. _this._delayedOnError = onError;
  30048. }
  30049. }
  30050. else {
  30051. if (_this._texture.isReady) {
  30052. BABYLON.Tools.SetImmediate(function () { return load(); });
  30053. }
  30054. else {
  30055. _this._texture.onLoadedObservable.add(load);
  30056. }
  30057. }
  30058. return _this;
  30059. }
  30060. Object.defineProperty(Texture.prototype, "noMipmap", {
  30061. get: function () {
  30062. return this._noMipmap;
  30063. },
  30064. enumerable: true,
  30065. configurable: true
  30066. });
  30067. Object.defineProperty(Texture.prototype, "isBlocking", {
  30068. get: function () {
  30069. return this._isBlocking;
  30070. },
  30071. set: function (value) {
  30072. this._isBlocking = value;
  30073. },
  30074. enumerable: true,
  30075. configurable: true
  30076. });
  30077. Object.defineProperty(Texture.prototype, "samplingMode", {
  30078. get: function () {
  30079. return this._samplingMode;
  30080. },
  30081. enumerable: true,
  30082. configurable: true
  30083. });
  30084. /**
  30085. * Update the url (and optional buffer) of this texture if url was null during construction.
  30086. * @param url the url of the texture
  30087. * @param buffer the buffer of the texture (defaults to null)
  30088. */
  30089. Texture.prototype.updateURL = function (url, buffer) {
  30090. if (buffer === void 0) { buffer = null; }
  30091. if (this.url) {
  30092. throw new Error("URL is already set");
  30093. }
  30094. this.url = url;
  30095. this._buffer = buffer;
  30096. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30097. this.delayLoad();
  30098. };
  30099. Texture.prototype.delayLoad = function () {
  30100. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30101. return;
  30102. }
  30103. var scene = this.getScene();
  30104. if (!scene) {
  30105. return;
  30106. }
  30107. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30108. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30109. if (!this._texture) {
  30110. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30111. if (this._deleteBuffer) {
  30112. delete this._buffer;
  30113. }
  30114. }
  30115. else {
  30116. if (this._delayedOnLoad) {
  30117. if (this._texture.isReady) {
  30118. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30119. }
  30120. else {
  30121. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30122. }
  30123. }
  30124. }
  30125. this._delayedOnLoad = null;
  30126. this._delayedOnError = null;
  30127. };
  30128. /**
  30129. * Default is Trilinear mode.
  30130. *
  30131. * | Value | Type | Description |
  30132. * | ----- | ------------------ | ----------- |
  30133. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30134. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30135. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30136. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30137. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30138. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30139. * | 7 | NEAREST_LINEAR | |
  30140. * | 8 | NEAREST_NEAREST | |
  30141. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30142. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30143. * | 11 | LINEAR_LINEAR | |
  30144. * | 12 | LINEAR_NEAREST | |
  30145. *
  30146. * > _mag_: magnification filter (close to the viewer)
  30147. * > _min_: minification filter (far from the viewer)
  30148. * > _mip_: filter used between mip map levels
  30149. *
  30150. */
  30151. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30152. if (!this._texture) {
  30153. return;
  30154. }
  30155. var scene = this.getScene();
  30156. if (!scene) {
  30157. return;
  30158. }
  30159. this._samplingMode = samplingMode;
  30160. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30161. };
  30162. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30163. x *= this.uScale;
  30164. y *= this.vScale;
  30165. x -= this.uRotationCenter * this.uScale;
  30166. y -= this.vRotationCenter * this.vScale;
  30167. z -= this.wRotationCenter;
  30168. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30169. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30170. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30171. t.z += this.wRotationCenter;
  30172. };
  30173. Texture.prototype.getTextureMatrix = function () {
  30174. var _this = this;
  30175. if (this.uOffset === this._cachedUOffset &&
  30176. this.vOffset === this._cachedVOffset &&
  30177. this.uScale === this._cachedUScale &&
  30178. this.vScale === this._cachedVScale &&
  30179. this.uAng === this._cachedUAng &&
  30180. this.vAng === this._cachedVAng &&
  30181. this.wAng === this._cachedWAng) {
  30182. return this._cachedTextureMatrix;
  30183. }
  30184. this._cachedUOffset = this.uOffset;
  30185. this._cachedVOffset = this.vOffset;
  30186. this._cachedUScale = this.uScale;
  30187. this._cachedVScale = this.vScale;
  30188. this._cachedUAng = this.uAng;
  30189. this._cachedVAng = this.vAng;
  30190. this._cachedWAng = this.wAng;
  30191. if (!this._cachedTextureMatrix) {
  30192. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30193. this._rowGenerationMatrix = new BABYLON.Matrix();
  30194. this._t0 = BABYLON.Vector3.Zero();
  30195. this._t1 = BABYLON.Vector3.Zero();
  30196. this._t2 = BABYLON.Vector3.Zero();
  30197. }
  30198. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30199. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30200. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30201. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30202. this._t1.subtractInPlace(this._t0);
  30203. this._t2.subtractInPlace(this._t0);
  30204. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30205. this._cachedTextureMatrix.m[0] = this._t1.x;
  30206. this._cachedTextureMatrix.m[1] = this._t1.y;
  30207. this._cachedTextureMatrix.m[2] = this._t1.z;
  30208. this._cachedTextureMatrix.m[4] = this._t2.x;
  30209. this._cachedTextureMatrix.m[5] = this._t2.y;
  30210. this._cachedTextureMatrix.m[6] = this._t2.z;
  30211. this._cachedTextureMatrix.m[8] = this._t0.x;
  30212. this._cachedTextureMatrix.m[9] = this._t0.y;
  30213. this._cachedTextureMatrix.m[10] = this._t0.z;
  30214. var scene = this.getScene();
  30215. if (!scene) {
  30216. return this._cachedTextureMatrix;
  30217. }
  30218. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30219. return mat.hasTexture(_this);
  30220. });
  30221. return this._cachedTextureMatrix;
  30222. };
  30223. Texture.prototype.getReflectionTextureMatrix = function () {
  30224. var _this = this;
  30225. var scene = this.getScene();
  30226. if (!scene) {
  30227. return this._cachedTextureMatrix;
  30228. }
  30229. if (this.uOffset === this._cachedUOffset &&
  30230. this.vOffset === this._cachedVOffset &&
  30231. this.uScale === this._cachedUScale &&
  30232. this.vScale === this._cachedVScale &&
  30233. this.coordinatesMode === this._cachedCoordinatesMode) {
  30234. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30235. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30236. return this._cachedTextureMatrix;
  30237. }
  30238. }
  30239. else {
  30240. return this._cachedTextureMatrix;
  30241. }
  30242. }
  30243. if (!this._cachedTextureMatrix) {
  30244. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30245. }
  30246. if (!this._projectionModeMatrix) {
  30247. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30248. }
  30249. this._cachedUOffset = this.uOffset;
  30250. this._cachedVOffset = this.vOffset;
  30251. this._cachedUScale = this.uScale;
  30252. this._cachedVScale = this.vScale;
  30253. this._cachedCoordinatesMode = this.coordinatesMode;
  30254. switch (this.coordinatesMode) {
  30255. case Texture.PLANAR_MODE:
  30256. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30257. this._cachedTextureMatrix[0] = this.uScale;
  30258. this._cachedTextureMatrix[5] = this.vScale;
  30259. this._cachedTextureMatrix[12] = this.uOffset;
  30260. this._cachedTextureMatrix[13] = this.vOffset;
  30261. break;
  30262. case Texture.PROJECTION_MODE:
  30263. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30264. this._projectionModeMatrix.m[0] = 0.5;
  30265. this._projectionModeMatrix.m[5] = -0.5;
  30266. this._projectionModeMatrix.m[10] = 0.0;
  30267. this._projectionModeMatrix.m[12] = 0.5;
  30268. this._projectionModeMatrix.m[13] = 0.5;
  30269. this._projectionModeMatrix.m[14] = 1.0;
  30270. this._projectionModeMatrix.m[15] = 1.0;
  30271. var projectionMatrix = scene.getProjectionMatrix();
  30272. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30273. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30274. break;
  30275. default:
  30276. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30277. break;
  30278. }
  30279. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30280. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30281. });
  30282. return this._cachedTextureMatrix;
  30283. };
  30284. Texture.prototype.clone = function () {
  30285. var _this = this;
  30286. return BABYLON.SerializationHelper.Clone(function () {
  30287. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30288. }, this);
  30289. };
  30290. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30291. get: function () {
  30292. if (!this._onLoadObservable) {
  30293. this._onLoadObservable = new BABYLON.Observable();
  30294. }
  30295. return this._onLoadObservable;
  30296. },
  30297. enumerable: true,
  30298. configurable: true
  30299. });
  30300. Texture.prototype.serialize = function () {
  30301. var serializationObject = _super.prototype.serialize.call(this);
  30302. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30303. serializationObject.base64String = this._buffer;
  30304. serializationObject.name = serializationObject.name.replace("data:", "");
  30305. }
  30306. serializationObject.invertY = this._invertY;
  30307. serializationObject.samplingMode = this.samplingMode;
  30308. return serializationObject;
  30309. };
  30310. Texture.prototype.getClassName = function () {
  30311. return "Texture";
  30312. };
  30313. Texture.prototype.dispose = function () {
  30314. _super.prototype.dispose.call(this);
  30315. if (this._onLoadObservable) {
  30316. this._onLoadObservable.clear();
  30317. this._onLoadObservable = null;
  30318. }
  30319. this._delayedOnLoad = null;
  30320. this._delayedOnError = null;
  30321. };
  30322. // Statics
  30323. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30324. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30325. if (onLoad === void 0) { onLoad = null; }
  30326. if (onError === void 0) { onError = null; }
  30327. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30328. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30329. };
  30330. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30331. if (parsedTexture.customType) {
  30332. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30333. // Update Sampling Mode
  30334. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30335. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30336. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30337. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30338. }
  30339. }
  30340. return parsedCustomTexture;
  30341. }
  30342. if (parsedTexture.isCube) {
  30343. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30344. }
  30345. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30346. return null;
  30347. }
  30348. var texture = BABYLON.SerializationHelper.Parse(function () {
  30349. var generateMipMaps = true;
  30350. if (parsedTexture.noMipmap) {
  30351. generateMipMaps = false;
  30352. }
  30353. if (parsedTexture.mirrorPlane) {
  30354. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30355. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30356. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30357. return mirrorTexture;
  30358. }
  30359. else if (parsedTexture.isRenderTarget) {
  30360. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30361. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30362. return renderTargetTexture;
  30363. }
  30364. else {
  30365. var texture;
  30366. if (parsedTexture.base64String) {
  30367. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30368. }
  30369. else {
  30370. var url = rootUrl + parsedTexture.name;
  30371. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30372. url = parsedTexture.url;
  30373. }
  30374. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30375. }
  30376. return texture;
  30377. }
  30378. }, parsedTexture, scene);
  30379. // Update Sampling Mode
  30380. if (parsedTexture.samplingMode) {
  30381. var sampling = parsedTexture.samplingMode;
  30382. if (texture._samplingMode !== sampling) {
  30383. texture.updateSamplingMode(sampling);
  30384. }
  30385. }
  30386. // Animations
  30387. if (parsedTexture.animations) {
  30388. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30389. var parsedAnimation = parsedTexture.animations[animationIndex];
  30390. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30391. }
  30392. }
  30393. return texture;
  30394. };
  30395. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30396. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30397. if (noMipmap === void 0) { noMipmap = false; }
  30398. if (invertY === void 0) { invertY = true; }
  30399. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30400. if (onLoad === void 0) { onLoad = null; }
  30401. if (onError === void 0) { onError = null; }
  30402. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30403. if (name.substr(0, 5) !== "data:") {
  30404. name = "data:" + name;
  30405. }
  30406. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30407. };
  30408. // Constants
  30409. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30410. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30411. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30412. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30413. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30414. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30415. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30416. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30417. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30418. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30419. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30420. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30421. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30422. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30423. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30424. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30425. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30426. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30427. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30428. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30429. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30430. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30431. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30432. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30433. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30434. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30435. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30436. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30437. /**
  30438. * 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
  30439. */
  30440. Texture.UseSerializedUrlIfAny = false;
  30441. __decorate([
  30442. BABYLON.serialize()
  30443. ], Texture.prototype, "url", void 0);
  30444. __decorate([
  30445. BABYLON.serialize()
  30446. ], Texture.prototype, "uOffset", void 0);
  30447. __decorate([
  30448. BABYLON.serialize()
  30449. ], Texture.prototype, "vOffset", void 0);
  30450. __decorate([
  30451. BABYLON.serialize()
  30452. ], Texture.prototype, "uScale", void 0);
  30453. __decorate([
  30454. BABYLON.serialize()
  30455. ], Texture.prototype, "vScale", void 0);
  30456. __decorate([
  30457. BABYLON.serialize()
  30458. ], Texture.prototype, "uAng", void 0);
  30459. __decorate([
  30460. BABYLON.serialize()
  30461. ], Texture.prototype, "vAng", void 0);
  30462. __decorate([
  30463. BABYLON.serialize()
  30464. ], Texture.prototype, "wAng", void 0);
  30465. __decorate([
  30466. BABYLON.serialize()
  30467. ], Texture.prototype, "uRotationCenter", void 0);
  30468. __decorate([
  30469. BABYLON.serialize()
  30470. ], Texture.prototype, "vRotationCenter", void 0);
  30471. __decorate([
  30472. BABYLON.serialize()
  30473. ], Texture.prototype, "wRotationCenter", void 0);
  30474. __decorate([
  30475. BABYLON.serialize()
  30476. ], Texture.prototype, "isBlocking", null);
  30477. return Texture;
  30478. }(BABYLON.BaseTexture));
  30479. BABYLON.Texture = Texture;
  30480. })(BABYLON || (BABYLON = {}));
  30481. //# sourceMappingURL=babylon.texture.js.map
  30482. var BABYLON;
  30483. (function (BABYLON) {
  30484. /**
  30485. * @hidden
  30486. **/
  30487. var _InstancesBatch = /** @class */ (function () {
  30488. function _InstancesBatch() {
  30489. this.mustReturn = false;
  30490. this.visibleInstances = new Array();
  30491. this.renderSelf = new Array();
  30492. }
  30493. return _InstancesBatch;
  30494. }());
  30495. BABYLON._InstancesBatch = _InstancesBatch;
  30496. var Mesh = /** @class */ (function (_super) {
  30497. __extends(Mesh, _super);
  30498. /**
  30499. * @constructor
  30500. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30501. * @param {Scene} scene The scene to add this mesh to.
  30502. * @param {Node} parent The parent of this mesh, if it has one
  30503. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30504. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30505. * When false, achieved by calling a clone(), also passing False.
  30506. * This will make creation of children, recursive.
  30507. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30508. */
  30509. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30510. if (scene === void 0) { scene = null; }
  30511. if (parent === void 0) { parent = null; }
  30512. if (source === void 0) { source = null; }
  30513. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30514. var _this = _super.call(this, name, scene) || this;
  30515. // Members
  30516. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30517. _this.instances = new Array();
  30518. _this._LODLevels = new Array();
  30519. /** @hidden */
  30520. _this._visibleInstances = {};
  30521. _this._renderIdForInstances = new Array();
  30522. _this._batchCache = new _InstancesBatch();
  30523. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30524. // Use by builder only to know what orientation were the mesh build in.
  30525. /** @hidden */
  30526. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30527. _this.overrideMaterialSideOrientation = null;
  30528. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30529. // Will be used to save a source mesh reference, If any
  30530. _this._source = null;
  30531. scene = _this.getScene();
  30532. if (source) {
  30533. // Geometry
  30534. if (source._geometry) {
  30535. source._geometry.applyToMesh(_this);
  30536. }
  30537. // Deep copy
  30538. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30539. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30540. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30541. ], ["_poseMatrix"]);
  30542. // Source mesh
  30543. _this._source = source;
  30544. // Construction Params
  30545. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30546. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30547. var myAnyThis = _this;
  30548. var myAnySource = source;
  30549. myAnyThis._closePath = myAnySource._closePath;
  30550. myAnyThis._idx = myAnySource._idx;
  30551. myAnyThis.dashSize = myAnySource.dashSize;
  30552. myAnyThis.gapSize = myAnySource.gapSize;
  30553. myAnyThis.path3D = myAnySource.path3D;
  30554. myAnyThis.pathArray = myAnySource.pathArray;
  30555. myAnyThis.arc = myAnySource.arc;
  30556. myAnyThis.radius = myAnySource.radius;
  30557. // Animation ranges
  30558. if (_this._source._ranges) {
  30559. var ranges = _this._source._ranges;
  30560. for (var name in ranges) {
  30561. if (!ranges.hasOwnProperty(name)) {
  30562. continue;
  30563. }
  30564. if (!ranges[name]) {
  30565. continue;
  30566. }
  30567. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30568. }
  30569. }
  30570. // Metadata
  30571. if (source.metadata && source.metadata.clone) {
  30572. _this.metadata = source.metadata.clone();
  30573. }
  30574. else {
  30575. _this.metadata = source.metadata;
  30576. }
  30577. // Tags
  30578. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30579. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30580. }
  30581. // Parent
  30582. _this.parent = source.parent;
  30583. // Pivot
  30584. _this.setPivotMatrix(source.getPivotMatrix());
  30585. _this.id = name + "." + source.id;
  30586. // Material
  30587. _this.material = source.material;
  30588. var index;
  30589. if (!doNotCloneChildren) {
  30590. // Children
  30591. var directDescendants = source.getDescendants(true);
  30592. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30593. var child = directDescendants[index_1];
  30594. if (child.clone) {
  30595. child.clone(name + "." + child.name, _this);
  30596. }
  30597. }
  30598. }
  30599. // Physics clone
  30600. var physicsEngine = _this.getScene().getPhysicsEngine();
  30601. if (clonePhysicsImpostor && physicsEngine) {
  30602. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30603. if (impostor) {
  30604. _this.physicsImpostor = impostor.clone(_this);
  30605. }
  30606. }
  30607. // Particles
  30608. for (index = 0; index < scene.particleSystems.length; index++) {
  30609. var system = scene.particleSystems[index];
  30610. if (system.emitter === source) {
  30611. system.clone(system.name, _this);
  30612. }
  30613. }
  30614. _this.refreshBoundingInfo();
  30615. _this.computeWorldMatrix(true);
  30616. }
  30617. // Parent
  30618. if (parent !== null) {
  30619. _this.parent = parent;
  30620. }
  30621. return _this;
  30622. }
  30623. Object.defineProperty(Mesh, "FRONTSIDE", {
  30624. /**
  30625. * Mesh side orientation : usually the external or front surface
  30626. */
  30627. get: function () {
  30628. return Mesh._FRONTSIDE;
  30629. },
  30630. enumerable: true,
  30631. configurable: true
  30632. });
  30633. Object.defineProperty(Mesh, "BACKSIDE", {
  30634. /**
  30635. * Mesh side orientation : usually the internal or back surface
  30636. */
  30637. get: function () {
  30638. return Mesh._BACKSIDE;
  30639. },
  30640. enumerable: true,
  30641. configurable: true
  30642. });
  30643. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30644. /**
  30645. * Mesh side orientation : both internal and external or front and back surfaces
  30646. */
  30647. get: function () {
  30648. return Mesh._DOUBLESIDE;
  30649. },
  30650. enumerable: true,
  30651. configurable: true
  30652. });
  30653. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30654. /**
  30655. * Mesh side orientation : by default, `FRONTSIDE`
  30656. */
  30657. get: function () {
  30658. return Mesh._DEFAULTSIDE;
  30659. },
  30660. enumerable: true,
  30661. configurable: true
  30662. });
  30663. Object.defineProperty(Mesh, "NO_CAP", {
  30664. /**
  30665. * Mesh cap setting : no cap
  30666. */
  30667. get: function () {
  30668. return Mesh._NO_CAP;
  30669. },
  30670. enumerable: true,
  30671. configurable: true
  30672. });
  30673. Object.defineProperty(Mesh, "CAP_START", {
  30674. /**
  30675. * Mesh cap setting : one cap at the beginning of the mesh
  30676. */
  30677. get: function () {
  30678. return Mesh._CAP_START;
  30679. },
  30680. enumerable: true,
  30681. configurable: true
  30682. });
  30683. Object.defineProperty(Mesh, "CAP_END", {
  30684. /**
  30685. * Mesh cap setting : one cap at the end of the mesh
  30686. */
  30687. get: function () {
  30688. return Mesh._CAP_END;
  30689. },
  30690. enumerable: true,
  30691. configurable: true
  30692. });
  30693. Object.defineProperty(Mesh, "CAP_ALL", {
  30694. /**
  30695. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30696. */
  30697. get: function () {
  30698. return Mesh._CAP_ALL;
  30699. },
  30700. enumerable: true,
  30701. configurable: true
  30702. });
  30703. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30704. /**
  30705. * An event triggered before rendering the mesh
  30706. */
  30707. get: function () {
  30708. if (!this._onBeforeRenderObservable) {
  30709. this._onBeforeRenderObservable = new BABYLON.Observable();
  30710. }
  30711. return this._onBeforeRenderObservable;
  30712. },
  30713. enumerable: true,
  30714. configurable: true
  30715. });
  30716. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30717. /**
  30718. * An event triggered after rendering the mesh
  30719. */
  30720. get: function () {
  30721. if (!this._onAfterRenderObservable) {
  30722. this._onAfterRenderObservable = new BABYLON.Observable();
  30723. }
  30724. return this._onAfterRenderObservable;
  30725. },
  30726. enumerable: true,
  30727. configurable: true
  30728. });
  30729. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  30730. /**
  30731. * An event triggered before drawing the mesh
  30732. */
  30733. get: function () {
  30734. if (!this._onBeforeDrawObservable) {
  30735. this._onBeforeDrawObservable = new BABYLON.Observable();
  30736. }
  30737. return this._onBeforeDrawObservable;
  30738. },
  30739. enumerable: true,
  30740. configurable: true
  30741. });
  30742. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30743. set: function (callback) {
  30744. if (this._onBeforeDrawObserver) {
  30745. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30746. }
  30747. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30748. },
  30749. enumerable: true,
  30750. configurable: true
  30751. });
  30752. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30753. get: function () {
  30754. return this._morphTargetManager;
  30755. },
  30756. set: function (value) {
  30757. if (this._morphTargetManager === value) {
  30758. return;
  30759. }
  30760. this._morphTargetManager = value;
  30761. this._syncGeometryWithMorphTargetManager();
  30762. },
  30763. enumerable: true,
  30764. configurable: true
  30765. });
  30766. Object.defineProperty(Mesh.prototype, "source", {
  30767. get: function () {
  30768. return this._source;
  30769. },
  30770. enumerable: true,
  30771. configurable: true
  30772. });
  30773. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30774. get: function () {
  30775. return this._unIndexed;
  30776. },
  30777. set: function (value) {
  30778. if (this._unIndexed !== value) {
  30779. this._unIndexed = value;
  30780. this._markSubMeshesAsAttributesDirty();
  30781. }
  30782. },
  30783. enumerable: true,
  30784. configurable: true
  30785. });
  30786. // Methods
  30787. /**
  30788. * Returns the string "Mesh".
  30789. */
  30790. Mesh.prototype.getClassName = function () {
  30791. return "Mesh";
  30792. };
  30793. /**
  30794. * Returns a string.
  30795. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30796. */
  30797. Mesh.prototype.toString = function (fullDetails) {
  30798. var ret = _super.prototype.toString.call(this, fullDetails);
  30799. ret += ", n vertices: " + this.getTotalVertices();
  30800. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30801. if (this.animations) {
  30802. for (var i = 0; i < this.animations.length; i++) {
  30803. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30804. }
  30805. }
  30806. if (fullDetails) {
  30807. if (this._geometry) {
  30808. var ib = this.getIndices();
  30809. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30810. if (vb && ib) {
  30811. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30812. }
  30813. }
  30814. else {
  30815. ret += ", flat shading: UNKNOWN";
  30816. }
  30817. }
  30818. return ret;
  30819. };
  30820. /** @hidden */
  30821. Mesh.prototype._unBindEffect = function () {
  30822. _super.prototype._unBindEffect.call(this);
  30823. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30824. var instance = _a[_i];
  30825. instance._unBindEffect();
  30826. }
  30827. };
  30828. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30829. /**
  30830. * True if the mesh has some Levels Of Details (LOD).
  30831. * Returns a boolean.
  30832. */
  30833. get: function () {
  30834. return this._LODLevels.length > 0;
  30835. },
  30836. enumerable: true,
  30837. configurable: true
  30838. });
  30839. /**
  30840. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30841. * @returns an array of {BABYLON.MeshLODLevel}
  30842. */
  30843. Mesh.prototype.getLODLevels = function () {
  30844. return this._LODLevels;
  30845. };
  30846. Mesh.prototype._sortLODLevels = function () {
  30847. this._LODLevels.sort(function (a, b) {
  30848. if (a.distance < b.distance) {
  30849. return 1;
  30850. }
  30851. if (a.distance > b.distance) {
  30852. return -1;
  30853. }
  30854. return 0;
  30855. });
  30856. };
  30857. /**
  30858. * Add a mesh as LOD level triggered at the given distance.
  30859. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30860. * @param distance The distance from the center of the object to show this level
  30861. * @param mesh The mesh to be added as LOD level (can be null)
  30862. * @return This mesh (for chaining)
  30863. */
  30864. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30865. if (mesh && mesh._masterMesh) {
  30866. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30867. return this;
  30868. }
  30869. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30870. this._LODLevels.push(level);
  30871. if (mesh) {
  30872. mesh._masterMesh = this;
  30873. }
  30874. this._sortLODLevels();
  30875. return this;
  30876. };
  30877. /**
  30878. * Returns the LOD level mesh at the passed distance or null if not found.
  30879. * It is related to the method `addLODLevel(distance, mesh)`.
  30880. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30881. * Returns an object Mesh or `null`.
  30882. */
  30883. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30884. for (var index = 0; index < this._LODLevels.length; index++) {
  30885. var level = this._LODLevels[index];
  30886. if (level.distance === distance) {
  30887. return level.mesh;
  30888. }
  30889. }
  30890. return null;
  30891. };
  30892. /**
  30893. * Remove a mesh from the LOD array
  30894. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30895. * @param {Mesh} mesh The mesh to be removed.
  30896. * @return {Mesh} This mesh (for chaining)
  30897. */
  30898. Mesh.prototype.removeLODLevel = function (mesh) {
  30899. for (var index = 0; index < this._LODLevels.length; index++) {
  30900. if (this._LODLevels[index].mesh === mesh) {
  30901. this._LODLevels.splice(index, 1);
  30902. if (mesh) {
  30903. mesh._masterMesh = null;
  30904. }
  30905. }
  30906. }
  30907. this._sortLODLevels();
  30908. return this;
  30909. };
  30910. /**
  30911. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30912. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  30913. */
  30914. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30915. if (!this._LODLevels || this._LODLevels.length === 0) {
  30916. return this;
  30917. }
  30918. var bSphere;
  30919. if (boundingSphere) {
  30920. bSphere = boundingSphere;
  30921. }
  30922. else {
  30923. var boundingInfo = this.getBoundingInfo();
  30924. bSphere = boundingInfo.boundingSphere;
  30925. }
  30926. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30927. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30928. if (this.onLODLevelSelection) {
  30929. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30930. }
  30931. return this;
  30932. }
  30933. for (var index = 0; index < this._LODLevels.length; index++) {
  30934. var level = this._LODLevels[index];
  30935. if (level.distance < distanceToCamera) {
  30936. if (level.mesh) {
  30937. level.mesh._preActivate();
  30938. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30939. }
  30940. if (this.onLODLevelSelection) {
  30941. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30942. }
  30943. return level.mesh;
  30944. }
  30945. }
  30946. if (this.onLODLevelSelection) {
  30947. this.onLODLevelSelection(distanceToCamera, this, this);
  30948. }
  30949. return this;
  30950. };
  30951. Object.defineProperty(Mesh.prototype, "geometry", {
  30952. /**
  30953. * Returns the mesh internal Geometry object.
  30954. */
  30955. get: function () {
  30956. return this._geometry;
  30957. },
  30958. enumerable: true,
  30959. configurable: true
  30960. });
  30961. /**
  30962. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30963. */
  30964. Mesh.prototype.getTotalVertices = function () {
  30965. if (this._geometry === null || this._geometry === undefined) {
  30966. return 0;
  30967. }
  30968. return this._geometry.getTotalVertices();
  30969. };
  30970. /**
  30971. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30972. * 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.
  30973. * You can force the copy with forceCopy === true
  30974. * Returns null if the mesh has no geometry or no vertex buffer.
  30975. * Possible `kind` values :
  30976. * - BABYLON.VertexBuffer.PositionKind
  30977. * - BABYLON.VertexBuffer.UVKind
  30978. * - BABYLON.VertexBuffer.UV2Kind
  30979. * - BABYLON.VertexBuffer.UV3Kind
  30980. * - BABYLON.VertexBuffer.UV4Kind
  30981. * - BABYLON.VertexBuffer.UV5Kind
  30982. * - BABYLON.VertexBuffer.UV6Kind
  30983. * - BABYLON.VertexBuffer.ColorKind
  30984. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30985. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30986. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30987. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30988. */
  30989. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30990. if (!this._geometry) {
  30991. return null;
  30992. }
  30993. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30994. };
  30995. /**
  30996. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30997. * Returns `null` if the mesh has no geometry.
  30998. * Possible `kind` values :
  30999. * - BABYLON.VertexBuffer.PositionKind
  31000. * - BABYLON.VertexBuffer.UVKind
  31001. * - BABYLON.VertexBuffer.UV2Kind
  31002. * - BABYLON.VertexBuffer.UV3Kind
  31003. * - BABYLON.VertexBuffer.UV4Kind
  31004. * - BABYLON.VertexBuffer.UV5Kind
  31005. * - BABYLON.VertexBuffer.UV6Kind
  31006. * - BABYLON.VertexBuffer.ColorKind
  31007. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31008. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31009. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31010. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31011. */
  31012. Mesh.prototype.getVertexBuffer = function (kind) {
  31013. if (!this._geometry) {
  31014. return null;
  31015. }
  31016. return this._geometry.getVertexBuffer(kind);
  31017. };
  31018. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31019. if (!this._geometry) {
  31020. if (this._delayInfo) {
  31021. return this._delayInfo.indexOf(kind) !== -1;
  31022. }
  31023. return false;
  31024. }
  31025. return this._geometry.isVerticesDataPresent(kind);
  31026. };
  31027. /**
  31028. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31029. * Possible `kind` values :
  31030. * - BABYLON.VertexBuffer.PositionKind
  31031. * - BABYLON.VertexBuffer.UVKind
  31032. * - BABYLON.VertexBuffer.UV2Kind
  31033. * - BABYLON.VertexBuffer.UV3Kind
  31034. * - BABYLON.VertexBuffer.UV4Kind
  31035. * - BABYLON.VertexBuffer.UV5Kind
  31036. * - BABYLON.VertexBuffer.UV6Kind
  31037. * - BABYLON.VertexBuffer.ColorKind
  31038. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31039. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31040. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31041. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31042. */
  31043. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31044. if (!this._geometry) {
  31045. if (this._delayInfo) {
  31046. return this._delayInfo.indexOf(kind) !== -1;
  31047. }
  31048. return false;
  31049. }
  31050. return this._geometry.isVertexBufferUpdatable(kind);
  31051. };
  31052. /**
  31053. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31054. * Possible `kind` values :
  31055. * - BABYLON.VertexBuffer.PositionKind
  31056. * - BABYLON.VertexBuffer.UVKind
  31057. * - BABYLON.VertexBuffer.UV2Kind
  31058. * - BABYLON.VertexBuffer.UV3Kind
  31059. * - BABYLON.VertexBuffer.UV4Kind
  31060. * - BABYLON.VertexBuffer.UV5Kind
  31061. * - BABYLON.VertexBuffer.UV6Kind
  31062. * - BABYLON.VertexBuffer.ColorKind
  31063. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31064. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31065. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31066. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31067. */
  31068. Mesh.prototype.getVerticesDataKinds = function () {
  31069. if (!this._geometry) {
  31070. var result = new Array();
  31071. if (this._delayInfo) {
  31072. this._delayInfo.forEach(function (kind, index, array) {
  31073. result.push(kind);
  31074. });
  31075. }
  31076. return result;
  31077. }
  31078. return this._geometry.getVerticesDataKinds();
  31079. };
  31080. /**
  31081. * Returns a positive integer : the total number of indices in this mesh geometry.
  31082. * Returns zero if the mesh has no geometry.
  31083. */
  31084. Mesh.prototype.getTotalIndices = function () {
  31085. if (!this._geometry) {
  31086. return 0;
  31087. }
  31088. return this._geometry.getTotalIndices();
  31089. };
  31090. /**
  31091. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31092. * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31093. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31094. * @returns the indices array or an empty array if the mesh has no geometry
  31095. */
  31096. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31097. if (!this._geometry) {
  31098. return [];
  31099. }
  31100. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31101. };
  31102. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31103. get: function () {
  31104. return this._masterMesh !== null && this._masterMesh !== undefined;
  31105. },
  31106. enumerable: true,
  31107. configurable: true
  31108. });
  31109. /**
  31110. * Determine if the current mesh is ready to be rendered
  31111. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31112. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31113. * @returns true if all associated assets are ready (material, textures, shaders)
  31114. */
  31115. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31116. if (completeCheck === void 0) { completeCheck = false; }
  31117. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31118. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31119. return false;
  31120. }
  31121. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31122. return false;
  31123. }
  31124. if (!this.subMeshes || this.subMeshes.length === 0) {
  31125. return true;
  31126. }
  31127. if (!completeCheck) {
  31128. return true;
  31129. }
  31130. var engine = this.getEngine();
  31131. var scene = this.getScene();
  31132. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31133. this.computeWorldMatrix();
  31134. var mat = this.material || scene.defaultMaterial;
  31135. if (mat) {
  31136. if (mat.storeEffectOnSubMeshes) {
  31137. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31138. var subMesh = _a[_i];
  31139. var effectiveMaterial = subMesh.getMaterial();
  31140. if (effectiveMaterial) {
  31141. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31142. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31143. return false;
  31144. }
  31145. }
  31146. else {
  31147. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31148. return false;
  31149. }
  31150. }
  31151. }
  31152. }
  31153. }
  31154. else {
  31155. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31156. return false;
  31157. }
  31158. }
  31159. }
  31160. // Shadows
  31161. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31162. var light = _c[_b];
  31163. var generator = light.getShadowGenerator();
  31164. if (generator) {
  31165. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31166. var subMesh = _e[_d];
  31167. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31168. return false;
  31169. }
  31170. }
  31171. }
  31172. }
  31173. // LOD
  31174. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31175. var lod = _g[_f];
  31176. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31177. return false;
  31178. }
  31179. }
  31180. return true;
  31181. };
  31182. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31183. /**
  31184. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31185. * This property is pertinent only for updatable parametric shapes.
  31186. */
  31187. get: function () {
  31188. return this._areNormalsFrozen;
  31189. },
  31190. enumerable: true,
  31191. configurable: true
  31192. });
  31193. /**
  31194. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31195. * It has no effect at all on other shapes.
  31196. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31197. * Returns the Mesh.
  31198. */
  31199. Mesh.prototype.freezeNormals = function () {
  31200. this._areNormalsFrozen = true;
  31201. return this;
  31202. };
  31203. /**
  31204. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31205. * It has no effect at all on other shapes.
  31206. * It reactivates the mesh normals computation if it was previously frozen.
  31207. * Returns the Mesh.
  31208. */
  31209. Mesh.prototype.unfreezeNormals = function () {
  31210. this._areNormalsFrozen = false;
  31211. return this;
  31212. };
  31213. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31214. /**
  31215. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31216. */
  31217. set: function (count) {
  31218. this._overridenInstanceCount = count;
  31219. },
  31220. enumerable: true,
  31221. configurable: true
  31222. });
  31223. // Methods
  31224. /** @hidden */
  31225. Mesh.prototype._preActivate = function () {
  31226. var sceneRenderId = this.getScene().getRenderId();
  31227. if (this._preActivateId === sceneRenderId) {
  31228. return this;
  31229. }
  31230. this._preActivateId = sceneRenderId;
  31231. this._visibleInstances = null;
  31232. return this;
  31233. };
  31234. /** @hidden */
  31235. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31236. if (this._visibleInstances) {
  31237. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31238. }
  31239. return this;
  31240. };
  31241. /** @hidden */
  31242. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31243. if (!this._visibleInstances) {
  31244. this._visibleInstances = {};
  31245. this._visibleInstances.defaultRenderId = renderId;
  31246. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31247. }
  31248. if (!this._visibleInstances[renderId]) {
  31249. this._visibleInstances[renderId] = new Array();
  31250. }
  31251. this._visibleInstances[renderId].push(instance);
  31252. return this;
  31253. };
  31254. /**
  31255. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31256. * This means the mesh underlying bounding box and sphere are recomputed.
  31257. * Returns the Mesh.
  31258. */
  31259. Mesh.prototype.refreshBoundingInfo = function () {
  31260. return this._refreshBoundingInfo(false);
  31261. };
  31262. /** @hidden */
  31263. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31264. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31265. return this;
  31266. }
  31267. var data = this._getPositionData(applySkeleton);
  31268. if (data) {
  31269. var bias = this.geometry ? this.geometry.boundingBias : null;
  31270. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31271. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31272. }
  31273. if (this.subMeshes) {
  31274. for (var index = 0; index < this.subMeshes.length; index++) {
  31275. this.subMeshes[index].refreshBoundingInfo();
  31276. }
  31277. }
  31278. this._updateBoundingInfo();
  31279. return this;
  31280. };
  31281. Mesh.prototype._getPositionData = function (applySkeleton) {
  31282. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31283. if (data && applySkeleton && this.skeleton) {
  31284. data = BABYLON.Tools.Slice(data);
  31285. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31286. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31287. if (matricesWeightsData && matricesIndicesData) {
  31288. var needExtras = this.numBoneInfluencers > 4;
  31289. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31290. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31291. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31292. var tempVector = BABYLON.Tmp.Vector3[0];
  31293. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31294. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31295. var matWeightIdx = 0;
  31296. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31297. finalMatrix.reset();
  31298. var inf;
  31299. var weight;
  31300. for (inf = 0; inf < 4; inf++) {
  31301. weight = matricesWeightsData[matWeightIdx + inf];
  31302. if (weight > 0) {
  31303. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31304. finalMatrix.addToSelf(tempMatrix);
  31305. }
  31306. }
  31307. if (needExtras) {
  31308. for (inf = 0; inf < 4; inf++) {
  31309. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31310. if (weight > 0) {
  31311. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31312. finalMatrix.addToSelf(tempMatrix);
  31313. }
  31314. }
  31315. }
  31316. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31317. tempVector.toArray(data, index);
  31318. }
  31319. }
  31320. }
  31321. return data;
  31322. };
  31323. /** @hidden */
  31324. Mesh.prototype._createGlobalSubMesh = function (force) {
  31325. var totalVertices = this.getTotalVertices();
  31326. if (!totalVertices || !this.getIndices()) {
  31327. return null;
  31328. }
  31329. // Check if we need to recreate the submeshes
  31330. if (this.subMeshes && this.subMeshes.length > 0) {
  31331. var ib = this.getIndices();
  31332. if (!ib) {
  31333. return null;
  31334. }
  31335. var totalIndices = ib.length;
  31336. var needToRecreate = false;
  31337. if (force) {
  31338. needToRecreate = true;
  31339. }
  31340. else {
  31341. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31342. var submesh = _a[_i];
  31343. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31344. needToRecreate = true;
  31345. break;
  31346. }
  31347. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31348. needToRecreate = true;
  31349. break;
  31350. }
  31351. }
  31352. }
  31353. if (!needToRecreate) {
  31354. return this.subMeshes[0];
  31355. }
  31356. }
  31357. this.releaseSubMeshes();
  31358. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31359. };
  31360. Mesh.prototype.subdivide = function (count) {
  31361. if (count < 1) {
  31362. return;
  31363. }
  31364. var totalIndices = this.getTotalIndices();
  31365. var subdivisionSize = (totalIndices / count) | 0;
  31366. var offset = 0;
  31367. // Ensure that subdivisionSize is a multiple of 3
  31368. while (subdivisionSize % 3 !== 0) {
  31369. subdivisionSize++;
  31370. }
  31371. this.releaseSubMeshes();
  31372. for (var index = 0; index < count; index++) {
  31373. if (offset >= totalIndices) {
  31374. break;
  31375. }
  31376. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31377. offset += subdivisionSize;
  31378. }
  31379. this.synchronizeInstances();
  31380. };
  31381. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31382. if (updatable === void 0) { updatable = false; }
  31383. if (!this._geometry) {
  31384. var vertexData = new BABYLON.VertexData();
  31385. vertexData.set(data, kind);
  31386. var scene = this.getScene();
  31387. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31388. }
  31389. else {
  31390. this._geometry.setVerticesData(kind, data, updatable, stride);
  31391. }
  31392. return this;
  31393. };
  31394. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31395. if (updatable === void 0) { updatable = true; }
  31396. var vb = this.getVertexBuffer(kind);
  31397. if (!vb || vb.isUpdatable() === updatable) {
  31398. return;
  31399. }
  31400. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31401. };
  31402. /**
  31403. * Sets the mesh VertexBuffer.
  31404. * Returns the Mesh.
  31405. */
  31406. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31407. if (!this._geometry) {
  31408. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31409. }
  31410. this._geometry.setVerticesBuffer(buffer);
  31411. return this;
  31412. };
  31413. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31414. if (!this._geometry) {
  31415. return this;
  31416. }
  31417. if (!makeItUnique) {
  31418. this._geometry.updateVerticesData(kind, data, updateExtends);
  31419. }
  31420. else {
  31421. this.makeGeometryUnique();
  31422. this.updateVerticesData(kind, data, updateExtends, false);
  31423. }
  31424. return this;
  31425. };
  31426. /**
  31427. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31428. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31429. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31430. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31431. * Returns the Mesh.
  31432. */
  31433. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31434. if (computeNormals === void 0) { computeNormals = true; }
  31435. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31436. if (!positions) {
  31437. return this;
  31438. }
  31439. positionFunction(positions);
  31440. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31441. if (computeNormals) {
  31442. var indices = this.getIndices();
  31443. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31444. if (!normals) {
  31445. return this;
  31446. }
  31447. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31448. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31449. }
  31450. return this;
  31451. };
  31452. /**
  31453. * Creates a un-shared specific occurence of the geometry for the mesh.
  31454. * Returns the Mesh.
  31455. */
  31456. Mesh.prototype.makeGeometryUnique = function () {
  31457. if (!this._geometry) {
  31458. return this;
  31459. }
  31460. var oldGeometry = this._geometry;
  31461. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31462. oldGeometry.releaseForMesh(this, true);
  31463. geometry.applyToMesh(this);
  31464. return this;
  31465. };
  31466. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31467. if (totalVertices === void 0) { totalVertices = null; }
  31468. if (updatable === void 0) { updatable = false; }
  31469. if (!this._geometry) {
  31470. var vertexData = new BABYLON.VertexData();
  31471. vertexData.indices = indices;
  31472. var scene = this.getScene();
  31473. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31474. }
  31475. else {
  31476. this._geometry.setIndices(indices, totalVertices, updatable);
  31477. }
  31478. return this;
  31479. };
  31480. /**
  31481. * Update the current index buffer
  31482. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31483. * Returns the Mesh.
  31484. */
  31485. Mesh.prototype.updateIndices = function (indices, offset) {
  31486. if (!this._geometry) {
  31487. return this;
  31488. }
  31489. this._geometry.updateIndices(indices, offset);
  31490. return this;
  31491. };
  31492. /**
  31493. * Invert the geometry to move from a right handed system to a left handed one.
  31494. * Returns the Mesh.
  31495. */
  31496. Mesh.prototype.toLeftHanded = function () {
  31497. if (!this._geometry) {
  31498. return this;
  31499. }
  31500. this._geometry.toLeftHanded();
  31501. return this;
  31502. };
  31503. /** @hidden */
  31504. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31505. if (!this._geometry) {
  31506. return this;
  31507. }
  31508. var engine = this.getScene().getEngine();
  31509. // Wireframe
  31510. var indexToBind;
  31511. if (this._unIndexed) {
  31512. indexToBind = null;
  31513. }
  31514. else {
  31515. switch (fillMode) {
  31516. case BABYLON.Material.PointFillMode:
  31517. indexToBind = null;
  31518. break;
  31519. case BABYLON.Material.WireFrameFillMode:
  31520. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31521. break;
  31522. default:
  31523. case BABYLON.Material.TriangleFillMode:
  31524. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31525. break;
  31526. }
  31527. }
  31528. // VBOs
  31529. this._geometry._bind(effect, indexToBind);
  31530. return this;
  31531. };
  31532. /** @hidden */
  31533. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31534. if (alternate === void 0) { alternate = false; }
  31535. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31536. return this;
  31537. }
  31538. if (this._onBeforeDrawObservable) {
  31539. this._onBeforeDrawObservable.notifyObservers(this);
  31540. }
  31541. var scene = this.getScene();
  31542. var engine = scene.getEngine();
  31543. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31544. // or triangles as points
  31545. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31546. }
  31547. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31548. // Triangles as wireframe
  31549. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31550. }
  31551. else {
  31552. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31553. }
  31554. if (scene._isAlternateRenderingEnabled && !alternate) {
  31555. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31556. if (!effect || !scene.activeCamera) {
  31557. return this;
  31558. }
  31559. scene._switchToAlternateCameraConfiguration(true);
  31560. this._effectiveMaterial.bindView(effect);
  31561. this._effectiveMaterial.bindViewProjection(effect);
  31562. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31563. this._draw(subMesh, fillMode, instancesCount, true);
  31564. engine.setViewport(scene.activeCamera.viewport);
  31565. scene._switchToAlternateCameraConfiguration(false);
  31566. this._effectiveMaterial.bindView(effect);
  31567. this._effectiveMaterial.bindViewProjection(effect);
  31568. }
  31569. return this;
  31570. };
  31571. /**
  31572. * Registers for this mesh a javascript function called just before the rendering process.
  31573. * This function is passed the current mesh.
  31574. * Return the Mesh.
  31575. */
  31576. Mesh.prototype.registerBeforeRender = function (func) {
  31577. this.onBeforeRenderObservable.add(func);
  31578. return this;
  31579. };
  31580. /**
  31581. * Disposes a previously registered javascript function called before the rendering.
  31582. * This function is passed the current mesh.
  31583. * Returns the Mesh.
  31584. */
  31585. Mesh.prototype.unregisterBeforeRender = function (func) {
  31586. this.onBeforeRenderObservable.removeCallback(func);
  31587. return this;
  31588. };
  31589. /**
  31590. * Registers for this mesh a javascript function called just after the rendering is complete.
  31591. * This function is passed the current mesh.
  31592. * Returns the Mesh.
  31593. */
  31594. Mesh.prototype.registerAfterRender = function (func) {
  31595. this.onAfterRenderObservable.add(func);
  31596. return this;
  31597. };
  31598. /**
  31599. * Disposes a previously registered javascript function called after the rendering.
  31600. * This function is passed the current mesh.
  31601. * Return the Mesh.
  31602. */
  31603. Mesh.prototype.unregisterAfterRender = function (func) {
  31604. this.onAfterRenderObservable.removeCallback(func);
  31605. return this;
  31606. };
  31607. /** @hidden */
  31608. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31609. var scene = this.getScene();
  31610. this._batchCache.mustReturn = false;
  31611. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31612. this._batchCache.visibleInstances[subMeshId] = null;
  31613. if (this._visibleInstances) {
  31614. var currentRenderId = scene.getRenderId();
  31615. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31616. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31617. var selfRenderId = this._renderId;
  31618. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31619. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31620. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31621. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31622. }
  31623. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31624. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31625. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31626. this._batchCache.mustReturn = true;
  31627. return this._batchCache;
  31628. }
  31629. if (currentRenderId !== selfRenderId) {
  31630. this._batchCache.renderSelf[subMeshId] = false;
  31631. }
  31632. }
  31633. this._renderIdForInstances[subMeshId] = currentRenderId;
  31634. }
  31635. return this._batchCache;
  31636. };
  31637. /** @hidden */
  31638. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31639. var visibleInstances = batch.visibleInstances[subMesh._id];
  31640. if (!visibleInstances) {
  31641. return this;
  31642. }
  31643. var matricesCount = visibleInstances.length + 1;
  31644. var bufferSize = matricesCount * 16 * 4;
  31645. var currentInstancesBufferSize = this._instancesBufferSize;
  31646. var instancesBuffer = this._instancesBuffer;
  31647. while (this._instancesBufferSize < bufferSize) {
  31648. this._instancesBufferSize *= 2;
  31649. }
  31650. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31651. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31652. }
  31653. var offset = 0;
  31654. var instancesCount = 0;
  31655. var world = this.getWorldMatrix();
  31656. if (batch.renderSelf[subMesh._id]) {
  31657. world.copyToArray(this._instancesData, offset);
  31658. offset += 16;
  31659. instancesCount++;
  31660. }
  31661. if (visibleInstances) {
  31662. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31663. var instance = visibleInstances[instanceIndex];
  31664. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31665. offset += 16;
  31666. instancesCount++;
  31667. }
  31668. }
  31669. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31670. if (instancesBuffer) {
  31671. instancesBuffer.dispose();
  31672. }
  31673. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31674. this._instancesBuffer = instancesBuffer;
  31675. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31676. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31677. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31678. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31679. }
  31680. else {
  31681. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31682. }
  31683. this._bind(subMesh, effect, fillMode);
  31684. this._draw(subMesh, fillMode, instancesCount);
  31685. engine.unbindInstanceAttributes();
  31686. return this;
  31687. };
  31688. /** @hidden */
  31689. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31690. var scene = this.getScene();
  31691. var engine = scene.getEngine();
  31692. if (hardwareInstancedRendering) {
  31693. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31694. }
  31695. else {
  31696. if (batch.renderSelf[subMesh._id]) {
  31697. // Draw
  31698. if (onBeforeDraw) {
  31699. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31700. }
  31701. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31702. }
  31703. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31704. if (visibleInstancesForSubMesh) {
  31705. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31706. var instance = visibleInstancesForSubMesh[instanceIndex];
  31707. // World
  31708. var world = instance.getWorldMatrix();
  31709. if (onBeforeDraw) {
  31710. onBeforeDraw(true, world, effectiveMaterial);
  31711. }
  31712. // Draw
  31713. this._draw(subMesh, fillMode);
  31714. }
  31715. }
  31716. }
  31717. return this;
  31718. };
  31719. /**
  31720. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  31721. * @param subMesh defines the subMesh to render
  31722. * @param enableAlphaMode defines if alpha mode can be changed
  31723. * @returns the current mesh
  31724. */
  31725. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31726. this._checkOcclusionQuery();
  31727. if (this._isOccluded) {
  31728. return this;
  31729. }
  31730. var scene = this.getScene();
  31731. // Managing instances
  31732. var batch = this._getInstancesRenderList(subMesh._id);
  31733. if (batch.mustReturn) {
  31734. return this;
  31735. }
  31736. // Checking geometry state
  31737. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31738. return this;
  31739. }
  31740. if (this._onBeforeRenderObservable) {
  31741. this._onBeforeRenderObservable.notifyObservers(this);
  31742. }
  31743. var engine = scene.getEngine();
  31744. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31745. // Material
  31746. var material = subMesh.getMaterial();
  31747. if (!material) {
  31748. return this;
  31749. }
  31750. this._effectiveMaterial = material;
  31751. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31752. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31753. return this;
  31754. }
  31755. }
  31756. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31757. return this;
  31758. }
  31759. // Alpha mode
  31760. if (enableAlphaMode) {
  31761. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31762. }
  31763. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  31764. var step = _a[_i];
  31765. step.action(this, subMesh, batch);
  31766. }
  31767. var effect;
  31768. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31769. effect = subMesh.effect;
  31770. }
  31771. else {
  31772. effect = this._effectiveMaterial.getEffect();
  31773. }
  31774. if (!effect) {
  31775. return this;
  31776. }
  31777. var sideOrientation = this.overrideMaterialSideOrientation;
  31778. if (sideOrientation == null) {
  31779. sideOrientation = this._effectiveMaterial.sideOrientation;
  31780. if (this._getWorldMatrixDeterminant() < 0) {
  31781. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31782. }
  31783. }
  31784. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31785. if (this._effectiveMaterial.forceDepthWrite) {
  31786. engine.setDepthWrite(true);
  31787. }
  31788. // Bind
  31789. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31790. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31791. this._bind(subMesh, effect, fillMode);
  31792. }
  31793. var world = this.getWorldMatrix();
  31794. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31795. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31796. }
  31797. else {
  31798. this._effectiveMaterial.bind(world, this);
  31799. }
  31800. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31801. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31802. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31803. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31804. }
  31805. // Draw
  31806. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31807. // Unbind
  31808. this._effectiveMaterial.unbind();
  31809. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  31810. var step = _c[_b];
  31811. step.action(this, subMesh, batch);
  31812. }
  31813. if (this._onAfterRenderObservable) {
  31814. this._onAfterRenderObservable.notifyObservers(this);
  31815. }
  31816. return this;
  31817. };
  31818. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31819. if (isInstance && effectiveMaterial) {
  31820. effectiveMaterial.bindOnlyWorldMatrix(world);
  31821. }
  31822. };
  31823. /**
  31824. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  31825. */
  31826. Mesh.prototype.getEmittedParticleSystems = function () {
  31827. var results = new Array();
  31828. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31829. var particleSystem = this.getScene().particleSystems[index];
  31830. if (particleSystem.emitter === this) {
  31831. results.push(particleSystem);
  31832. }
  31833. }
  31834. return results;
  31835. };
  31836. /**
  31837. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  31838. */
  31839. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31840. var results = new Array();
  31841. var descendants = this.getDescendants();
  31842. descendants.push(this);
  31843. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31844. var particleSystem = this.getScene().particleSystems[index];
  31845. var emitter = particleSystem.emitter;
  31846. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31847. results.push(particleSystem);
  31848. }
  31849. }
  31850. return results;
  31851. };
  31852. /**
  31853. * Normalize matrix weights so that all vertices have a total weight set to 1
  31854. */
  31855. Mesh.prototype.cleanMatrixWeights = function () {
  31856. var epsilon = 1e-3;
  31857. var noInfluenceBoneIndex = 0.0;
  31858. if (this.skeleton) {
  31859. noInfluenceBoneIndex = this.skeleton.bones.length;
  31860. }
  31861. else {
  31862. return;
  31863. }
  31864. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31865. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31866. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31867. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31868. var influencers = this.numBoneInfluencers;
  31869. var size = matricesWeights.length;
  31870. for (var i = 0; i < size; i += 4) {
  31871. var weight = 0.0;
  31872. var firstZeroWeight = -1;
  31873. for (var j = 0; j < 4; j++) {
  31874. var w = matricesWeights[i + j];
  31875. weight += w;
  31876. if (w < epsilon && firstZeroWeight < 0) {
  31877. firstZeroWeight = j;
  31878. }
  31879. }
  31880. if (matricesWeightsExtra) {
  31881. for (var j = 0; j < 4; j++) {
  31882. var w = matricesWeightsExtra[i + j];
  31883. weight += w;
  31884. if (w < epsilon && firstZeroWeight < 0) {
  31885. firstZeroWeight = j + 4;
  31886. }
  31887. }
  31888. }
  31889. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31890. firstZeroWeight = influencers - 1;
  31891. }
  31892. if (weight > epsilon) {
  31893. var mweight = 1.0 / weight;
  31894. for (var j = 0; j < 4; j++) {
  31895. matricesWeights[i + j] *= mweight;
  31896. }
  31897. if (matricesWeightsExtra) {
  31898. for (var j = 0; j < 4; j++) {
  31899. matricesWeightsExtra[i + j] *= mweight;
  31900. }
  31901. }
  31902. }
  31903. else {
  31904. if (firstZeroWeight >= 4) {
  31905. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31906. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31907. }
  31908. else {
  31909. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31910. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31911. }
  31912. }
  31913. }
  31914. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31915. if (matricesIndicesExtra) {
  31916. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31917. }
  31918. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  31919. if (matricesWeightsExtra) {
  31920. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  31921. }
  31922. };
  31923. /** @hidden */
  31924. Mesh.prototype._checkDelayState = function () {
  31925. var scene = this.getScene();
  31926. if (this._geometry) {
  31927. this._geometry.load(scene);
  31928. }
  31929. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31930. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31931. this._queueLoad(scene);
  31932. }
  31933. return this;
  31934. };
  31935. Mesh.prototype._queueLoad = function (scene) {
  31936. var _this = this;
  31937. scene._addPendingData(this);
  31938. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31939. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31940. if (data instanceof ArrayBuffer) {
  31941. _this._delayLoadingFunction(data, _this);
  31942. }
  31943. else {
  31944. _this._delayLoadingFunction(JSON.parse(data), _this);
  31945. }
  31946. _this.instances.forEach(function (instance) {
  31947. instance._syncSubMeshes();
  31948. });
  31949. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31950. scene._removePendingData(_this);
  31951. }, function () { }, scene.database, getBinaryData);
  31952. return this;
  31953. };
  31954. /**
  31955. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  31956. * A mesh is in the frustum if its bounding box intersects the frustum
  31957. * @param frustumPlanes defines the frustum to test
  31958. * @returns true if the mesh is in the frustum planes
  31959. */
  31960. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31961. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31962. return false;
  31963. }
  31964. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31965. return false;
  31966. }
  31967. this._checkDelayState();
  31968. return true;
  31969. };
  31970. /**
  31971. * Sets the mesh material by the material or multiMaterial `id` property.
  31972. * The material `id` is a string identifying the material or the multiMaterial.
  31973. * This method returns the Mesh.
  31974. */
  31975. Mesh.prototype.setMaterialByID = function (id) {
  31976. var materials = this.getScene().materials;
  31977. var index;
  31978. for (index = materials.length - 1; index > -1; index--) {
  31979. if (materials[index].id === id) {
  31980. this.material = materials[index];
  31981. return this;
  31982. }
  31983. }
  31984. // Multi
  31985. var multiMaterials = this.getScene().multiMaterials;
  31986. for (index = multiMaterials.length - 1; index > -1; index--) {
  31987. if (multiMaterials[index].id === id) {
  31988. this.material = multiMaterials[index];
  31989. return this;
  31990. }
  31991. }
  31992. return this;
  31993. };
  31994. /**
  31995. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31996. */
  31997. Mesh.prototype.getAnimatables = function () {
  31998. var results = new Array();
  31999. if (this.material) {
  32000. results.push(this.material);
  32001. }
  32002. if (this.skeleton) {
  32003. results.push(this.skeleton);
  32004. }
  32005. return results;
  32006. };
  32007. /**
  32008. * Modifies the mesh geometry according to the passed transformation matrix.
  32009. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32010. * The mesh normals are modified using the same transformation.
  32011. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32012. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32013. * Returns the Mesh.
  32014. */
  32015. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32016. // Position
  32017. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32018. return this;
  32019. }
  32020. var submeshes = this.subMeshes.splice(0);
  32021. this._resetPointsArrayCache();
  32022. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32023. var temp = new Array();
  32024. var index;
  32025. for (index = 0; index < data.length; index += 3) {
  32026. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32027. }
  32028. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32029. // Normals
  32030. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32031. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32032. temp = [];
  32033. for (index = 0; index < data.length; index += 3) {
  32034. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32035. }
  32036. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32037. }
  32038. // flip faces?
  32039. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32040. this.flipFaces();
  32041. }
  32042. // Restore submeshes
  32043. this.releaseSubMeshes();
  32044. this.subMeshes = submeshes;
  32045. return this;
  32046. };
  32047. /**
  32048. * Modifies the mesh geometry according to its own current World Matrix.
  32049. * The mesh World Matrix is then reset.
  32050. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32051. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32052. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32053. * Returns the Mesh.
  32054. */
  32055. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32056. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32057. this.scaling.copyFromFloats(1, 1, 1);
  32058. this.position.copyFromFloats(0, 0, 0);
  32059. this.rotation.copyFromFloats(0, 0, 0);
  32060. //only if quaternion is already set
  32061. if (this.rotationQuaternion) {
  32062. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32063. }
  32064. this._worldMatrix = BABYLON.Matrix.Identity();
  32065. return this;
  32066. };
  32067. Object.defineProperty(Mesh.prototype, "_positions", {
  32068. // Cache
  32069. get: function () {
  32070. if (this._geometry) {
  32071. return this._geometry._positions;
  32072. }
  32073. return null;
  32074. },
  32075. enumerable: true,
  32076. configurable: true
  32077. });
  32078. /** @hidden */
  32079. Mesh.prototype._resetPointsArrayCache = function () {
  32080. if (this._geometry) {
  32081. this._geometry._resetPointsArrayCache();
  32082. }
  32083. return this;
  32084. };
  32085. /** @hidden */
  32086. Mesh.prototype._generatePointsArray = function () {
  32087. if (this._geometry) {
  32088. return this._geometry._generatePointsArray();
  32089. }
  32090. return false;
  32091. };
  32092. /**
  32093. * Returns a new Mesh object generated from the current mesh properties.
  32094. * This method must not get confused with createInstance().
  32095. * The parameter `name` is a string, the name given to the new mesh.
  32096. * The optional parameter `newParent` can be any Node object (default `null`).
  32097. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32098. * 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.
  32099. */
  32100. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32101. if (name === void 0) { name = ""; }
  32102. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32103. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32104. };
  32105. /**
  32106. * Releases resources associated with this mesh.
  32107. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32108. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32109. */
  32110. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32111. var _this = this;
  32112. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32113. this.morphTargetManager = null;
  32114. if (this._geometry) {
  32115. this._geometry.releaseForMesh(this, true);
  32116. }
  32117. if (this._onBeforeDrawObservable) {
  32118. this._onBeforeDrawObservable.clear();
  32119. }
  32120. if (this._onBeforeRenderObservable) {
  32121. this._onBeforeRenderObservable.clear();
  32122. }
  32123. if (this._onAfterRenderObservable) {
  32124. this._onAfterRenderObservable.clear();
  32125. }
  32126. // Sources
  32127. var meshes = this.getScene().meshes;
  32128. meshes.forEach(function (abstractMesh) {
  32129. var mesh = abstractMesh;
  32130. if (mesh._source && mesh._source === _this) {
  32131. mesh._source = null;
  32132. }
  32133. });
  32134. this._source = null;
  32135. // Instances
  32136. if (this._instancesBuffer) {
  32137. this._instancesBuffer.dispose();
  32138. this._instancesBuffer = null;
  32139. }
  32140. while (this.instances.length) {
  32141. this.instances[0].dispose();
  32142. }
  32143. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32144. };
  32145. /**
  32146. * Modifies the mesh geometry according to a displacement map.
  32147. * 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.
  32148. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32149. * This method returns nothing.
  32150. * @param url is a string, the URL from the image file is to be downloaded.
  32151. * @param minHeight is the lower limit of the displacement.
  32152. * @param maxHeight is the upper limit of the displacement.
  32153. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32154. * @param uvOffset is an optional vector2 used to offset UV.
  32155. * @param uvScale is an optional vector2 used to scale UV.
  32156. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32157. * @returns the Mesh.
  32158. */
  32159. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32160. var _this = this;
  32161. if (forceUpdate === void 0) { forceUpdate = false; }
  32162. var scene = this.getScene();
  32163. var onload = function (img) {
  32164. // Getting height map data
  32165. var canvas = document.createElement("canvas");
  32166. var context = canvas.getContext("2d");
  32167. var heightMapWidth = img.width;
  32168. var heightMapHeight = img.height;
  32169. canvas.width = heightMapWidth;
  32170. canvas.height = heightMapHeight;
  32171. context.drawImage(img, 0, 0);
  32172. // Create VertexData from map data
  32173. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32174. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32175. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32176. //execute success callback, if set
  32177. if (onSuccess) {
  32178. onSuccess(_this);
  32179. }
  32180. };
  32181. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32182. return this;
  32183. };
  32184. /**
  32185. * Modifies the mesh geometry according to a displacementMap buffer.
  32186. * 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.
  32187. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32188. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32189. * @param heightMapWidth is the width of the buffer image.
  32190. * @param heightMapHeight is the height of the buffer image.
  32191. * @param minHeight is the lower limit of the displacement.
  32192. * @param maxHeight is the upper limit of the displacement.
  32193. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32194. * @param uvOffset is an optional vector2 used to offset UV.
  32195. * @param uvScale is an optional vector2 used to scale UV.
  32196. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32197. * @returns the Mesh.
  32198. */
  32199. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32200. if (forceUpdate === void 0) { forceUpdate = false; }
  32201. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32202. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32203. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32204. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32205. return this;
  32206. }
  32207. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32208. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32209. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32210. var position = BABYLON.Vector3.Zero();
  32211. var normal = BABYLON.Vector3.Zero();
  32212. var uv = BABYLON.Vector2.Zero();
  32213. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32214. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32215. for (var index = 0; index < positions.length; index += 3) {
  32216. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32217. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32218. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32219. // Compute height
  32220. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32221. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32222. var pos = (u + v * heightMapWidth) * 4;
  32223. var r = buffer[pos] / 255.0;
  32224. var g = buffer[pos + 1] / 255.0;
  32225. var b = buffer[pos + 2] / 255.0;
  32226. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32227. normal.normalize();
  32228. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32229. position = position.add(normal);
  32230. position.toArray(positions, index);
  32231. }
  32232. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32233. if (forceUpdate) {
  32234. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32235. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32236. }
  32237. else {
  32238. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32239. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32240. }
  32241. return this;
  32242. };
  32243. /**
  32244. * Modify the mesh to get a flat shading rendering.
  32245. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32246. * This method returns the Mesh.
  32247. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32248. */
  32249. Mesh.prototype.convertToFlatShadedMesh = function () {
  32250. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32251. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32252. var kinds = this.getVerticesDataKinds();
  32253. var vbs = {};
  32254. var data = {};
  32255. var newdata = {};
  32256. var updatableNormals = false;
  32257. var kindIndex;
  32258. var kind;
  32259. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32260. kind = kinds[kindIndex];
  32261. var vertexBuffer = this.getVertexBuffer(kind);
  32262. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32263. updatableNormals = vertexBuffer.isUpdatable();
  32264. kinds.splice(kindIndex, 1);
  32265. kindIndex--;
  32266. continue;
  32267. }
  32268. vbs[kind] = vertexBuffer;
  32269. data[kind] = vbs[kind].getData();
  32270. newdata[kind] = [];
  32271. }
  32272. // Save previous submeshes
  32273. var previousSubmeshes = this.subMeshes.slice(0);
  32274. var indices = this.getIndices();
  32275. var totalIndices = this.getTotalIndices();
  32276. // Generating unique vertices per face
  32277. var index;
  32278. for (index = 0; index < totalIndices; index++) {
  32279. var vertexIndex = indices[index];
  32280. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32281. kind = kinds[kindIndex];
  32282. var stride = vbs[kind].getStrideSize();
  32283. for (var offset = 0; offset < stride; offset++) {
  32284. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32285. }
  32286. }
  32287. }
  32288. // Updating faces & normal
  32289. var normals = [];
  32290. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32291. for (index = 0; index < totalIndices; index += 3) {
  32292. indices[index] = index;
  32293. indices[index + 1] = index + 1;
  32294. indices[index + 2] = index + 2;
  32295. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32296. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32297. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32298. var p1p2 = p1.subtract(p2);
  32299. var p3p2 = p3.subtract(p2);
  32300. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32301. // Store same normals for every vertex
  32302. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32303. normals.push(normal.x);
  32304. normals.push(normal.y);
  32305. normals.push(normal.z);
  32306. }
  32307. }
  32308. this.setIndices(indices);
  32309. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32310. // Updating vertex buffers
  32311. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32312. kind = kinds[kindIndex];
  32313. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32314. }
  32315. // Updating submeshes
  32316. this.releaseSubMeshes();
  32317. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32318. var previousOne = previousSubmeshes[submeshIndex];
  32319. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32320. }
  32321. this.synchronizeInstances();
  32322. return this;
  32323. };
  32324. /**
  32325. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32326. * In other words, more vertices, no more indices and a single bigger VBO.
  32327. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32328. * Returns the Mesh.
  32329. */
  32330. Mesh.prototype.convertToUnIndexedMesh = function () {
  32331. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32332. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32333. var kinds = this.getVerticesDataKinds();
  32334. var vbs = {};
  32335. var data = {};
  32336. var newdata = {};
  32337. var kindIndex;
  32338. var kind;
  32339. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32340. kind = kinds[kindIndex];
  32341. var vertexBuffer = this.getVertexBuffer(kind);
  32342. vbs[kind] = vertexBuffer;
  32343. data[kind] = vbs[kind].getData();
  32344. newdata[kind] = [];
  32345. }
  32346. // Save previous submeshes
  32347. var previousSubmeshes = this.subMeshes.slice(0);
  32348. var indices = this.getIndices();
  32349. var totalIndices = this.getTotalIndices();
  32350. // Generating unique vertices per face
  32351. var index;
  32352. for (index = 0; index < totalIndices; index++) {
  32353. var vertexIndex = indices[index];
  32354. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32355. kind = kinds[kindIndex];
  32356. var stride = vbs[kind].getStrideSize();
  32357. for (var offset = 0; offset < stride; offset++) {
  32358. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32359. }
  32360. }
  32361. }
  32362. // Updating indices
  32363. for (index = 0; index < totalIndices; index += 3) {
  32364. indices[index] = index;
  32365. indices[index + 1] = index + 1;
  32366. indices[index + 2] = index + 2;
  32367. }
  32368. this.setIndices(indices);
  32369. // Updating vertex buffers
  32370. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32371. kind = kinds[kindIndex];
  32372. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32373. }
  32374. // Updating submeshes
  32375. this.releaseSubMeshes();
  32376. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32377. var previousOne = previousSubmeshes[submeshIndex];
  32378. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32379. }
  32380. this._unIndexed = true;
  32381. this.synchronizeInstances();
  32382. return this;
  32383. };
  32384. /**
  32385. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32386. * This method returns the Mesh.
  32387. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32388. */
  32389. Mesh.prototype.flipFaces = function (flipNormals) {
  32390. if (flipNormals === void 0) { flipNormals = false; }
  32391. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32392. var i;
  32393. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32394. for (i = 0; i < vertex_data.normals.length; i++) {
  32395. vertex_data.normals[i] *= -1;
  32396. }
  32397. }
  32398. if (vertex_data.indices) {
  32399. var temp;
  32400. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32401. // reassign indices
  32402. temp = vertex_data.indices[i + 1];
  32403. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32404. vertex_data.indices[i + 2] = temp;
  32405. }
  32406. }
  32407. vertex_data.applyToMesh(this);
  32408. return this;
  32409. };
  32410. // Instances
  32411. /**
  32412. * Creates a new InstancedMesh object from the mesh model.
  32413. * An instance shares the same properties and the same material than its model.
  32414. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32415. * Only these properties of each instance can then be set individually :
  32416. * - position
  32417. * - rotation
  32418. * - rotationQuaternion
  32419. * - setPivotMatrix
  32420. * - scaling
  32421. *
  32422. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32423. * Warning : this method is not supported for Line mesh and LineSystem
  32424. */
  32425. Mesh.prototype.createInstance = function (name) {
  32426. return new BABYLON.InstancedMesh(name, this);
  32427. };
  32428. /**
  32429. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32430. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32431. * This method returns the Mesh.
  32432. */
  32433. Mesh.prototype.synchronizeInstances = function () {
  32434. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32435. var instance = this.instances[instanceIndex];
  32436. instance._syncSubMeshes();
  32437. }
  32438. return this;
  32439. };
  32440. /**
  32441. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32442. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32443. * This should be used together with the simplification to avoid disappearing triangles.
  32444. * Returns the Mesh.
  32445. * @param successCallback an optional success callback to be called after the optimization finished.
  32446. */
  32447. Mesh.prototype.optimizeIndices = function (successCallback) {
  32448. var _this = this;
  32449. var indices = this.getIndices();
  32450. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32451. if (!positions || !indices) {
  32452. return this;
  32453. }
  32454. var vectorPositions = new Array();
  32455. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32456. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32457. }
  32458. var dupes = new Array();
  32459. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32460. var realPos = vectorPositions.length - 1 - iteration;
  32461. var testedPosition = vectorPositions[realPos];
  32462. for (var j = 0; j < realPos; ++j) {
  32463. var againstPosition = vectorPositions[j];
  32464. if (testedPosition.equals(againstPosition)) {
  32465. dupes[realPos] = j;
  32466. break;
  32467. }
  32468. }
  32469. }, function () {
  32470. for (var i = 0; i < indices.length; ++i) {
  32471. indices[i] = dupes[indices[i]] || indices[i];
  32472. }
  32473. //indices are now reordered
  32474. var originalSubMeshes = _this.subMeshes.slice(0);
  32475. _this.setIndices(indices);
  32476. _this.subMeshes = originalSubMeshes;
  32477. if (successCallback) {
  32478. successCallback(_this);
  32479. }
  32480. });
  32481. return this;
  32482. };
  32483. Mesh.prototype.serialize = function (serializationObject) {
  32484. serializationObject.name = this.name;
  32485. serializationObject.id = this.id;
  32486. serializationObject.type = this.getClassName();
  32487. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32488. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32489. }
  32490. serializationObject.position = this.position.asArray();
  32491. if (this.rotationQuaternion) {
  32492. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32493. }
  32494. else if (this.rotation) {
  32495. serializationObject.rotation = this.rotation.asArray();
  32496. }
  32497. serializationObject.scaling = this.scaling.asArray();
  32498. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32499. serializationObject.isEnabled = this.isEnabled(false);
  32500. serializationObject.isVisible = this.isVisible;
  32501. serializationObject.infiniteDistance = this.infiniteDistance;
  32502. serializationObject.pickable = this.isPickable;
  32503. serializationObject.receiveShadows = this.receiveShadows;
  32504. serializationObject.billboardMode = this.billboardMode;
  32505. serializationObject.visibility = this.visibility;
  32506. serializationObject.checkCollisions = this.checkCollisions;
  32507. serializationObject.isBlocker = this.isBlocker;
  32508. // Parent
  32509. if (this.parent) {
  32510. serializationObject.parentId = this.parent.id;
  32511. }
  32512. // Geometry
  32513. serializationObject.isUnIndexed = this.isUnIndexed;
  32514. var geometry = this._geometry;
  32515. if (geometry) {
  32516. var geometryId = geometry.id;
  32517. serializationObject.geometryId = geometryId;
  32518. // SubMeshes
  32519. serializationObject.subMeshes = [];
  32520. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32521. var subMesh = this.subMeshes[subIndex];
  32522. serializationObject.subMeshes.push({
  32523. materialIndex: subMesh.materialIndex,
  32524. verticesStart: subMesh.verticesStart,
  32525. verticesCount: subMesh.verticesCount,
  32526. indexStart: subMesh.indexStart,
  32527. indexCount: subMesh.indexCount
  32528. });
  32529. }
  32530. }
  32531. // Material
  32532. if (this.material) {
  32533. serializationObject.materialId = this.material.id;
  32534. }
  32535. else {
  32536. this.material = null;
  32537. }
  32538. // Morph targets
  32539. if (this.morphTargetManager) {
  32540. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32541. }
  32542. // Skeleton
  32543. if (this.skeleton) {
  32544. serializationObject.skeletonId = this.skeleton.id;
  32545. }
  32546. // Physics
  32547. //TODO implement correct serialization for physics impostors.
  32548. var impostor = this.getPhysicsImpostor();
  32549. if (impostor) {
  32550. serializationObject.physicsMass = impostor.getParam("mass");
  32551. serializationObject.physicsFriction = impostor.getParam("friction");
  32552. serializationObject.physicsRestitution = impostor.getParam("mass");
  32553. serializationObject.physicsImpostor = impostor.type;
  32554. }
  32555. // Metadata
  32556. if (this.metadata) {
  32557. serializationObject.metadata = this.metadata;
  32558. }
  32559. // Instances
  32560. serializationObject.instances = [];
  32561. for (var index = 0; index < this.instances.length; index++) {
  32562. var instance = this.instances[index];
  32563. if (instance.doNotSerialize) {
  32564. continue;
  32565. }
  32566. var serializationInstance = {
  32567. name: instance.name,
  32568. id: instance.id,
  32569. position: instance.position.asArray(),
  32570. scaling: instance.scaling.asArray()
  32571. };
  32572. if (instance.parent) {
  32573. serializationInstance.parentId = instance.parent.id;
  32574. }
  32575. if (instance.rotationQuaternion) {
  32576. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32577. }
  32578. else if (instance.rotation) {
  32579. serializationInstance.rotation = instance.rotation.asArray();
  32580. }
  32581. serializationObject.instances.push(serializationInstance);
  32582. // Animations
  32583. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32584. serializationInstance.ranges = instance.serializeAnimationRanges();
  32585. }
  32586. //
  32587. // Animations
  32588. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32589. serializationObject.ranges = this.serializeAnimationRanges();
  32590. // Layer mask
  32591. serializationObject.layerMask = this.layerMask;
  32592. // Alpha
  32593. serializationObject.alphaIndex = this.alphaIndex;
  32594. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32595. // Overlay
  32596. serializationObject.overlayAlpha = this.overlayAlpha;
  32597. serializationObject.overlayColor = this.overlayColor.asArray();
  32598. serializationObject.renderOverlay = this.renderOverlay;
  32599. // Fog
  32600. serializationObject.applyFog = this.applyFog;
  32601. // Action Manager
  32602. if (this.actionManager) {
  32603. serializationObject.actions = this.actionManager.serialize(this.name);
  32604. }
  32605. };
  32606. /** @hidden */
  32607. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32608. if (!this.geometry) {
  32609. return;
  32610. }
  32611. this._markSubMeshesAsAttributesDirty();
  32612. var morphTargetManager = this._morphTargetManager;
  32613. if (morphTargetManager && morphTargetManager.vertexCount) {
  32614. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32615. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32616. this.morphTargetManager = null;
  32617. return;
  32618. }
  32619. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32620. var morphTarget = morphTargetManager.getActiveTarget(index);
  32621. var positions = morphTarget.getPositions();
  32622. if (!positions) {
  32623. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32624. return;
  32625. }
  32626. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32627. var normals = morphTarget.getNormals();
  32628. if (normals) {
  32629. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32630. }
  32631. var tangents = morphTarget.getTangents();
  32632. if (tangents) {
  32633. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32634. }
  32635. }
  32636. }
  32637. else {
  32638. var index = 0;
  32639. // Positions
  32640. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32641. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32642. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32643. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32644. }
  32645. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32646. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32647. }
  32648. index++;
  32649. }
  32650. }
  32651. };
  32652. // Statics
  32653. /**
  32654. * Returns a new Mesh object parsed from the source provided.
  32655. * The parameter `parsedMesh` is the source.
  32656. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32657. */
  32658. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32659. var mesh;
  32660. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32661. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32662. }
  32663. else {
  32664. mesh = new Mesh(parsedMesh.name, scene);
  32665. }
  32666. mesh.id = parsedMesh.id;
  32667. if (BABYLON.Tags) {
  32668. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32669. }
  32670. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32671. if (parsedMesh.metadata !== undefined) {
  32672. mesh.metadata = parsedMesh.metadata;
  32673. }
  32674. if (parsedMesh.rotationQuaternion) {
  32675. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32676. }
  32677. else if (parsedMesh.rotation) {
  32678. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32679. }
  32680. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32681. if (parsedMesh.localMatrix) {
  32682. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32683. }
  32684. else if (parsedMesh.pivotMatrix) {
  32685. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32686. }
  32687. mesh.setEnabled(parsedMesh.isEnabled);
  32688. mesh.isVisible = parsedMesh.isVisible;
  32689. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32690. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32691. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32692. if (parsedMesh.applyFog !== undefined) {
  32693. mesh.applyFog = parsedMesh.applyFog;
  32694. }
  32695. if (parsedMesh.pickable !== undefined) {
  32696. mesh.isPickable = parsedMesh.pickable;
  32697. }
  32698. if (parsedMesh.alphaIndex !== undefined) {
  32699. mesh.alphaIndex = parsedMesh.alphaIndex;
  32700. }
  32701. mesh.receiveShadows = parsedMesh.receiveShadows;
  32702. mesh.billboardMode = parsedMesh.billboardMode;
  32703. if (parsedMesh.visibility !== undefined) {
  32704. mesh.visibility = parsedMesh.visibility;
  32705. }
  32706. mesh.checkCollisions = parsedMesh.checkCollisions;
  32707. if (parsedMesh.isBlocker !== undefined) {
  32708. mesh.isBlocker = parsedMesh.isBlocker;
  32709. }
  32710. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32711. // freezeWorldMatrix
  32712. if (parsedMesh.freezeWorldMatrix) {
  32713. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32714. }
  32715. // Parent
  32716. if (parsedMesh.parentId) {
  32717. mesh._waitingParentId = parsedMesh.parentId;
  32718. }
  32719. // Actions
  32720. if (parsedMesh.actions !== undefined) {
  32721. mesh._waitingActions = parsedMesh.actions;
  32722. }
  32723. // Overlay
  32724. if (parsedMesh.overlayAlpha !== undefined) {
  32725. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32726. }
  32727. if (parsedMesh.overlayColor !== undefined) {
  32728. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32729. }
  32730. if (parsedMesh.renderOverlay !== undefined) {
  32731. mesh.renderOverlay = parsedMesh.renderOverlay;
  32732. }
  32733. // Geometry
  32734. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32735. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32736. if (parsedMesh.delayLoadingFile) {
  32737. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32738. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32739. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32740. if (parsedMesh._binaryInfo) {
  32741. mesh._binaryInfo = parsedMesh._binaryInfo;
  32742. }
  32743. mesh._delayInfo = [];
  32744. if (parsedMesh.hasUVs) {
  32745. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32746. }
  32747. if (parsedMesh.hasUVs2) {
  32748. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32749. }
  32750. if (parsedMesh.hasUVs3) {
  32751. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32752. }
  32753. if (parsedMesh.hasUVs4) {
  32754. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32755. }
  32756. if (parsedMesh.hasUVs5) {
  32757. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32758. }
  32759. if (parsedMesh.hasUVs6) {
  32760. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32761. }
  32762. if (parsedMesh.hasColors) {
  32763. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32764. }
  32765. if (parsedMesh.hasMatricesIndices) {
  32766. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32767. }
  32768. if (parsedMesh.hasMatricesWeights) {
  32769. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32770. }
  32771. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32772. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32773. mesh._checkDelayState();
  32774. }
  32775. }
  32776. else {
  32777. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32778. }
  32779. // Material
  32780. if (parsedMesh.materialId) {
  32781. mesh.setMaterialByID(parsedMesh.materialId);
  32782. }
  32783. else {
  32784. mesh.material = null;
  32785. }
  32786. // Morph targets
  32787. if (parsedMesh.morphTargetManagerId > -1) {
  32788. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32789. }
  32790. // Skeleton
  32791. if (parsedMesh.skeletonId > -1) {
  32792. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32793. if (parsedMesh.numBoneInfluencers) {
  32794. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32795. }
  32796. }
  32797. // Animations
  32798. if (parsedMesh.animations) {
  32799. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32800. var parsedAnimation = parsedMesh.animations[animationIndex];
  32801. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32802. }
  32803. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32804. }
  32805. if (parsedMesh.autoAnimate) {
  32806. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32807. }
  32808. // Layer Mask
  32809. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32810. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32811. }
  32812. else {
  32813. mesh.layerMask = 0x0FFFFFFF;
  32814. }
  32815. // Physics
  32816. if (parsedMesh.physicsImpostor) {
  32817. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32818. mass: parsedMesh.physicsMass,
  32819. friction: parsedMesh.physicsFriction,
  32820. restitution: parsedMesh.physicsRestitution
  32821. }, scene);
  32822. }
  32823. // Instances
  32824. if (parsedMesh.instances) {
  32825. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32826. var parsedInstance = parsedMesh.instances[index];
  32827. var instance = mesh.createInstance(parsedInstance.name);
  32828. if (parsedInstance.id) {
  32829. instance.id = parsedInstance.id;
  32830. }
  32831. if (BABYLON.Tags) {
  32832. if (parsedInstance.tags) {
  32833. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32834. }
  32835. else {
  32836. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  32837. }
  32838. }
  32839. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32840. if (parsedInstance.parentId) {
  32841. instance._waitingParentId = parsedInstance.parentId;
  32842. }
  32843. if (parsedInstance.rotationQuaternion) {
  32844. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32845. }
  32846. else if (parsedInstance.rotation) {
  32847. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32848. }
  32849. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32850. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  32851. instance.checkCollisions = parsedInstance.checkCollisions;
  32852. }
  32853. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  32854. instance.isPickable = parsedInstance.pickable;
  32855. }
  32856. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  32857. instance.showBoundingBox = parsedInstance.showBoundingBox;
  32858. }
  32859. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  32860. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  32861. }
  32862. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  32863. instance.alphaIndex = parsedInstance.alphaIndex;
  32864. }
  32865. // Physics
  32866. if (parsedInstance.physicsImpostor) {
  32867. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  32868. mass: parsedInstance.physicsMass,
  32869. friction: parsedInstance.physicsFriction,
  32870. restitution: parsedInstance.physicsRestitution
  32871. }, scene);
  32872. }
  32873. // Animation
  32874. if (parsedInstance.animations) {
  32875. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  32876. parsedAnimation = parsedInstance.animations[animationIndex];
  32877. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32878. }
  32879. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  32880. if (parsedInstance.autoAnimate) {
  32881. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  32882. }
  32883. }
  32884. }
  32885. }
  32886. return mesh;
  32887. };
  32888. /**
  32889. * Creates a ribbon mesh.
  32890. * Please consider using the same method from the MeshBuilder class instead.
  32891. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  32892. *
  32893. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32894. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32895. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32896. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32897. * 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.
  32898. * 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.
  32899. * 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
  32900. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32901. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32903. */
  32904. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32905. if (closeArray === void 0) { closeArray = false; }
  32906. if (updatable === void 0) { updatable = false; }
  32907. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32908. pathArray: pathArray,
  32909. closeArray: closeArray,
  32910. closePath: closePath,
  32911. offset: offset,
  32912. updatable: updatable,
  32913. sideOrientation: sideOrientation,
  32914. instance: instance
  32915. }, scene);
  32916. };
  32917. /**
  32918. * Creates a plane polygonal mesh. By default, this is a disc.
  32919. * Please consider using the same method from the MeshBuilder class instead.
  32920. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32921. * 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.
  32922. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32923. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32924. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32925. */
  32926. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32927. if (scene === void 0) { scene = null; }
  32928. var options = {
  32929. radius: radius,
  32930. tessellation: tessellation,
  32931. sideOrientation: sideOrientation,
  32932. updatable: updatable
  32933. };
  32934. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32935. };
  32936. /**
  32937. * Creates a box mesh.
  32938. * Please consider using the same method from the MeshBuilder class instead.
  32939. * The parameter `size` sets the size (float) of each box side (default 1).
  32940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32941. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32943. */
  32944. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32945. if (scene === void 0) { scene = null; }
  32946. var options = {
  32947. size: size,
  32948. sideOrientation: sideOrientation,
  32949. updatable: updatable
  32950. };
  32951. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32952. };
  32953. /**
  32954. * Creates a sphere mesh.
  32955. * Please consider using the same method from the MeshBuilder class instead.
  32956. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32957. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32958. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32959. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32961. */
  32962. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32963. var options = {
  32964. segments: segments,
  32965. diameterX: diameter,
  32966. diameterY: diameter,
  32967. diameterZ: diameter,
  32968. sideOrientation: sideOrientation,
  32969. updatable: updatable
  32970. };
  32971. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32972. };
  32973. /**
  32974. * Creates a cylinder or a cone mesh.
  32975. * Please consider using the same method from the MeshBuilder class instead.
  32976. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32977. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32978. * 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.
  32979. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32980. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32981. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32982. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32984. */
  32985. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32986. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32987. if (scene !== undefined) {
  32988. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32989. updatable = scene;
  32990. }
  32991. scene = subdivisions;
  32992. subdivisions = 1;
  32993. }
  32994. var options = {
  32995. height: height,
  32996. diameterTop: diameterTop,
  32997. diameterBottom: diameterBottom,
  32998. tessellation: tessellation,
  32999. subdivisions: subdivisions,
  33000. sideOrientation: sideOrientation,
  33001. updatable: updatable
  33002. };
  33003. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33004. };
  33005. // Torus (Code from SharpDX.org)
  33006. /**
  33007. * Creates a torus mesh.
  33008. * Please consider using the same method from the MeshBuilder class instead.
  33009. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33010. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33011. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33013. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33014. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33015. */
  33016. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33017. var options = {
  33018. diameter: diameter,
  33019. thickness: thickness,
  33020. tessellation: tessellation,
  33021. sideOrientation: sideOrientation,
  33022. updatable: updatable
  33023. };
  33024. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33025. };
  33026. /**
  33027. * Creates a torus knot mesh.
  33028. * Please consider using the same method from the MeshBuilder class instead.
  33029. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33030. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33031. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33032. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33033. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33034. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33036. */
  33037. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33038. var options = {
  33039. radius: radius,
  33040. tube: tube,
  33041. radialSegments: radialSegments,
  33042. tubularSegments: tubularSegments,
  33043. p: p,
  33044. q: q,
  33045. sideOrientation: sideOrientation,
  33046. updatable: updatable
  33047. };
  33048. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33049. };
  33050. /**
  33051. * Creates a line mesh.
  33052. * Please consider using the same method from the MeshBuilder class instead.
  33053. * 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.
  33054. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33055. * The parameter `points` is an array successive Vector3.
  33056. * 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
  33057. * When updating an instance, remember that only point positions can change, not the number of points.
  33058. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33059. */
  33060. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33061. if (scene === void 0) { scene = null; }
  33062. if (updatable === void 0) { updatable = false; }
  33063. if (instance === void 0) { instance = null; }
  33064. var options = {
  33065. points: points,
  33066. updatable: updatable,
  33067. instance: instance
  33068. };
  33069. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33070. };
  33071. /**
  33072. * Creates a dashed line mesh.
  33073. * Please consider using the same method from the MeshBuilder class instead.
  33074. * 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.
  33075. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33076. * The parameter `points` is an array successive Vector3.
  33077. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33078. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33079. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33080. * 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
  33081. * When updating an instance, remember that only point positions can change, not the number of points.
  33082. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33083. */
  33084. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33085. if (scene === void 0) { scene = null; }
  33086. var options = {
  33087. points: points,
  33088. dashSize: dashSize,
  33089. gapSize: gapSize,
  33090. dashNb: dashNb,
  33091. updatable: updatable,
  33092. instance: instance
  33093. };
  33094. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33095. };
  33096. /**
  33097. * Creates a polygon mesh.
  33098. * Please consider using the same method from the MeshBuilder class instead.
  33099. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33100. * 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.
  33101. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33102. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33103. * Remember you can only change the shape positions, not their number when updating a polygon.
  33104. */
  33105. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33106. var options = {
  33107. shape: shape,
  33108. holes: holes,
  33109. updatable: updatable,
  33110. sideOrientation: sideOrientation
  33111. };
  33112. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33113. };
  33114. /**
  33115. * Creates an extruded polygon mesh, with depth in the Y direction.
  33116. * Please consider using the same method from the MeshBuilder class instead.
  33117. */
  33118. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33119. var options = {
  33120. shape: shape,
  33121. holes: holes,
  33122. depth: depth,
  33123. updatable: updatable,
  33124. sideOrientation: sideOrientation
  33125. };
  33126. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33127. };
  33128. /**
  33129. * Creates an extruded shape mesh.
  33130. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33131. * Please consider using the same method from the MeshBuilder class instead.
  33132. *
  33133. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33134. * 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
  33135. * extruded along the Z axis.
  33136. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33137. * 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.
  33138. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33139. * 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
  33140. * 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
  33141. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33142. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33143. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33145. */
  33146. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33147. if (scene === void 0) { scene = null; }
  33148. var options = {
  33149. shape: shape,
  33150. path: path,
  33151. scale: scale,
  33152. rotation: rotation,
  33153. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33154. sideOrientation: sideOrientation,
  33155. instance: instance,
  33156. updatable: updatable
  33157. };
  33158. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33159. };
  33160. /**
  33161. * Creates an custom extruded shape mesh.
  33162. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33163. * Please consider using the same method from the MeshBuilder class instead.
  33164. *
  33165. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33166. * 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
  33167. * extruded along the Z axis.
  33168. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33169. * 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
  33170. * and the distance of this point from the begining of the path :
  33171. * ```javascript
  33172. * var rotationFunction = function(i, distance) {
  33173. * // do things
  33174. * return rotationValue; }
  33175. * ```
  33176. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33177. * 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
  33178. * and the distance of this point from the begining of the path :
  33179. * ```javascript
  33180. * var scaleFunction = function(i, distance) {
  33181. * // do things
  33182. * return scaleValue;}
  33183. * ```
  33184. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33185. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33186. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33187. * 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
  33188. * 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
  33189. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33190. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33191. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33192. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33193. */
  33194. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33195. var options = {
  33196. shape: shape,
  33197. path: path,
  33198. scaleFunction: scaleFunction,
  33199. rotationFunction: rotationFunction,
  33200. ribbonCloseArray: ribbonCloseArray,
  33201. ribbonClosePath: ribbonClosePath,
  33202. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33203. sideOrientation: sideOrientation,
  33204. instance: instance,
  33205. updatable: updatable
  33206. };
  33207. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33208. };
  33209. /**
  33210. * Creates lathe mesh.
  33211. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33212. * Please consider using the same method from the MeshBuilder class instead.
  33213. * 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
  33214. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33215. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33216. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33217. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33218. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33219. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33220. */
  33221. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33222. var options = {
  33223. shape: shape,
  33224. radius: radius,
  33225. tessellation: tessellation,
  33226. sideOrientation: sideOrientation,
  33227. updatable: updatable
  33228. };
  33229. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33230. };
  33231. /**
  33232. * Creates a plane mesh.
  33233. * Please consider using the same method from the MeshBuilder class instead.
  33234. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33235. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33236. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33238. */
  33239. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33240. var options = {
  33241. size: size,
  33242. width: size,
  33243. height: size,
  33244. sideOrientation: sideOrientation,
  33245. updatable: updatable
  33246. };
  33247. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33248. };
  33249. /**
  33250. * Creates a ground mesh.
  33251. * Please consider using the same method from the MeshBuilder class instead.
  33252. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33253. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33255. */
  33256. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33257. var options = {
  33258. width: width,
  33259. height: height,
  33260. subdivisions: subdivisions,
  33261. updatable: updatable
  33262. };
  33263. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33264. };
  33265. /**
  33266. * Creates a tiled ground mesh.
  33267. * Please consider using the same method from the MeshBuilder class instead.
  33268. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33269. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33270. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33271. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33272. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33273. * numbers of subdivisions on the ground width and height of each tile.
  33274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33275. */
  33276. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33277. var options = {
  33278. xmin: xmin,
  33279. zmin: zmin,
  33280. xmax: xmax,
  33281. zmax: zmax,
  33282. subdivisions: subdivisions,
  33283. precision: precision,
  33284. updatable: updatable
  33285. };
  33286. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33287. };
  33288. /**
  33289. * Creates a ground mesh from a height map.
  33290. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33291. * Please consider using the same method from the MeshBuilder class instead.
  33292. * @param url sets the URL of the height map image resource.
  33293. * @param width (positive float, default 10) set the ground width size.
  33294. * @param height (positive float, default 10) set the ground height size.
  33295. * @param subdivisions (positive integer, default 1) sets the number of subdivision per side.
  33296. * @param minHeight (float, default 0) is the minimum altitude on the ground.
  33297. * @param maxHeight (float, default 1) is the maximum altitude on the ground.
  33298. * @param onReady is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  33299. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible).
  33300. * This function is passed the newly built mesh :
  33301. * ```javascript
  33302. * function(mesh) { // do things
  33303. * return; }
  33304. * ```
  33305. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33306. */
  33307. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33308. var options = {
  33309. width: width,
  33310. height: height,
  33311. subdivisions: subdivisions,
  33312. minHeight: minHeight,
  33313. maxHeight: maxHeight,
  33314. updatable: updatable,
  33315. onReady: onReady,
  33316. alphaFilter: alphaFilter
  33317. };
  33318. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33319. };
  33320. /**
  33321. * Creates a tube mesh.
  33322. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33323. * Please consider using the same method from the MeshBuilder class instead.
  33324. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33325. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33326. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33327. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33328. * 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.
  33329. * It must return a radius value (positive float) :
  33330. * ```javascript
  33331. * var radiusFunction = function(i, distance) {
  33332. * // do things
  33333. * return radius; }
  33334. * ```
  33335. * 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
  33336. * 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
  33337. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33338. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33340. */
  33341. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33342. var options = {
  33343. path: path,
  33344. radius: radius,
  33345. tessellation: tessellation,
  33346. radiusFunction: radiusFunction,
  33347. arc: 1,
  33348. cap: cap,
  33349. updatable: updatable,
  33350. sideOrientation: sideOrientation,
  33351. instance: instance
  33352. };
  33353. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33354. };
  33355. /**
  33356. * Creates a polyhedron mesh.
  33357. * Please consider using the same method from the MeshBuilder class instead.
  33358. * 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
  33359. * to choose the wanted type.
  33360. * The parameter `size` (positive float, default 1) sets the polygon size.
  33361. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33362. * 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`.
  33363. * 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
  33364. * 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)`).
  33365. * 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
  33366. * 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.
  33367. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33368. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33369. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33370. */
  33371. Mesh.CreatePolyhedron = function (name, options, scene) {
  33372. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33373. };
  33374. /**
  33375. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33376. * Please consider using the same method from the MeshBuilder class instead.
  33377. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33378. * 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`).
  33379. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33380. * 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.
  33381. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33382. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33384. */
  33385. Mesh.CreateIcoSphere = function (name, options, scene) {
  33386. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33387. };
  33388. /**
  33389. * Creates a decal mesh.
  33390. * Please consider using the same method from the MeshBuilder class instead.
  33391. * 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.
  33392. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33393. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33394. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33395. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33396. */
  33397. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33398. var options = {
  33399. position: position,
  33400. normal: normal,
  33401. size: size,
  33402. angle: angle
  33403. };
  33404. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33405. };
  33406. // Skeletons
  33407. /**
  33408. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33409. */
  33410. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33411. if (!this._sourcePositions) {
  33412. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33413. if (!source) {
  33414. return this._sourcePositions;
  33415. }
  33416. this._sourcePositions = new Float32Array(source);
  33417. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33418. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33419. }
  33420. }
  33421. return this._sourcePositions;
  33422. };
  33423. /**
  33424. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33425. */
  33426. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33427. if (!this._sourceNormals) {
  33428. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33429. if (!source) {
  33430. return this._sourceNormals;
  33431. }
  33432. this._sourceNormals = new Float32Array(source);
  33433. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33434. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33435. }
  33436. }
  33437. return this._sourceNormals;
  33438. };
  33439. /**
  33440. * Updates the vertex buffer by applying transformation from the bones.
  33441. * Returns the Mesh.
  33442. *
  33443. * @param {skeleton} skeleton to apply
  33444. */
  33445. Mesh.prototype.applySkeleton = function (skeleton) {
  33446. if (!this.geometry) {
  33447. return this;
  33448. }
  33449. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33450. return this;
  33451. }
  33452. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33453. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33454. return this;
  33455. }
  33456. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33457. return this;
  33458. }
  33459. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33460. return this;
  33461. }
  33462. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33463. return this;
  33464. }
  33465. if (!this._sourcePositions) {
  33466. var submeshes = this.subMeshes.slice();
  33467. this.setPositionsForCPUSkinning();
  33468. this.subMeshes = submeshes;
  33469. }
  33470. if (!this._sourceNormals) {
  33471. this.setNormalsForCPUSkinning();
  33472. }
  33473. // positionsData checks for not being Float32Array will only pass at most once
  33474. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33475. if (!positionsData) {
  33476. return this;
  33477. }
  33478. if (!(positionsData instanceof Float32Array)) {
  33479. positionsData = new Float32Array(positionsData);
  33480. }
  33481. // normalsData checks for not being Float32Array will only pass at most once
  33482. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33483. if (!normalsData) {
  33484. return this;
  33485. }
  33486. if (!(normalsData instanceof Float32Array)) {
  33487. normalsData = new Float32Array(normalsData);
  33488. }
  33489. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33490. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33491. if (!matricesWeightsData || !matricesIndicesData) {
  33492. return this;
  33493. }
  33494. var needExtras = this.numBoneInfluencers > 4;
  33495. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33496. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33497. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33498. var tempVector3 = BABYLON.Vector3.Zero();
  33499. var finalMatrix = new BABYLON.Matrix();
  33500. var tempMatrix = new BABYLON.Matrix();
  33501. var matWeightIdx = 0;
  33502. var inf;
  33503. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33504. var weight;
  33505. for (inf = 0; inf < 4; inf++) {
  33506. weight = matricesWeightsData[matWeightIdx + inf];
  33507. if (weight > 0) {
  33508. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33509. finalMatrix.addToSelf(tempMatrix);
  33510. }
  33511. }
  33512. if (needExtras) {
  33513. for (inf = 0; inf < 4; inf++) {
  33514. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33515. if (weight > 0) {
  33516. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33517. finalMatrix.addToSelf(tempMatrix);
  33518. }
  33519. }
  33520. }
  33521. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33522. tempVector3.toArray(positionsData, index);
  33523. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33524. tempVector3.toArray(normalsData, index);
  33525. finalMatrix.reset();
  33526. }
  33527. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33528. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33529. return this;
  33530. };
  33531. // Tools
  33532. /**
  33533. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33534. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33535. */
  33536. Mesh.MinMax = function (meshes) {
  33537. var minVector = null;
  33538. var maxVector = null;
  33539. meshes.forEach(function (mesh, index, array) {
  33540. var boundingInfo = mesh.getBoundingInfo();
  33541. var boundingBox = boundingInfo.boundingBox;
  33542. if (!minVector || !maxVector) {
  33543. minVector = boundingBox.minimumWorld;
  33544. maxVector = boundingBox.maximumWorld;
  33545. }
  33546. else {
  33547. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33548. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33549. }
  33550. });
  33551. if (!minVector || !maxVector) {
  33552. return {
  33553. min: BABYLON.Vector3.Zero(),
  33554. max: BABYLON.Vector3.Zero()
  33555. };
  33556. }
  33557. return {
  33558. min: minVector,
  33559. max: maxVector
  33560. };
  33561. };
  33562. /**
  33563. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33564. */
  33565. Mesh.Center = function (meshesOrMinMaxVector) {
  33566. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33567. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33568. };
  33569. /**
  33570. * Merge the array of meshes into a single mesh for performance reasons.
  33571. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  33572. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  33573. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33574. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33575. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33576. */
  33577. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33578. if (disposeSource === void 0) { disposeSource = true; }
  33579. var index;
  33580. if (!allow32BitsIndices) {
  33581. var totalVertices = 0;
  33582. // Counting vertices
  33583. for (index = 0; index < meshes.length; index++) {
  33584. if (meshes[index]) {
  33585. totalVertices += meshes[index].getTotalVertices();
  33586. if (totalVertices > 65536) {
  33587. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33588. return null;
  33589. }
  33590. }
  33591. }
  33592. }
  33593. // Merge
  33594. var vertexData = null;
  33595. var otherVertexData;
  33596. var indiceArray = new Array();
  33597. var source = null;
  33598. for (index = 0; index < meshes.length; index++) {
  33599. if (meshes[index]) {
  33600. var wm = meshes[index].computeWorldMatrix(true);
  33601. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33602. otherVertexData.transform(wm);
  33603. if (vertexData) {
  33604. vertexData.merge(otherVertexData, allow32BitsIndices);
  33605. }
  33606. else {
  33607. vertexData = otherVertexData;
  33608. source = meshes[index];
  33609. }
  33610. if (subdivideWithSubMeshes) {
  33611. indiceArray.push(meshes[index].getTotalIndices());
  33612. }
  33613. }
  33614. }
  33615. source = source;
  33616. if (!meshSubclass) {
  33617. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33618. }
  33619. vertexData.applyToMesh(meshSubclass);
  33620. // Setting properties
  33621. meshSubclass.material = source.material;
  33622. meshSubclass.checkCollisions = source.checkCollisions;
  33623. // Cleaning
  33624. if (disposeSource) {
  33625. for (index = 0; index < meshes.length; index++) {
  33626. if (meshes[index]) {
  33627. meshes[index].dispose();
  33628. }
  33629. }
  33630. }
  33631. // Subdivide
  33632. if (subdivideWithSubMeshes) {
  33633. //-- removal of global submesh
  33634. meshSubclass.releaseSubMeshes();
  33635. index = 0;
  33636. var offset = 0;
  33637. //-- apply subdivision according to index table
  33638. while (index < indiceArray.length) {
  33639. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33640. offset += indiceArray[index];
  33641. index++;
  33642. }
  33643. }
  33644. return meshSubclass;
  33645. };
  33646. // Consts
  33647. Mesh._FRONTSIDE = 0;
  33648. Mesh._BACKSIDE = 1;
  33649. Mesh._DOUBLESIDE = 2;
  33650. Mesh._DEFAULTSIDE = 0;
  33651. Mesh._NO_CAP = 0;
  33652. Mesh._CAP_START = 1;
  33653. Mesh._CAP_END = 2;
  33654. Mesh._CAP_ALL = 3;
  33655. return Mesh;
  33656. }(BABYLON.AbstractMesh));
  33657. BABYLON.Mesh = Mesh;
  33658. })(BABYLON || (BABYLON = {}));
  33659. //# sourceMappingURL=babylon.mesh.js.map
  33660. var BABYLON;
  33661. (function (BABYLON) {
  33662. var BaseSubMesh = /** @class */ (function () {
  33663. function BaseSubMesh() {
  33664. }
  33665. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33666. get: function () {
  33667. return this._materialEffect;
  33668. },
  33669. enumerable: true,
  33670. configurable: true
  33671. });
  33672. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33673. if (defines === void 0) { defines = null; }
  33674. if (this._materialEffect === effect) {
  33675. if (!effect) {
  33676. this._materialDefines = null;
  33677. }
  33678. return;
  33679. }
  33680. this._materialDefines = defines;
  33681. this._materialEffect = effect;
  33682. };
  33683. return BaseSubMesh;
  33684. }());
  33685. BABYLON.BaseSubMesh = BaseSubMesh;
  33686. var SubMesh = /** @class */ (function (_super) {
  33687. __extends(SubMesh, _super);
  33688. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33689. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33690. var _this = _super.call(this) || this;
  33691. _this.materialIndex = materialIndex;
  33692. _this.verticesStart = verticesStart;
  33693. _this.verticesCount = verticesCount;
  33694. _this.indexStart = indexStart;
  33695. _this.indexCount = indexCount;
  33696. /** @hidden */
  33697. _this._renderId = 0;
  33698. _this._mesh = mesh;
  33699. _this._renderingMesh = renderingMesh || mesh;
  33700. mesh.subMeshes.push(_this);
  33701. _this._trianglePlanes = [];
  33702. _this._id = mesh.subMeshes.length - 1;
  33703. if (createBoundingBox) {
  33704. _this.refreshBoundingInfo();
  33705. mesh.computeWorldMatrix(true);
  33706. }
  33707. return _this;
  33708. }
  33709. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33710. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33711. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33712. };
  33713. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33714. get: function () {
  33715. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  33716. },
  33717. enumerable: true,
  33718. configurable: true
  33719. });
  33720. /**
  33721. * Returns the submesh BoudingInfo object.
  33722. */
  33723. SubMesh.prototype.getBoundingInfo = function () {
  33724. if (this.IsGlobal) {
  33725. return this._mesh.getBoundingInfo();
  33726. }
  33727. return this._boundingInfo;
  33728. };
  33729. /**
  33730. * Sets the submesh BoundingInfo.
  33731. * Return the SubMesh.
  33732. */
  33733. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33734. this._boundingInfo = boundingInfo;
  33735. return this;
  33736. };
  33737. /**
  33738. * Returns the mesh of the current submesh.
  33739. */
  33740. SubMesh.prototype.getMesh = function () {
  33741. return this._mesh;
  33742. };
  33743. /**
  33744. * Returns the rendering mesh of the submesh.
  33745. */
  33746. SubMesh.prototype.getRenderingMesh = function () {
  33747. return this._renderingMesh;
  33748. };
  33749. /**
  33750. * Returns the submesh material.
  33751. */
  33752. SubMesh.prototype.getMaterial = function () {
  33753. var rootMaterial = this._renderingMesh.material;
  33754. if (rootMaterial === null || rootMaterial === undefined) {
  33755. return this._mesh.getScene().defaultMaterial;
  33756. }
  33757. else if (rootMaterial.getSubMaterial) {
  33758. var multiMaterial = rootMaterial;
  33759. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33760. if (this._currentMaterial !== effectiveMaterial) {
  33761. this._currentMaterial = effectiveMaterial;
  33762. this._materialDefines = null;
  33763. }
  33764. return effectiveMaterial;
  33765. }
  33766. return rootMaterial;
  33767. };
  33768. // Methods
  33769. /**
  33770. * Sets a new updated BoundingInfo object to the submesh.
  33771. * Returns the SubMesh.
  33772. */
  33773. SubMesh.prototype.refreshBoundingInfo = function () {
  33774. this._lastColliderWorldVertices = null;
  33775. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33776. return this;
  33777. }
  33778. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33779. if (!data) {
  33780. this._boundingInfo = this._mesh.getBoundingInfo();
  33781. return this;
  33782. }
  33783. var indices = this._renderingMesh.getIndices();
  33784. var extend;
  33785. //is this the only submesh?
  33786. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33787. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33788. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33789. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33790. }
  33791. else {
  33792. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33793. }
  33794. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33795. return this;
  33796. };
  33797. /** @hidden */
  33798. SubMesh.prototype._checkCollision = function (collider) {
  33799. var boundingInfo = this.getBoundingInfo();
  33800. return boundingInfo._checkCollision(collider);
  33801. };
  33802. /**
  33803. * Updates the submesh BoundingInfo.
  33804. * Returns the Submesh.
  33805. */
  33806. SubMesh.prototype.updateBoundingInfo = function (world) {
  33807. var boundingInfo = this.getBoundingInfo();
  33808. if (!boundingInfo) {
  33809. this.refreshBoundingInfo();
  33810. boundingInfo = this.getBoundingInfo();
  33811. }
  33812. boundingInfo.update(world);
  33813. return this;
  33814. };
  33815. /**
  33816. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33817. * Boolean returned.
  33818. */
  33819. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33820. var boundingInfo = this.getBoundingInfo();
  33821. if (!boundingInfo) {
  33822. return false;
  33823. }
  33824. return boundingInfo.isInFrustum(frustumPlanes);
  33825. };
  33826. /**
  33827. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33828. * Boolean returned.
  33829. */
  33830. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33831. var boundingInfo = this.getBoundingInfo();
  33832. if (!boundingInfo) {
  33833. return false;
  33834. }
  33835. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33836. };
  33837. /**
  33838. * Renders the submesh.
  33839. * Returns it.
  33840. */
  33841. SubMesh.prototype.render = function (enableAlphaMode) {
  33842. this._renderingMesh.render(this, enableAlphaMode);
  33843. return this;
  33844. };
  33845. /**
  33846. * Returns a new Index Buffer.
  33847. * Type returned : WebGLBuffer.
  33848. */
  33849. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33850. if (!this._linesIndexBuffer) {
  33851. var linesIndices = [];
  33852. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33853. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33854. }
  33855. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33856. this.linesIndexCount = linesIndices.length;
  33857. }
  33858. return this._linesIndexBuffer;
  33859. };
  33860. /**
  33861. * True is the passed Ray intersects the submesh bounding box.
  33862. * Boolean returned.
  33863. */
  33864. SubMesh.prototype.canIntersects = function (ray) {
  33865. var boundingInfo = this.getBoundingInfo();
  33866. if (!boundingInfo) {
  33867. return false;
  33868. }
  33869. return ray.intersectsBox(boundingInfo.boundingBox);
  33870. };
  33871. /**
  33872. * Returns an object IntersectionInfo.
  33873. */
  33874. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33875. var intersectInfo = null;
  33876. var material = this.getMaterial();
  33877. if (!material) {
  33878. return null;
  33879. }
  33880. switch (material.fillMode) {
  33881. case BABYLON.Material.PointListDrawMode:
  33882. case BABYLON.Material.LineListDrawMode:
  33883. case BABYLON.Material.LineLoopDrawMode:
  33884. case BABYLON.Material.LineStripDrawMode:
  33885. case BABYLON.Material.TriangleFanDrawMode:
  33886. case BABYLON.Material.TriangleStripDrawMode:
  33887. return null;
  33888. }
  33889. // LineMesh first as it's also a Mesh...
  33890. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33891. var lineMesh = this._mesh;
  33892. // Line test
  33893. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33894. var p0 = positions[indices[index]];
  33895. var p1 = positions[indices[index + 1]];
  33896. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33897. if (length < 0) {
  33898. continue;
  33899. }
  33900. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33901. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33902. if (fastCheck) {
  33903. break;
  33904. }
  33905. }
  33906. }
  33907. }
  33908. else {
  33909. // Triangles test
  33910. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33911. var p0 = positions[indices[index]];
  33912. var p1 = positions[indices[index + 1]];
  33913. var p2 = positions[indices[index + 2]];
  33914. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33915. if (currentIntersectInfo) {
  33916. if (currentIntersectInfo.distance < 0) {
  33917. continue;
  33918. }
  33919. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33920. intersectInfo = currentIntersectInfo;
  33921. intersectInfo.faceId = index / 3;
  33922. if (fastCheck) {
  33923. break;
  33924. }
  33925. }
  33926. }
  33927. }
  33928. }
  33929. return intersectInfo;
  33930. };
  33931. /** @hidden */
  33932. SubMesh.prototype._rebuild = function () {
  33933. if (this._linesIndexBuffer) {
  33934. this._linesIndexBuffer = null;
  33935. }
  33936. };
  33937. // Clone
  33938. /**
  33939. * Creates a new Submesh from the passed Mesh.
  33940. */
  33941. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33942. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33943. if (!this.IsGlobal) {
  33944. var boundingInfo = this.getBoundingInfo();
  33945. if (!boundingInfo) {
  33946. return result;
  33947. }
  33948. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33949. }
  33950. return result;
  33951. };
  33952. // Dispose
  33953. /**
  33954. * Disposes the Submesh.
  33955. * Returns nothing.
  33956. */
  33957. SubMesh.prototype.dispose = function () {
  33958. if (this._linesIndexBuffer) {
  33959. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33960. this._linesIndexBuffer = null;
  33961. }
  33962. // Remove from mesh
  33963. var index = this._mesh.subMeshes.indexOf(this);
  33964. this._mesh.subMeshes.splice(index, 1);
  33965. };
  33966. // Statics
  33967. /**
  33968. * Creates a new Submesh from the passed parameters :
  33969. * - materialIndex (integer) : the index of the main mesh material.
  33970. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33971. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33972. * - mesh (Mesh) : the main mesh to create the submesh from.
  33973. * - renderingMesh (optional Mesh) : rendering mesh.
  33974. */
  33975. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33976. var minVertexIndex = Number.MAX_VALUE;
  33977. var maxVertexIndex = -Number.MAX_VALUE;
  33978. renderingMesh = (renderingMesh || mesh);
  33979. var indices = renderingMesh.getIndices();
  33980. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33981. var vertexIndex = indices[index];
  33982. if (vertexIndex < minVertexIndex)
  33983. minVertexIndex = vertexIndex;
  33984. if (vertexIndex > maxVertexIndex)
  33985. maxVertexIndex = vertexIndex;
  33986. }
  33987. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33988. };
  33989. return SubMesh;
  33990. }(BaseSubMesh));
  33991. BABYLON.SubMesh = SubMesh;
  33992. })(BABYLON || (BABYLON = {}));
  33993. //# sourceMappingURL=babylon.subMesh.js.map
  33994. var __assign = (this && this.__assign) || function () {
  33995. __assign = Object.assign || function(t) {
  33996. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33997. s = arguments[i];
  33998. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33999. t[p] = s[p];
  34000. }
  34001. return t;
  34002. };
  34003. return __assign.apply(this, arguments);
  34004. };
  34005. var BABYLON;
  34006. (function (BABYLON) {
  34007. /**
  34008. * Manages the defines for the Material
  34009. */
  34010. var MaterialDefines = /** @class */ (function () {
  34011. function MaterialDefines() {
  34012. this._isDirty = true;
  34013. /** @hidden */
  34014. this._areLightsDirty = true;
  34015. /** @hidden */
  34016. this._areAttributesDirty = true;
  34017. /** @hidden */
  34018. this._areTexturesDirty = true;
  34019. /** @hidden */
  34020. this._areFresnelDirty = true;
  34021. /** @hidden */
  34022. this._areMiscDirty = true;
  34023. /** @hidden */
  34024. this._areImageProcessingDirty = true;
  34025. /** @hidden */
  34026. this._normals = false;
  34027. /** @hidden */
  34028. this._uvs = false;
  34029. /** @hidden */
  34030. this._needNormals = false;
  34031. /** @hidden */
  34032. this._needUVs = false;
  34033. }
  34034. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34035. /**
  34036. * Specifies if the material needs to be re-calculated
  34037. */
  34038. get: function () {
  34039. return this._isDirty;
  34040. },
  34041. enumerable: true,
  34042. configurable: true
  34043. });
  34044. /**
  34045. * Marks the material to indicate that it has been re-calculated
  34046. */
  34047. MaterialDefines.prototype.markAsProcessed = function () {
  34048. this._isDirty = false;
  34049. this._areAttributesDirty = false;
  34050. this._areTexturesDirty = false;
  34051. this._areFresnelDirty = false;
  34052. this._areLightsDirty = false;
  34053. this._areMiscDirty = false;
  34054. this._areImageProcessingDirty = false;
  34055. };
  34056. /**
  34057. * Marks the material to indicate that it needs to be re-calculated
  34058. */
  34059. MaterialDefines.prototype.markAsUnprocessed = function () {
  34060. this._isDirty = true;
  34061. };
  34062. /**
  34063. * Marks the material to indicate all of its defines need to be re-calculated
  34064. */
  34065. MaterialDefines.prototype.markAllAsDirty = function () {
  34066. this._areTexturesDirty = true;
  34067. this._areAttributesDirty = true;
  34068. this._areLightsDirty = true;
  34069. this._areFresnelDirty = true;
  34070. this._areMiscDirty = true;
  34071. this._areImageProcessingDirty = true;
  34072. this._isDirty = true;
  34073. };
  34074. /**
  34075. * Marks the material to indicate that image processing needs to be re-calculated
  34076. */
  34077. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34078. this._areImageProcessingDirty = true;
  34079. this._isDirty = true;
  34080. };
  34081. /**
  34082. * Marks the material to indicate the lights need to be re-calculated
  34083. */
  34084. MaterialDefines.prototype.markAsLightDirty = function () {
  34085. this._areLightsDirty = true;
  34086. this._isDirty = true;
  34087. };
  34088. /**
  34089. * Marks the attribute state as changed
  34090. */
  34091. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34092. this._areAttributesDirty = true;
  34093. this._isDirty = true;
  34094. };
  34095. /**
  34096. * Marks the texture state as changed
  34097. */
  34098. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34099. this._areTexturesDirty = true;
  34100. this._isDirty = true;
  34101. };
  34102. /**
  34103. * Marks the fresnel state as changed
  34104. */
  34105. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34106. this._areFresnelDirty = true;
  34107. this._isDirty = true;
  34108. };
  34109. /**
  34110. * Marks the misc state as changed
  34111. */
  34112. MaterialDefines.prototype.markAsMiscDirty = function () {
  34113. this._areMiscDirty = true;
  34114. this._isDirty = true;
  34115. };
  34116. /**
  34117. * Rebuilds the material defines
  34118. */
  34119. MaterialDefines.prototype.rebuild = function () {
  34120. if (this._keys) {
  34121. delete this._keys;
  34122. }
  34123. this._keys = [];
  34124. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34125. var key = _a[_i];
  34126. if (key[0] === "_") {
  34127. continue;
  34128. }
  34129. this._keys.push(key);
  34130. }
  34131. };
  34132. /**
  34133. * Specifies if two material defines are equal
  34134. * @param other - A material define instance to compare to
  34135. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34136. */
  34137. MaterialDefines.prototype.isEqual = function (other) {
  34138. if (this._keys.length !== other._keys.length) {
  34139. return false;
  34140. }
  34141. for (var index = 0; index < this._keys.length; index++) {
  34142. var prop = this._keys[index];
  34143. if (this[prop] !== other[prop]) {
  34144. return false;
  34145. }
  34146. }
  34147. return true;
  34148. };
  34149. /**
  34150. * Clones this instance's defines to another instance
  34151. * @param other - material defines to clone values to
  34152. */
  34153. MaterialDefines.prototype.cloneTo = function (other) {
  34154. if (this._keys.length !== other._keys.length) {
  34155. other._keys = this._keys.slice(0);
  34156. }
  34157. for (var index = 0; index < this._keys.length; index++) {
  34158. var prop = this._keys[index];
  34159. other[prop] = this[prop];
  34160. }
  34161. };
  34162. /**
  34163. * Resets the material define values
  34164. */
  34165. MaterialDefines.prototype.reset = function () {
  34166. for (var index = 0; index < this._keys.length; index++) {
  34167. var prop = this._keys[index];
  34168. var type = typeof this[prop];
  34169. switch (type) {
  34170. case "number":
  34171. this[prop] = 0;
  34172. break;
  34173. case "string":
  34174. this[prop] = "";
  34175. break;
  34176. default:
  34177. this[prop] = false;
  34178. break;
  34179. }
  34180. }
  34181. };
  34182. /**
  34183. * Converts the material define values to a string
  34184. * @returns - String of material define information
  34185. */
  34186. MaterialDefines.prototype.toString = function () {
  34187. var result = "";
  34188. for (var index = 0; index < this._keys.length; index++) {
  34189. var prop = this._keys[index];
  34190. var value = this[prop];
  34191. var type = typeof value;
  34192. switch (type) {
  34193. case "number":
  34194. case "string":
  34195. result += "#define " + prop + " " + value + "\n";
  34196. break;
  34197. default:
  34198. if (value) {
  34199. result += "#define " + prop + "\n";
  34200. }
  34201. break;
  34202. }
  34203. }
  34204. return result;
  34205. };
  34206. return MaterialDefines;
  34207. }());
  34208. BABYLON.MaterialDefines = MaterialDefines;
  34209. /**
  34210. * Base class for the main features of a material in Babylon.js
  34211. */
  34212. var Material = /** @class */ (function () {
  34213. /**
  34214. * Creates a material instance
  34215. * @param name defines the name of the material
  34216. * @param scene defines the scene to reference
  34217. * @param doNotAdd specifies if the material should be added to the scene
  34218. */
  34219. function Material(name, scene, doNotAdd) {
  34220. /**
  34221. * Specifies if the ready state should be checked on each call
  34222. */
  34223. this.checkReadyOnEveryCall = false;
  34224. /**
  34225. * Specifies if the ready state should be checked once
  34226. */
  34227. this.checkReadyOnlyOnce = false;
  34228. /**
  34229. * The state of the material
  34230. */
  34231. this.state = "";
  34232. /**
  34233. * The alpha value of the material
  34234. */
  34235. this._alpha = 1.0;
  34236. /**
  34237. * Specifies if back face culling is enabled
  34238. */
  34239. this._backFaceCulling = true;
  34240. /**
  34241. * Gets a boolean indicating that current material needs to register RTT
  34242. */
  34243. this.hasRenderTargetTextures = false;
  34244. /**
  34245. * Specifies if the material should be serialized
  34246. */
  34247. this.doNotSerialize = false;
  34248. /**
  34249. * Specifies if the effect should be stored on sub meshes
  34250. */
  34251. this.storeEffectOnSubMeshes = false;
  34252. /**
  34253. * An event triggered when the material is disposed
  34254. */
  34255. this.onDisposeObservable = new BABYLON.Observable();
  34256. /**
  34257. * Stores the value of the alpha mode
  34258. */
  34259. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34260. /**
  34261. * Stores the state of the need depth pre-pass value
  34262. */
  34263. this._needDepthPrePass = false;
  34264. /**
  34265. * Specifies if depth writing should be disabled
  34266. */
  34267. this.disableDepthWrite = false;
  34268. /**
  34269. * Specifies if depth writing should be forced
  34270. */
  34271. this.forceDepthWrite = false;
  34272. /**
  34273. * Specifies if there should be a separate pass for culling
  34274. */
  34275. this.separateCullingPass = false;
  34276. /**
  34277. * Stores the state specifing if fog should be enabled
  34278. */
  34279. this._fogEnabled = true;
  34280. /**
  34281. * Stores the size of points
  34282. */
  34283. this.pointSize = 1.0;
  34284. /**
  34285. * Stores the z offset value
  34286. */
  34287. this.zOffset = 0;
  34288. /**
  34289. * @hidden
  34290. * Specifies if the material was previously ready
  34291. */
  34292. this._wasPreviouslyReady = false;
  34293. /**
  34294. * Stores the fill mode state
  34295. */
  34296. this._fillMode = Material.TriangleFillMode;
  34297. this.name = name;
  34298. this.id = name || BABYLON.Tools.RandomId();
  34299. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34300. this.uniqueId = this._scene.getUniqueId();
  34301. if (this._scene.useRightHandedSystem) {
  34302. this.sideOrientation = Material.ClockWiseSideOrientation;
  34303. }
  34304. else {
  34305. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34306. }
  34307. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34308. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34309. if (!doNotAdd) {
  34310. this._scene.materials.push(this);
  34311. }
  34312. }
  34313. Object.defineProperty(Material, "TriangleFillMode", {
  34314. /**
  34315. * Returns the triangle fill mode
  34316. */
  34317. get: function () {
  34318. return Material._TriangleFillMode;
  34319. },
  34320. enumerable: true,
  34321. configurable: true
  34322. });
  34323. Object.defineProperty(Material, "WireFrameFillMode", {
  34324. /**
  34325. * Returns the wireframe mode
  34326. */
  34327. get: function () {
  34328. return Material._WireFrameFillMode;
  34329. },
  34330. enumerable: true,
  34331. configurable: true
  34332. });
  34333. Object.defineProperty(Material, "PointFillMode", {
  34334. /**
  34335. * Returns the point fill mode
  34336. */
  34337. get: function () {
  34338. return Material._PointFillMode;
  34339. },
  34340. enumerable: true,
  34341. configurable: true
  34342. });
  34343. Object.defineProperty(Material, "PointListDrawMode", {
  34344. /**
  34345. * Returns the point list draw mode
  34346. */
  34347. get: function () {
  34348. return Material._PointListDrawMode;
  34349. },
  34350. enumerable: true,
  34351. configurable: true
  34352. });
  34353. Object.defineProperty(Material, "LineListDrawMode", {
  34354. /**
  34355. * Returns the line list draw mode
  34356. */
  34357. get: function () {
  34358. return Material._LineListDrawMode;
  34359. },
  34360. enumerable: true,
  34361. configurable: true
  34362. });
  34363. Object.defineProperty(Material, "LineLoopDrawMode", {
  34364. /**
  34365. * Returns the line loop draw mode
  34366. */
  34367. get: function () {
  34368. return Material._LineLoopDrawMode;
  34369. },
  34370. enumerable: true,
  34371. configurable: true
  34372. });
  34373. Object.defineProperty(Material, "LineStripDrawMode", {
  34374. /**
  34375. * Returns the line strip draw mode
  34376. */
  34377. get: function () {
  34378. return Material._LineStripDrawMode;
  34379. },
  34380. enumerable: true,
  34381. configurable: true
  34382. });
  34383. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34384. /**
  34385. * Returns the triangle strip draw mode
  34386. */
  34387. get: function () {
  34388. return Material._TriangleStripDrawMode;
  34389. },
  34390. enumerable: true,
  34391. configurable: true
  34392. });
  34393. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34394. /**
  34395. * Returns the triangle fan draw mode
  34396. */
  34397. get: function () {
  34398. return Material._TriangleFanDrawMode;
  34399. },
  34400. enumerable: true,
  34401. configurable: true
  34402. });
  34403. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34404. /**
  34405. * Returns the clock-wise side orientation
  34406. */
  34407. get: function () {
  34408. return Material._ClockWiseSideOrientation;
  34409. },
  34410. enumerable: true,
  34411. configurable: true
  34412. });
  34413. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34414. /**
  34415. * Returns the counter clock-wise side orientation
  34416. */
  34417. get: function () {
  34418. return Material._CounterClockWiseSideOrientation;
  34419. },
  34420. enumerable: true,
  34421. configurable: true
  34422. });
  34423. Object.defineProperty(Material, "TextureDirtyFlag", {
  34424. /**
  34425. * Returns the dirty texture flag value
  34426. */
  34427. get: function () {
  34428. return Material._TextureDirtyFlag;
  34429. },
  34430. enumerable: true,
  34431. configurable: true
  34432. });
  34433. Object.defineProperty(Material, "LightDirtyFlag", {
  34434. /**
  34435. * Returns the dirty light flag value
  34436. */
  34437. get: function () {
  34438. return Material._LightDirtyFlag;
  34439. },
  34440. enumerable: true,
  34441. configurable: true
  34442. });
  34443. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34444. /**
  34445. * Returns the dirty fresnel flag value
  34446. */
  34447. get: function () {
  34448. return Material._FresnelDirtyFlag;
  34449. },
  34450. enumerable: true,
  34451. configurable: true
  34452. });
  34453. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34454. /**
  34455. * Returns the dirty attributes flag value
  34456. */
  34457. get: function () {
  34458. return Material._AttributesDirtyFlag;
  34459. },
  34460. enumerable: true,
  34461. configurable: true
  34462. });
  34463. Object.defineProperty(Material, "MiscDirtyFlag", {
  34464. /**
  34465. * Returns the dirty misc flag value
  34466. */
  34467. get: function () {
  34468. return Material._MiscDirtyFlag;
  34469. },
  34470. enumerable: true,
  34471. configurable: true
  34472. });
  34473. Object.defineProperty(Material.prototype, "alpha", {
  34474. /**
  34475. * Gets the alpha value of the material
  34476. */
  34477. get: function () {
  34478. return this._alpha;
  34479. },
  34480. /**
  34481. * Sets the alpha value of the material
  34482. */
  34483. set: function (value) {
  34484. if (this._alpha === value) {
  34485. return;
  34486. }
  34487. this._alpha = value;
  34488. this.markAsDirty(Material.MiscDirtyFlag);
  34489. },
  34490. enumerable: true,
  34491. configurable: true
  34492. });
  34493. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34494. /**
  34495. * Gets the back-face culling state
  34496. */
  34497. get: function () {
  34498. return this._backFaceCulling;
  34499. },
  34500. /**
  34501. * Sets the back-face culling state
  34502. */
  34503. set: function (value) {
  34504. if (this._backFaceCulling === value) {
  34505. return;
  34506. }
  34507. this._backFaceCulling = value;
  34508. this.markAsDirty(Material.TextureDirtyFlag);
  34509. },
  34510. enumerable: true,
  34511. configurable: true
  34512. });
  34513. Object.defineProperty(Material.prototype, "onDispose", {
  34514. /**
  34515. * Called during a dispose event
  34516. */
  34517. set: function (callback) {
  34518. if (this._onDisposeObserver) {
  34519. this.onDisposeObservable.remove(this._onDisposeObserver);
  34520. }
  34521. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34522. },
  34523. enumerable: true,
  34524. configurable: true
  34525. });
  34526. Object.defineProperty(Material.prototype, "onBindObservable", {
  34527. /**
  34528. * An event triggered when the material is bound
  34529. */
  34530. get: function () {
  34531. if (!this._onBindObservable) {
  34532. this._onBindObservable = new BABYLON.Observable();
  34533. }
  34534. return this._onBindObservable;
  34535. },
  34536. enumerable: true,
  34537. configurable: true
  34538. });
  34539. Object.defineProperty(Material.prototype, "onBind", {
  34540. /**
  34541. * Called during a bind event
  34542. */
  34543. set: function (callback) {
  34544. if (this._onBindObserver) {
  34545. this.onBindObservable.remove(this._onBindObserver);
  34546. }
  34547. this._onBindObserver = this.onBindObservable.add(callback);
  34548. },
  34549. enumerable: true,
  34550. configurable: true
  34551. });
  34552. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34553. /**
  34554. * An event triggered when the material is unbound
  34555. */
  34556. get: function () {
  34557. if (!this._onUnBindObservable) {
  34558. this._onUnBindObservable = new BABYLON.Observable();
  34559. }
  34560. return this._onUnBindObservable;
  34561. },
  34562. enumerable: true,
  34563. configurable: true
  34564. });
  34565. Object.defineProperty(Material.prototype, "alphaMode", {
  34566. /**
  34567. * Gets the value of the alpha mode
  34568. */
  34569. get: function () {
  34570. return this._alphaMode;
  34571. },
  34572. /**
  34573. * Sets the value of the alpha mode.
  34574. *
  34575. * | Value | Type | Description |
  34576. * | --- | --- | --- |
  34577. * | 0 | ALPHA_DISABLE | |
  34578. * | 1 | ALPHA_ADD | |
  34579. * | 2 | ALPHA_COMBINE | |
  34580. * | 3 | ALPHA_SUBTRACT | |
  34581. * | 4 | ALPHA_MULTIPLY | |
  34582. * | 5 | ALPHA_MAXIMIZED | |
  34583. * | 6 | ALPHA_ONEONE | |
  34584. * | 7 | ALPHA_PREMULTIPLIED | |
  34585. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34586. * | 9 | ALPHA_INTERPOLATE | |
  34587. * | 10 | ALPHA_SCREENMODE | |
  34588. *
  34589. */
  34590. set: function (value) {
  34591. if (this._alphaMode === value) {
  34592. return;
  34593. }
  34594. this._alphaMode = value;
  34595. this.markAsDirty(Material.TextureDirtyFlag);
  34596. },
  34597. enumerable: true,
  34598. configurable: true
  34599. });
  34600. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34601. /**
  34602. * Gets the depth pre-pass value
  34603. */
  34604. get: function () {
  34605. return this._needDepthPrePass;
  34606. },
  34607. /**
  34608. * Sets the need depth pre-pass value
  34609. */
  34610. set: function (value) {
  34611. if (this._needDepthPrePass === value) {
  34612. return;
  34613. }
  34614. this._needDepthPrePass = value;
  34615. if (this._needDepthPrePass) {
  34616. this.checkReadyOnEveryCall = true;
  34617. }
  34618. },
  34619. enumerable: true,
  34620. configurable: true
  34621. });
  34622. Object.defineProperty(Material.prototype, "fogEnabled", {
  34623. /**
  34624. * Gets the value of the fog enabled state
  34625. */
  34626. get: function () {
  34627. return this._fogEnabled;
  34628. },
  34629. /**
  34630. * Sets the state for enabling fog
  34631. */
  34632. set: function (value) {
  34633. if (this._fogEnabled === value) {
  34634. return;
  34635. }
  34636. this._fogEnabled = value;
  34637. this.markAsDirty(Material.MiscDirtyFlag);
  34638. },
  34639. enumerable: true,
  34640. configurable: true
  34641. });
  34642. Object.defineProperty(Material.prototype, "wireframe", {
  34643. /**
  34644. * Gets a value specifying if wireframe mode is enabled
  34645. */
  34646. get: function () {
  34647. switch (this._fillMode) {
  34648. case Material.WireFrameFillMode:
  34649. case Material.LineListDrawMode:
  34650. case Material.LineLoopDrawMode:
  34651. case Material.LineStripDrawMode:
  34652. return true;
  34653. }
  34654. return this._scene.forceWireframe;
  34655. },
  34656. /**
  34657. * Sets the state of wireframe mode
  34658. */
  34659. set: function (value) {
  34660. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34661. },
  34662. enumerable: true,
  34663. configurable: true
  34664. });
  34665. Object.defineProperty(Material.prototype, "pointsCloud", {
  34666. /**
  34667. * Gets the value specifying if point clouds are enabled
  34668. */
  34669. get: function () {
  34670. switch (this._fillMode) {
  34671. case Material.PointFillMode:
  34672. case Material.PointListDrawMode:
  34673. return true;
  34674. }
  34675. return this._scene.forcePointsCloud;
  34676. },
  34677. /**
  34678. * Sets the state of point cloud mode
  34679. */
  34680. set: function (value) {
  34681. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34682. },
  34683. enumerable: true,
  34684. configurable: true
  34685. });
  34686. Object.defineProperty(Material.prototype, "fillMode", {
  34687. /**
  34688. * Gets the material fill mode
  34689. */
  34690. get: function () {
  34691. return this._fillMode;
  34692. },
  34693. /**
  34694. * Sets the material fill mode
  34695. */
  34696. set: function (value) {
  34697. if (this._fillMode === value) {
  34698. return;
  34699. }
  34700. this._fillMode = value;
  34701. this.markAsDirty(Material.MiscDirtyFlag);
  34702. },
  34703. enumerable: true,
  34704. configurable: true
  34705. });
  34706. /**
  34707. * Returns a string representation of the current material
  34708. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34709. * @returns a string with material information
  34710. */
  34711. Material.prototype.toString = function (fullDetails) {
  34712. var ret = "Name: " + this.name;
  34713. if (fullDetails) {
  34714. }
  34715. return ret;
  34716. };
  34717. /**
  34718. * Gets the class name of the material
  34719. * @returns a string with the class name of the material
  34720. */
  34721. Material.prototype.getClassName = function () {
  34722. return "Material";
  34723. };
  34724. Object.defineProperty(Material.prototype, "isFrozen", {
  34725. /**
  34726. * Specifies if updates for the material been locked
  34727. */
  34728. get: function () {
  34729. return this.checkReadyOnlyOnce;
  34730. },
  34731. enumerable: true,
  34732. configurable: true
  34733. });
  34734. /**
  34735. * Locks updates for the material
  34736. */
  34737. Material.prototype.freeze = function () {
  34738. this.checkReadyOnlyOnce = true;
  34739. };
  34740. /**
  34741. * Unlocks updates for the material
  34742. */
  34743. Material.prototype.unfreeze = function () {
  34744. this.checkReadyOnlyOnce = false;
  34745. };
  34746. /**
  34747. * Specifies if the material is ready to be used
  34748. * @param mesh defines the mesh to check
  34749. * @param useInstances specifies if instances should be used
  34750. * @returns a boolean indicating if the material is ready to be used
  34751. */
  34752. Material.prototype.isReady = function (mesh, useInstances) {
  34753. return true;
  34754. };
  34755. /**
  34756. * Specifies that the submesh is ready to be used
  34757. * @param mesh defines the mesh to check
  34758. * @param subMesh defines which submesh to check
  34759. * @param useInstances specifies that instances should be used
  34760. * @returns a boolean indicating that the submesh is ready or not
  34761. */
  34762. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34763. return false;
  34764. };
  34765. /**
  34766. * Returns the material effect
  34767. * @returns the effect associated with the material
  34768. */
  34769. Material.prototype.getEffect = function () {
  34770. return this._effect;
  34771. };
  34772. /**
  34773. * Returns the current scene
  34774. * @returns a Scene
  34775. */
  34776. Material.prototype.getScene = function () {
  34777. return this._scene;
  34778. };
  34779. /**
  34780. * Specifies if the material will require alpha blending
  34781. * @returns a boolean specifying if alpha blending is needed
  34782. */
  34783. Material.prototype.needAlphaBlending = function () {
  34784. return (this.alpha < 1.0);
  34785. };
  34786. /**
  34787. * Specifies if the mesh will require alpha blending
  34788. * @param mesh defines the mesh to check
  34789. * @returns a boolean specifying if alpha blending is needed for the mesh
  34790. */
  34791. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34792. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34793. };
  34794. /**
  34795. * Specifies if this material should be rendered in alpha test mode
  34796. * @returns a boolean specifying if an alpha test is needed.
  34797. */
  34798. Material.prototype.needAlphaTesting = function () {
  34799. return false;
  34800. };
  34801. /**
  34802. * Gets the texture used for the alpha test
  34803. * @returns the texture to use for alpha testing
  34804. */
  34805. Material.prototype.getAlphaTestTexture = function () {
  34806. return null;
  34807. };
  34808. /**
  34809. * Marks the material to indicate that it needs to be re-calculated
  34810. */
  34811. Material.prototype.markDirty = function () {
  34812. this._wasPreviouslyReady = false;
  34813. };
  34814. /** @hidden */
  34815. Material.prototype._preBind = function (effect, overrideOrientation) {
  34816. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34817. var engine = this._scene.getEngine();
  34818. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34819. var reverse = orientation === Material.ClockWiseSideOrientation;
  34820. engine.enableEffect(effect ? effect : this._effect);
  34821. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34822. return reverse;
  34823. };
  34824. /**
  34825. * Binds the material to the mesh
  34826. * @param world defines the world transformation matrix
  34827. * @param mesh defines the mesh to bind the material to
  34828. */
  34829. Material.prototype.bind = function (world, mesh) {
  34830. };
  34831. /**
  34832. * Binds the submesh to the material
  34833. * @param world defines the world transformation matrix
  34834. * @param mesh defines the mesh containing the submesh
  34835. * @param subMesh defines the submesh to bind the material to
  34836. */
  34837. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34838. };
  34839. /**
  34840. * Binds the world matrix to the material
  34841. * @param world defines the world transformation matrix
  34842. */
  34843. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34844. };
  34845. /**
  34846. * Binds the scene's uniform buffer to the effect.
  34847. * @param effect defines the effect to bind to the scene uniform buffer
  34848. * @param sceneUbo defines the uniform buffer storing scene data
  34849. */
  34850. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34851. sceneUbo.bindToEffect(effect, "Scene");
  34852. };
  34853. /**
  34854. * Binds the view matrix to the effect
  34855. * @param effect defines the effect to bind the view matrix to
  34856. */
  34857. Material.prototype.bindView = function (effect) {
  34858. if (!this._useUBO) {
  34859. effect.setMatrix("view", this.getScene().getViewMatrix());
  34860. }
  34861. else {
  34862. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34863. }
  34864. };
  34865. /**
  34866. * Binds the view projection matrix to the effect
  34867. * @param effect defines the effect to bind the view projection matrix to
  34868. */
  34869. Material.prototype.bindViewProjection = function (effect) {
  34870. if (!this._useUBO) {
  34871. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34872. }
  34873. else {
  34874. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34875. }
  34876. };
  34877. /**
  34878. * Specifies if material alpha testing should be turned on for the mesh
  34879. * @param mesh defines the mesh to check
  34880. */
  34881. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34882. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34883. };
  34884. /**
  34885. * Processes to execute after binding the material to a mesh
  34886. * @param mesh defines the rendered mesh
  34887. */
  34888. Material.prototype._afterBind = function (mesh) {
  34889. this._scene._cachedMaterial = this;
  34890. if (mesh) {
  34891. this._scene._cachedVisibility = mesh.visibility;
  34892. }
  34893. else {
  34894. this._scene._cachedVisibility = 1;
  34895. }
  34896. if (this._onBindObservable && mesh) {
  34897. this._onBindObservable.notifyObservers(mesh);
  34898. }
  34899. if (this.disableDepthWrite) {
  34900. var engine = this._scene.getEngine();
  34901. this._cachedDepthWriteState = engine.getDepthWrite();
  34902. engine.setDepthWrite(false);
  34903. }
  34904. };
  34905. /**
  34906. * Unbinds the material from the mesh
  34907. */
  34908. Material.prototype.unbind = function () {
  34909. if (this._onUnBindObservable) {
  34910. this._onUnBindObservable.notifyObservers(this);
  34911. }
  34912. if (this.disableDepthWrite) {
  34913. var engine = this._scene.getEngine();
  34914. engine.setDepthWrite(this._cachedDepthWriteState);
  34915. }
  34916. };
  34917. /**
  34918. * Gets the active textures from the material
  34919. * @returns an array of textures
  34920. */
  34921. Material.prototype.getActiveTextures = function () {
  34922. return [];
  34923. };
  34924. /**
  34925. * Specifies if the material uses a texture
  34926. * @param texture defines the texture to check against the material
  34927. * @returns a boolean specifying if the material uses the texture
  34928. */
  34929. Material.prototype.hasTexture = function (texture) {
  34930. return false;
  34931. };
  34932. /**
  34933. * Makes a duplicate of the material, and gives it a new name
  34934. * @param name defines the new name for the duplicated material
  34935. * @returns the cloned material
  34936. */
  34937. Material.prototype.clone = function (name) {
  34938. return null;
  34939. };
  34940. /**
  34941. * Gets the meshes bound to the material
  34942. * @returns an array of meshes bound to the material
  34943. */
  34944. Material.prototype.getBindedMeshes = function () {
  34945. var result = new Array();
  34946. for (var index = 0; index < this._scene.meshes.length; index++) {
  34947. var mesh = this._scene.meshes[index];
  34948. if (mesh.material === this) {
  34949. result.push(mesh);
  34950. }
  34951. }
  34952. return result;
  34953. };
  34954. /**
  34955. * Force shader compilation
  34956. * @param mesh defines the mesh associated with this material
  34957. * @param onCompiled defines a function to execute once the material is compiled
  34958. * @param options defines the options to configure the compilation
  34959. */
  34960. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34961. var _this = this;
  34962. var localOptions = __assign({ clipPlane: false }, options);
  34963. var subMesh = new BABYLON.BaseSubMesh();
  34964. var scene = this.getScene();
  34965. var checkReady = function () {
  34966. if (!_this._scene || !_this._scene.getEngine()) {
  34967. return;
  34968. }
  34969. if (subMesh._materialDefines) {
  34970. subMesh._materialDefines._renderId = -1;
  34971. }
  34972. var clipPlaneState = scene.clipPlane;
  34973. if (localOptions.clipPlane) {
  34974. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34975. }
  34976. if (_this.storeEffectOnSubMeshes) {
  34977. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34978. if (onCompiled) {
  34979. onCompiled(_this);
  34980. }
  34981. }
  34982. else {
  34983. setTimeout(checkReady, 16);
  34984. }
  34985. }
  34986. else {
  34987. if (_this.isReady(mesh)) {
  34988. if (onCompiled) {
  34989. onCompiled(_this);
  34990. }
  34991. }
  34992. else {
  34993. setTimeout(checkReady, 16);
  34994. }
  34995. }
  34996. if (localOptions.clipPlane) {
  34997. scene.clipPlane = clipPlaneState;
  34998. }
  34999. };
  35000. checkReady();
  35001. };
  35002. /**
  35003. * Force shader compilation
  35004. * @param mesh defines the mesh that will use this material
  35005. * @param options defines additional options for compiling the shaders
  35006. * @returns a promise that resolves when the compilation completes
  35007. */
  35008. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35009. var _this = this;
  35010. return new Promise(function (resolve) {
  35011. _this.forceCompilation(mesh, function () {
  35012. resolve();
  35013. }, options);
  35014. });
  35015. };
  35016. /**
  35017. * Marks a define in the material to indicate that it needs to be re-computed
  35018. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35019. */
  35020. Material.prototype.markAsDirty = function (flag) {
  35021. if (flag & Material.TextureDirtyFlag) {
  35022. this._markAllSubMeshesAsTexturesDirty();
  35023. }
  35024. if (flag & Material.LightDirtyFlag) {
  35025. this._markAllSubMeshesAsLightsDirty();
  35026. }
  35027. if (flag & Material.FresnelDirtyFlag) {
  35028. this._markAllSubMeshesAsFresnelDirty();
  35029. }
  35030. if (flag & Material.AttributesDirtyFlag) {
  35031. this._markAllSubMeshesAsAttributesDirty();
  35032. }
  35033. if (flag & Material.MiscDirtyFlag) {
  35034. this._markAllSubMeshesAsMiscDirty();
  35035. }
  35036. this.getScene().resetCachedMaterial();
  35037. };
  35038. /**
  35039. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35040. * @param func defines a function which checks material defines against the submeshes
  35041. */
  35042. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35043. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35044. var mesh = _a[_i];
  35045. if (!mesh.subMeshes) {
  35046. continue;
  35047. }
  35048. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35049. var subMesh = _c[_b];
  35050. if (subMesh.getMaterial() !== this) {
  35051. continue;
  35052. }
  35053. if (!subMesh._materialDefines) {
  35054. continue;
  35055. }
  35056. func(subMesh._materialDefines);
  35057. }
  35058. }
  35059. };
  35060. /**
  35061. * Indicates that image processing needs to be re-calculated for all submeshes
  35062. */
  35063. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35064. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35065. };
  35066. /**
  35067. * Indicates that textures need to be re-calculated for all submeshes
  35068. */
  35069. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35070. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35071. };
  35072. /**
  35073. * Indicates that fresnel needs to be re-calculated for all submeshes
  35074. */
  35075. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35076. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35077. };
  35078. /**
  35079. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35080. */
  35081. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35082. this._markAllSubMeshesAsDirty(function (defines) {
  35083. defines.markAsFresnelDirty();
  35084. defines.markAsMiscDirty();
  35085. });
  35086. };
  35087. /**
  35088. * Indicates that lights need to be re-calculated for all submeshes
  35089. */
  35090. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35091. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35092. };
  35093. /**
  35094. * Indicates that attributes need to be re-calculated for all submeshes
  35095. */
  35096. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35097. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35098. };
  35099. /**
  35100. * Indicates that misc needs to be re-calculated for all submeshes
  35101. */
  35102. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35103. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35104. };
  35105. /**
  35106. * Indicates that textures and misc need to be re-calculated for all submeshes
  35107. */
  35108. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35109. this._markAllSubMeshesAsDirty(function (defines) {
  35110. defines.markAsTexturesDirty();
  35111. defines.markAsMiscDirty();
  35112. });
  35113. };
  35114. /**
  35115. * Disposes the material
  35116. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35117. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35118. */
  35119. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35120. // Animations
  35121. this.getScene().stopAnimation(this);
  35122. this.getScene().freeProcessedMaterials();
  35123. // Remove from scene
  35124. var index = this._scene.materials.indexOf(this);
  35125. if (index >= 0) {
  35126. this._scene.materials.splice(index, 1);
  35127. }
  35128. // Remove from meshes
  35129. for (index = 0; index < this._scene.meshes.length; index++) {
  35130. var mesh = this._scene.meshes[index];
  35131. if (mesh.material === this) {
  35132. mesh.material = null;
  35133. if (mesh.geometry) {
  35134. var geometry = (mesh.geometry);
  35135. if (this.storeEffectOnSubMeshes) {
  35136. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35137. var subMesh = _a[_i];
  35138. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35139. if (forceDisposeEffect && subMesh._materialEffect) {
  35140. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35141. }
  35142. }
  35143. }
  35144. else {
  35145. geometry._releaseVertexArrayObject(this._effect);
  35146. }
  35147. }
  35148. }
  35149. }
  35150. this._uniformBuffer.dispose();
  35151. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35152. if (forceDisposeEffect && this._effect) {
  35153. if (!this.storeEffectOnSubMeshes) {
  35154. this._scene.getEngine()._releaseEffect(this._effect);
  35155. }
  35156. this._effect = null;
  35157. }
  35158. // Callback
  35159. this.onDisposeObservable.notifyObservers(this);
  35160. this.onDisposeObservable.clear();
  35161. if (this._onBindObservable) {
  35162. this._onBindObservable.clear();
  35163. }
  35164. if (this._onUnBindObservable) {
  35165. this._onUnBindObservable.clear();
  35166. }
  35167. };
  35168. /**
  35169. * Serializes this material
  35170. * @returns the serialized material object
  35171. */
  35172. Material.prototype.serialize = function () {
  35173. return BABYLON.SerializationHelper.Serialize(this);
  35174. };
  35175. /**
  35176. * Creates a MultiMaterial from parsed MultiMaterial data.
  35177. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35178. * @param scene defines the hosting scene
  35179. * @returns a new MultiMaterial
  35180. */
  35181. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35182. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35183. multiMaterial.id = parsedMultiMaterial.id;
  35184. if (BABYLON.Tags) {
  35185. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35186. }
  35187. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35188. var subMatId = parsedMultiMaterial.materials[matIndex];
  35189. if (subMatId) {
  35190. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35191. }
  35192. else {
  35193. multiMaterial.subMaterials.push(null);
  35194. }
  35195. }
  35196. return multiMaterial;
  35197. };
  35198. /**
  35199. * Creates a material from parsed material data
  35200. * @param parsedMaterial defines parsed material data
  35201. * @param scene defines the hosting scene
  35202. * @param rootUrl defines the root URL to use to load textures
  35203. * @returns a new material
  35204. */
  35205. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35206. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35207. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35208. }
  35209. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35210. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35211. if (!BABYLON.LegacyPBRMaterial) {
  35212. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35213. return;
  35214. }
  35215. }
  35216. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35217. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35218. };
  35219. // Triangle views
  35220. Material._TriangleFillMode = 0;
  35221. Material._WireFrameFillMode = 1;
  35222. Material._PointFillMode = 2;
  35223. // Draw modes
  35224. Material._PointListDrawMode = 3;
  35225. Material._LineListDrawMode = 4;
  35226. Material._LineLoopDrawMode = 5;
  35227. Material._LineStripDrawMode = 6;
  35228. Material._TriangleStripDrawMode = 7;
  35229. Material._TriangleFanDrawMode = 8;
  35230. /**
  35231. * Stores the clock-wise side orientation
  35232. */
  35233. Material._ClockWiseSideOrientation = 0;
  35234. /**
  35235. * Stores the counter clock-wise side orientation
  35236. */
  35237. Material._CounterClockWiseSideOrientation = 1;
  35238. /**
  35239. * The dirty texture flag value
  35240. */
  35241. Material._TextureDirtyFlag = 1;
  35242. /**
  35243. * The dirty light flag value
  35244. */
  35245. Material._LightDirtyFlag = 2;
  35246. /**
  35247. * The dirty fresnel flag value
  35248. */
  35249. Material._FresnelDirtyFlag = 4;
  35250. /**
  35251. * The dirty attribute flag value
  35252. */
  35253. Material._AttributesDirtyFlag = 8;
  35254. /**
  35255. * The dirty misc flag value
  35256. */
  35257. Material._MiscDirtyFlag = 16;
  35258. __decorate([
  35259. BABYLON.serialize()
  35260. ], Material.prototype, "id", void 0);
  35261. __decorate([
  35262. BABYLON.serialize()
  35263. ], Material.prototype, "uniqueId", void 0);
  35264. __decorate([
  35265. BABYLON.serialize()
  35266. ], Material.prototype, "name", void 0);
  35267. __decorate([
  35268. BABYLON.serialize()
  35269. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35270. __decorate([
  35271. BABYLON.serialize()
  35272. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35273. __decorate([
  35274. BABYLON.serialize()
  35275. ], Material.prototype, "state", void 0);
  35276. __decorate([
  35277. BABYLON.serialize("alpha")
  35278. ], Material.prototype, "_alpha", void 0);
  35279. __decorate([
  35280. BABYLON.serialize("backFaceCulling")
  35281. ], Material.prototype, "_backFaceCulling", void 0);
  35282. __decorate([
  35283. BABYLON.serialize()
  35284. ], Material.prototype, "sideOrientation", void 0);
  35285. __decorate([
  35286. BABYLON.serialize("alphaMode")
  35287. ], Material.prototype, "_alphaMode", void 0);
  35288. __decorate([
  35289. BABYLON.serialize()
  35290. ], Material.prototype, "_needDepthPrePass", void 0);
  35291. __decorate([
  35292. BABYLON.serialize()
  35293. ], Material.prototype, "disableDepthWrite", void 0);
  35294. __decorate([
  35295. BABYLON.serialize()
  35296. ], Material.prototype, "forceDepthWrite", void 0);
  35297. __decorate([
  35298. BABYLON.serialize()
  35299. ], Material.prototype, "separateCullingPass", void 0);
  35300. __decorate([
  35301. BABYLON.serialize("fogEnabled")
  35302. ], Material.prototype, "_fogEnabled", void 0);
  35303. __decorate([
  35304. BABYLON.serialize()
  35305. ], Material.prototype, "pointSize", void 0);
  35306. __decorate([
  35307. BABYLON.serialize()
  35308. ], Material.prototype, "zOffset", void 0);
  35309. __decorate([
  35310. BABYLON.serialize()
  35311. ], Material.prototype, "wireframe", null);
  35312. __decorate([
  35313. BABYLON.serialize()
  35314. ], Material.prototype, "pointsCloud", null);
  35315. __decorate([
  35316. BABYLON.serialize()
  35317. ], Material.prototype, "fillMode", null);
  35318. return Material;
  35319. }());
  35320. BABYLON.Material = Material;
  35321. })(BABYLON || (BABYLON = {}));
  35322. //# sourceMappingURL=babylon.material.js.map
  35323. var BABYLON;
  35324. (function (BABYLON) {
  35325. var UniformBuffer = /** @class */ (function () {
  35326. /**
  35327. * Uniform buffer objects.
  35328. *
  35329. * Handles blocks of uniform on the GPU.
  35330. *
  35331. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35332. *
  35333. * For more information, please refer to :
  35334. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35335. */
  35336. function UniformBuffer(engine, data, dynamic) {
  35337. this._engine = engine;
  35338. this._noUBO = !engine.supportsUniformBuffers;
  35339. this._dynamic = dynamic;
  35340. this._data = data || [];
  35341. this._uniformLocations = {};
  35342. this._uniformSizes = {};
  35343. this._uniformLocationPointer = 0;
  35344. this._needSync = false;
  35345. if (this._noUBO) {
  35346. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35347. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35348. this.updateFloat = this._updateFloatForEffect;
  35349. this.updateFloat2 = this._updateFloat2ForEffect;
  35350. this.updateFloat3 = this._updateFloat3ForEffect;
  35351. this.updateFloat4 = this._updateFloat4ForEffect;
  35352. this.updateMatrix = this._updateMatrixForEffect;
  35353. this.updateVector3 = this._updateVector3ForEffect;
  35354. this.updateVector4 = this._updateVector4ForEffect;
  35355. this.updateColor3 = this._updateColor3ForEffect;
  35356. this.updateColor4 = this._updateColor4ForEffect;
  35357. }
  35358. else {
  35359. this._engine._uniformBuffers.push(this);
  35360. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35361. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35362. this.updateFloat = this._updateFloatForUniform;
  35363. this.updateFloat2 = this._updateFloat2ForUniform;
  35364. this.updateFloat3 = this._updateFloat3ForUniform;
  35365. this.updateFloat4 = this._updateFloat4ForUniform;
  35366. this.updateMatrix = this._updateMatrixForUniform;
  35367. this.updateVector3 = this._updateVector3ForUniform;
  35368. this.updateVector4 = this._updateVector4ForUniform;
  35369. this.updateColor3 = this._updateColor3ForUniform;
  35370. this.updateColor4 = this._updateColor4ForUniform;
  35371. }
  35372. }
  35373. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35374. // Properties
  35375. /**
  35376. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35377. * or just falling back on setUniformXXX calls.
  35378. */
  35379. get: function () {
  35380. return !this._noUBO;
  35381. },
  35382. enumerable: true,
  35383. configurable: true
  35384. });
  35385. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35386. /**
  35387. * Indicates if the WebGL underlying uniform buffer is in sync
  35388. * with the javascript cache data.
  35389. */
  35390. get: function () {
  35391. return !this._needSync;
  35392. },
  35393. enumerable: true,
  35394. configurable: true
  35395. });
  35396. /**
  35397. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35398. * Also, a dynamic UniformBuffer will disable cache verification and always
  35399. * update the underlying WebGL uniform buffer to the GPU.
  35400. */
  35401. UniformBuffer.prototype.isDynamic = function () {
  35402. return this._dynamic !== undefined;
  35403. };
  35404. /**
  35405. * The data cache on JS side.
  35406. */
  35407. UniformBuffer.prototype.getData = function () {
  35408. return this._bufferData;
  35409. };
  35410. /**
  35411. * The underlying WebGL Uniform buffer.
  35412. */
  35413. UniformBuffer.prototype.getBuffer = function () {
  35414. return this._buffer;
  35415. };
  35416. /**
  35417. * std140 layout specifies how to align data within an UBO structure.
  35418. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35419. * for specs.
  35420. */
  35421. UniformBuffer.prototype._fillAlignment = function (size) {
  35422. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35423. // and 4x4 matrices
  35424. // TODO : change if other types are used
  35425. var alignment;
  35426. if (size <= 2) {
  35427. alignment = size;
  35428. }
  35429. else {
  35430. alignment = 4;
  35431. }
  35432. if ((this._uniformLocationPointer % alignment) !== 0) {
  35433. var oldPointer = this._uniformLocationPointer;
  35434. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35435. var diff = this._uniformLocationPointer - oldPointer;
  35436. for (var i = 0; i < diff; i++) {
  35437. this._data.push(0);
  35438. }
  35439. }
  35440. };
  35441. /**
  35442. * Adds an uniform in the buffer.
  35443. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35444. * for the layout to be correct !
  35445. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35446. * @param {number|number[]} size Data size, or data directly.
  35447. */
  35448. UniformBuffer.prototype.addUniform = function (name, size) {
  35449. if (this._noUBO) {
  35450. return;
  35451. }
  35452. if (this._uniformLocations[name] !== undefined) {
  35453. // Already existing uniform
  35454. return;
  35455. }
  35456. // This function must be called in the order of the shader layout !
  35457. // size can be the size of the uniform, or data directly
  35458. var data;
  35459. if (size instanceof Array) {
  35460. data = size;
  35461. size = data.length;
  35462. }
  35463. else {
  35464. size = size;
  35465. data = [];
  35466. // Fill with zeros
  35467. for (var i = 0; i < size; i++) {
  35468. data.push(0);
  35469. }
  35470. }
  35471. this._fillAlignment(size);
  35472. this._uniformSizes[name] = size;
  35473. this._uniformLocations[name] = this._uniformLocationPointer;
  35474. this._uniformLocationPointer += size;
  35475. for (var i = 0; i < size; i++) {
  35476. this._data.push(data[i]);
  35477. }
  35478. this._needSync = true;
  35479. };
  35480. /**
  35481. * Wrapper for addUniform.
  35482. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35483. * @param {Matrix} mat A 4x4 matrix.
  35484. */
  35485. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35486. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35487. };
  35488. /**
  35489. * Wrapper for addUniform.
  35490. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35491. * @param {number} x
  35492. * @param {number} y
  35493. */
  35494. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35495. var temp = [x, y];
  35496. this.addUniform(name, temp);
  35497. };
  35498. /**
  35499. * Wrapper for addUniform.
  35500. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35501. * @param {number} x
  35502. * @param {number} y
  35503. * @param {number} z
  35504. */
  35505. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35506. var temp = [x, y, z];
  35507. this.addUniform(name, temp);
  35508. };
  35509. /**
  35510. * Wrapper for addUniform.
  35511. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35512. * @param {Color3} color
  35513. */
  35514. UniformBuffer.prototype.addColor3 = function (name, color) {
  35515. var temp = new Array();
  35516. color.toArray(temp);
  35517. this.addUniform(name, temp);
  35518. };
  35519. /**
  35520. * Wrapper for addUniform.
  35521. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35522. * @param {Color3} color
  35523. * @param {number} alpha
  35524. */
  35525. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35526. var temp = new Array();
  35527. color.toArray(temp);
  35528. temp.push(alpha);
  35529. this.addUniform(name, temp);
  35530. };
  35531. /**
  35532. * Wrapper for addUniform.
  35533. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35534. * @param {Vector3} vector
  35535. */
  35536. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35537. var temp = new Array();
  35538. vector.toArray(temp);
  35539. this.addUniform(name, temp);
  35540. };
  35541. /**
  35542. * Wrapper for addUniform.
  35543. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35544. */
  35545. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35546. this.addUniform(name, 12);
  35547. };
  35548. /**
  35549. * Wrapper for addUniform.
  35550. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35551. */
  35552. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35553. this.addUniform(name, 8);
  35554. };
  35555. /**
  35556. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35557. */
  35558. UniformBuffer.prototype.create = function () {
  35559. if (this._noUBO) {
  35560. return;
  35561. }
  35562. if (this._buffer) {
  35563. return; // nothing to do
  35564. }
  35565. // See spec, alignment must be filled as a vec4
  35566. this._fillAlignment(4);
  35567. this._bufferData = new Float32Array(this._data);
  35568. this._rebuild();
  35569. this._needSync = true;
  35570. };
  35571. /** @hidden */
  35572. UniformBuffer.prototype._rebuild = function () {
  35573. if (this._noUBO) {
  35574. return;
  35575. }
  35576. if (this._dynamic) {
  35577. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35578. }
  35579. else {
  35580. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35581. }
  35582. };
  35583. /**
  35584. * Updates the WebGL Uniform Buffer on the GPU.
  35585. * If the `dynamic` flag is set to true, no cache comparison is done.
  35586. * Otherwise, the buffer will be updated only if the cache differs.
  35587. */
  35588. UniformBuffer.prototype.update = function () {
  35589. if (!this._buffer) {
  35590. this.create();
  35591. return;
  35592. }
  35593. if (!this._dynamic && !this._needSync) {
  35594. return;
  35595. }
  35596. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35597. this._needSync = false;
  35598. };
  35599. /**
  35600. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35601. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35602. * @param {number[]|Float32Array} data Flattened data
  35603. * @param {number} size Size of the data.
  35604. */
  35605. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35606. var location = this._uniformLocations[uniformName];
  35607. if (location === undefined) {
  35608. if (this._buffer) {
  35609. // Cannot add an uniform if the buffer is already created
  35610. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35611. return;
  35612. }
  35613. this.addUniform(uniformName, size);
  35614. location = this._uniformLocations[uniformName];
  35615. }
  35616. if (!this._buffer) {
  35617. this.create();
  35618. }
  35619. if (!this._dynamic) {
  35620. // Cache for static uniform buffers
  35621. var changed = false;
  35622. for (var i = 0; i < size; i++) {
  35623. if (this._bufferData[location + i] !== data[i]) {
  35624. changed = true;
  35625. this._bufferData[location + i] = data[i];
  35626. }
  35627. }
  35628. this._needSync = this._needSync || changed;
  35629. }
  35630. else {
  35631. // No cache for dynamic
  35632. for (var i = 0; i < size; i++) {
  35633. this._bufferData[location + i] = data[i];
  35634. }
  35635. }
  35636. };
  35637. // Update methods
  35638. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35639. // To match std140, matrix must be realigned
  35640. for (var i = 0; i < 3; i++) {
  35641. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35642. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35643. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35644. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35645. }
  35646. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35647. };
  35648. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35649. this._currentEffect.setMatrix3x3(name, matrix);
  35650. };
  35651. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35652. this._currentEffect.setMatrix2x2(name, matrix);
  35653. };
  35654. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35655. // To match std140, matrix must be realigned
  35656. for (var i = 0; i < 2; i++) {
  35657. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35658. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35659. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35660. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35661. }
  35662. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35663. };
  35664. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35665. this._currentEffect.setFloat(name, x);
  35666. };
  35667. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35668. UniformBuffer._tempBuffer[0] = x;
  35669. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35670. };
  35671. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35672. if (suffix === void 0) { suffix = ""; }
  35673. this._currentEffect.setFloat2(name + suffix, x, y);
  35674. };
  35675. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35676. if (suffix === void 0) { suffix = ""; }
  35677. UniformBuffer._tempBuffer[0] = x;
  35678. UniformBuffer._tempBuffer[1] = y;
  35679. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35680. };
  35681. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35682. if (suffix === void 0) { suffix = ""; }
  35683. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35684. };
  35685. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35686. if (suffix === void 0) { suffix = ""; }
  35687. UniformBuffer._tempBuffer[0] = x;
  35688. UniformBuffer._tempBuffer[1] = y;
  35689. UniformBuffer._tempBuffer[2] = z;
  35690. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35691. };
  35692. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35693. if (suffix === void 0) { suffix = ""; }
  35694. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35695. };
  35696. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35697. if (suffix === void 0) { suffix = ""; }
  35698. UniformBuffer._tempBuffer[0] = x;
  35699. UniformBuffer._tempBuffer[1] = y;
  35700. UniformBuffer._tempBuffer[2] = z;
  35701. UniformBuffer._tempBuffer[3] = w;
  35702. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35703. };
  35704. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35705. this._currentEffect.setMatrix(name, mat);
  35706. };
  35707. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35708. this.updateUniform(name, mat.toArray(), 16);
  35709. };
  35710. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35711. this._currentEffect.setVector3(name, vector);
  35712. };
  35713. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35714. vector.toArray(UniformBuffer._tempBuffer);
  35715. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35716. };
  35717. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35718. this._currentEffect.setVector4(name, vector);
  35719. };
  35720. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35721. vector.toArray(UniformBuffer._tempBuffer);
  35722. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35723. };
  35724. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35725. if (suffix === void 0) { suffix = ""; }
  35726. this._currentEffect.setColor3(name + suffix, color);
  35727. };
  35728. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35729. if (suffix === void 0) { suffix = ""; }
  35730. color.toArray(UniformBuffer._tempBuffer);
  35731. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35732. };
  35733. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35734. if (suffix === void 0) { suffix = ""; }
  35735. this._currentEffect.setColor4(name + suffix, color, alpha);
  35736. };
  35737. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35738. if (suffix === void 0) { suffix = ""; }
  35739. color.toArray(UniformBuffer._tempBuffer);
  35740. UniformBuffer._tempBuffer[3] = alpha;
  35741. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35742. };
  35743. /**
  35744. * Sets a sampler uniform on the effect.
  35745. * @param {string} name Name of the sampler.
  35746. * @param {Texture} texture
  35747. */
  35748. UniformBuffer.prototype.setTexture = function (name, texture) {
  35749. this._currentEffect.setTexture(name, texture);
  35750. };
  35751. /**
  35752. * Directly updates the value of the uniform in the cache AND on the GPU.
  35753. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35754. * @param {number[]|Float32Array} data Flattened data
  35755. */
  35756. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35757. this.updateUniform(uniformName, data, data.length);
  35758. this.update();
  35759. };
  35760. /**
  35761. * Binds this uniform buffer to an effect.
  35762. * @param {Effect} effect
  35763. * @param {string} name Name of the uniform block in the shader.
  35764. */
  35765. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35766. this._currentEffect = effect;
  35767. if (this._noUBO || !this._buffer) {
  35768. return;
  35769. }
  35770. effect.bindUniformBuffer(this._buffer, name);
  35771. };
  35772. /**
  35773. * Disposes the uniform buffer.
  35774. */
  35775. UniformBuffer.prototype.dispose = function () {
  35776. if (this._noUBO) {
  35777. return;
  35778. }
  35779. var index = this._engine._uniformBuffers.indexOf(this);
  35780. if (index !== -1) {
  35781. this._engine._uniformBuffers.splice(index, 1);
  35782. }
  35783. if (!this._buffer) {
  35784. return;
  35785. }
  35786. if (this._engine._releaseBuffer(this._buffer)) {
  35787. this._buffer = null;
  35788. }
  35789. };
  35790. // Pool for avoiding memory leaks
  35791. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35792. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35793. return UniformBuffer;
  35794. }());
  35795. BABYLON.UniformBuffer = UniformBuffer;
  35796. })(BABYLON || (BABYLON = {}));
  35797. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35798. var BABYLON;
  35799. (function (BABYLON) {
  35800. /**
  35801. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35802. */
  35803. var VertexData = /** @class */ (function () {
  35804. function VertexData() {
  35805. }
  35806. /**
  35807. * Uses the passed data array to set the set the values for the specified kind of data
  35808. * @param data a linear array of floating numbers
  35809. * @param kind the type of data that is being set, eg positions, colors etc
  35810. */
  35811. VertexData.prototype.set = function (data, kind) {
  35812. switch (kind) {
  35813. case BABYLON.VertexBuffer.PositionKind:
  35814. this.positions = data;
  35815. break;
  35816. case BABYLON.VertexBuffer.NormalKind:
  35817. this.normals = data;
  35818. break;
  35819. case BABYLON.VertexBuffer.TangentKind:
  35820. this.tangents = data;
  35821. break;
  35822. case BABYLON.VertexBuffer.UVKind:
  35823. this.uvs = data;
  35824. break;
  35825. case BABYLON.VertexBuffer.UV2Kind:
  35826. this.uvs2 = data;
  35827. break;
  35828. case BABYLON.VertexBuffer.UV3Kind:
  35829. this.uvs3 = data;
  35830. break;
  35831. case BABYLON.VertexBuffer.UV4Kind:
  35832. this.uvs4 = data;
  35833. break;
  35834. case BABYLON.VertexBuffer.UV5Kind:
  35835. this.uvs5 = data;
  35836. break;
  35837. case BABYLON.VertexBuffer.UV6Kind:
  35838. this.uvs6 = data;
  35839. break;
  35840. case BABYLON.VertexBuffer.ColorKind:
  35841. this.colors = data;
  35842. break;
  35843. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35844. this.matricesIndices = data;
  35845. break;
  35846. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35847. this.matricesWeights = data;
  35848. break;
  35849. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35850. this.matricesIndicesExtra = data;
  35851. break;
  35852. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35853. this.matricesWeightsExtra = data;
  35854. break;
  35855. }
  35856. };
  35857. /**
  35858. * Associates the vertexData to the passed Mesh.
  35859. * Sets it as updatable or not (default `false`)
  35860. * @param mesh the mesh the vertexData is applied to
  35861. * @param updatable when used and having the value true allows new data to update the vertexData
  35862. * @returns the VertexData
  35863. */
  35864. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35865. this._applyTo(mesh, updatable);
  35866. return this;
  35867. };
  35868. /**
  35869. * Associates the vertexData to the passed Geometry.
  35870. * Sets it as updatable or not (default `false`)
  35871. * @param geometry the geometry the vertexData is applied to
  35872. * @param updatable when used and having the value true allows new data to update the vertexData
  35873. * @returns VertexData
  35874. */
  35875. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35876. this._applyTo(geometry, updatable);
  35877. return this;
  35878. };
  35879. /**
  35880. * Updates the associated mesh
  35881. * @param mesh the mesh to be updated
  35882. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35883. * @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
  35884. * @returns VertexData
  35885. */
  35886. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35887. this._update(mesh);
  35888. return this;
  35889. };
  35890. /**
  35891. * Updates the associated geometry
  35892. * @param geometry the geometry to be updated
  35893. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35894. * @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
  35895. * @returns VertexData.
  35896. */
  35897. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35898. this._update(geometry);
  35899. return this;
  35900. };
  35901. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35902. if (updatable === void 0) { updatable = false; }
  35903. if (this.positions) {
  35904. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35905. }
  35906. if (this.normals) {
  35907. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35908. }
  35909. if (this.tangents) {
  35910. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35911. }
  35912. if (this.uvs) {
  35913. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35914. }
  35915. if (this.uvs2) {
  35916. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35917. }
  35918. if (this.uvs3) {
  35919. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35920. }
  35921. if (this.uvs4) {
  35922. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35923. }
  35924. if (this.uvs5) {
  35925. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35926. }
  35927. if (this.uvs6) {
  35928. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35929. }
  35930. if (this.colors) {
  35931. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35932. }
  35933. if (this.matricesIndices) {
  35934. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35935. }
  35936. if (this.matricesWeights) {
  35937. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35938. }
  35939. if (this.matricesIndicesExtra) {
  35940. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35941. }
  35942. if (this.matricesWeightsExtra) {
  35943. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35944. }
  35945. if (this.indices) {
  35946. meshOrGeometry.setIndices(this.indices, null, updatable);
  35947. }
  35948. else {
  35949. meshOrGeometry.setIndices([], null);
  35950. }
  35951. return this;
  35952. };
  35953. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35954. if (this.positions) {
  35955. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35956. }
  35957. if (this.normals) {
  35958. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35959. }
  35960. if (this.tangents) {
  35961. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35962. }
  35963. if (this.uvs) {
  35964. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35965. }
  35966. if (this.uvs2) {
  35967. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35968. }
  35969. if (this.uvs3) {
  35970. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35971. }
  35972. if (this.uvs4) {
  35973. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35974. }
  35975. if (this.uvs5) {
  35976. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35977. }
  35978. if (this.uvs6) {
  35979. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35980. }
  35981. if (this.colors) {
  35982. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35983. }
  35984. if (this.matricesIndices) {
  35985. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35986. }
  35987. if (this.matricesWeights) {
  35988. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35989. }
  35990. if (this.matricesIndicesExtra) {
  35991. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35992. }
  35993. if (this.matricesWeightsExtra) {
  35994. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35995. }
  35996. if (this.indices) {
  35997. meshOrGeometry.setIndices(this.indices, null);
  35998. }
  35999. return this;
  36000. };
  36001. /**
  36002. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36003. * @param matrix the transforming matrix
  36004. * @returns the VertexData
  36005. */
  36006. VertexData.prototype.transform = function (matrix) {
  36007. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36008. var transformed = BABYLON.Vector3.Zero();
  36009. var index;
  36010. if (this.positions) {
  36011. var position = BABYLON.Vector3.Zero();
  36012. for (index = 0; index < this.positions.length; index += 3) {
  36013. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36014. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36015. this.positions[index] = transformed.x;
  36016. this.positions[index + 1] = transformed.y;
  36017. this.positions[index + 2] = transformed.z;
  36018. }
  36019. }
  36020. if (this.normals) {
  36021. var normal = BABYLON.Vector3.Zero();
  36022. for (index = 0; index < this.normals.length; index += 3) {
  36023. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36024. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36025. this.normals[index] = transformed.x;
  36026. this.normals[index + 1] = transformed.y;
  36027. this.normals[index + 2] = transformed.z;
  36028. }
  36029. }
  36030. if (this.tangents) {
  36031. var tangent = BABYLON.Vector4.Zero();
  36032. var tangentTransformed = BABYLON.Vector4.Zero();
  36033. for (index = 0; index < this.tangents.length; index += 4) {
  36034. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36035. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36036. this.tangents[index] = tangentTransformed.x;
  36037. this.tangents[index + 1] = tangentTransformed.y;
  36038. this.tangents[index + 2] = tangentTransformed.z;
  36039. this.tangents[index + 3] = tangentTransformed.w;
  36040. }
  36041. }
  36042. if (flip && this.indices) {
  36043. for (index = 0; index < this.indices.length; index += 3) {
  36044. var tmp = this.indices[index + 1];
  36045. this.indices[index + 1] = this.indices[index + 2];
  36046. this.indices[index + 2] = tmp;
  36047. }
  36048. }
  36049. return this;
  36050. };
  36051. /**
  36052. * Merges the passed VertexData into the current one
  36053. * @param other the VertexData to be merged into the current one
  36054. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36055. * @returns the modified VertexData
  36056. */
  36057. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36058. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36059. this._validate();
  36060. other._validate();
  36061. if (!this.normals !== !other.normals ||
  36062. !this.tangents !== !other.tangents ||
  36063. !this.uvs !== !other.uvs ||
  36064. !this.uvs2 !== !other.uvs2 ||
  36065. !this.uvs3 !== !other.uvs3 ||
  36066. !this.uvs4 !== !other.uvs4 ||
  36067. !this.uvs5 !== !other.uvs5 ||
  36068. !this.uvs6 !== !other.uvs6 ||
  36069. !this.colors !== !other.colors ||
  36070. !this.matricesIndices !== !other.matricesIndices ||
  36071. !this.matricesWeights !== !other.matricesWeights ||
  36072. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36073. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36074. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36075. }
  36076. if (other.indices) {
  36077. if (!this.indices) {
  36078. this.indices = [];
  36079. }
  36080. var offset = this.positions ? this.positions.length / 3 : 0;
  36081. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36082. if (isSrcTypedArray) {
  36083. var len = this.indices.length + other.indices.length;
  36084. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36085. temp.set(this.indices);
  36086. var decal = this.indices.length;
  36087. for (var index = 0; index < other.indices.length; index++) {
  36088. temp[decal + index] = other.indices[index] + offset;
  36089. }
  36090. this.indices = temp;
  36091. }
  36092. else {
  36093. for (var index = 0; index < other.indices.length; index++) {
  36094. this.indices.push(other.indices[index] + offset);
  36095. }
  36096. }
  36097. }
  36098. this.positions = this._mergeElement(this.positions, other.positions);
  36099. this.normals = this._mergeElement(this.normals, other.normals);
  36100. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36101. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36102. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36103. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36104. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36105. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36106. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36107. this.colors = this._mergeElement(this.colors, other.colors);
  36108. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36109. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36110. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36111. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36112. return this;
  36113. };
  36114. VertexData.prototype._mergeElement = function (source, other) {
  36115. if (!source) {
  36116. return other;
  36117. }
  36118. if (!other) {
  36119. return source;
  36120. }
  36121. var len = other.length + source.length;
  36122. var isSrcTypedArray = source instanceof Float32Array;
  36123. var isOthTypedArray = other instanceof Float32Array;
  36124. // use non-loop method when the source is Float32Array
  36125. if (isSrcTypedArray) {
  36126. var ret32 = new Float32Array(len);
  36127. ret32.set(source);
  36128. ret32.set(other, source.length);
  36129. return ret32;
  36130. // source is number[], when other is also use concat
  36131. }
  36132. else if (!isOthTypedArray) {
  36133. return source.concat(other);
  36134. // source is a number[], but other is a Float32Array, loop required
  36135. }
  36136. else {
  36137. var ret = source.slice(0); // copy source to a separate array
  36138. for (var i = 0, len = other.length; i < len; i++) {
  36139. ret.push(other[i]);
  36140. }
  36141. return ret;
  36142. }
  36143. };
  36144. VertexData.prototype._validate = function () {
  36145. if (!this.positions) {
  36146. throw new Error("Positions are required");
  36147. }
  36148. var getElementCount = function (kind, values) {
  36149. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36150. if ((values.length % stride) !== 0) {
  36151. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36152. }
  36153. return values.length / stride;
  36154. };
  36155. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36156. var validateElementCount = function (kind, values) {
  36157. var elementCount = getElementCount(kind, values);
  36158. if (elementCount !== positionsElementCount) {
  36159. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36160. }
  36161. };
  36162. if (this.normals)
  36163. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36164. if (this.tangents)
  36165. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36166. if (this.uvs)
  36167. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36168. if (this.uvs2)
  36169. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36170. if (this.uvs3)
  36171. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36172. if (this.uvs4)
  36173. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36174. if (this.uvs5)
  36175. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36176. if (this.uvs6)
  36177. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36178. if (this.colors)
  36179. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36180. if (this.matricesIndices)
  36181. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36182. if (this.matricesWeights)
  36183. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36184. if (this.matricesIndicesExtra)
  36185. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36186. if (this.matricesWeightsExtra)
  36187. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36188. };
  36189. /**
  36190. * Serializes the VertexData
  36191. * @returns a serialized object
  36192. */
  36193. VertexData.prototype.serialize = function () {
  36194. var serializationObject = this.serialize();
  36195. if (this.positions) {
  36196. serializationObject.positions = this.positions;
  36197. }
  36198. if (this.normals) {
  36199. serializationObject.normals = this.normals;
  36200. }
  36201. if (this.tangents) {
  36202. serializationObject.tangents = this.tangents;
  36203. }
  36204. if (this.uvs) {
  36205. serializationObject.uvs = this.uvs;
  36206. }
  36207. if (this.uvs2) {
  36208. serializationObject.uvs2 = this.uvs2;
  36209. }
  36210. if (this.uvs3) {
  36211. serializationObject.uvs3 = this.uvs3;
  36212. }
  36213. if (this.uvs4) {
  36214. serializationObject.uvs4 = this.uvs4;
  36215. }
  36216. if (this.uvs5) {
  36217. serializationObject.uvs5 = this.uvs5;
  36218. }
  36219. if (this.uvs6) {
  36220. serializationObject.uvs6 = this.uvs6;
  36221. }
  36222. if (this.colors) {
  36223. serializationObject.colors = this.colors;
  36224. }
  36225. if (this.matricesIndices) {
  36226. serializationObject.matricesIndices = this.matricesIndices;
  36227. serializationObject.matricesIndices._isExpanded = true;
  36228. }
  36229. if (this.matricesWeights) {
  36230. serializationObject.matricesWeights = this.matricesWeights;
  36231. }
  36232. if (this.matricesIndicesExtra) {
  36233. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36234. serializationObject.matricesIndicesExtra._isExpanded = true;
  36235. }
  36236. if (this.matricesWeightsExtra) {
  36237. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36238. }
  36239. serializationObject.indices = this.indices;
  36240. return serializationObject;
  36241. };
  36242. // Statics
  36243. /**
  36244. * Extracts the vertexData from a mesh
  36245. * @param mesh the mesh from which to extract the VertexData
  36246. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36247. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36248. * @returns the object VertexData associated to the passed mesh
  36249. */
  36250. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36251. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36252. };
  36253. /**
  36254. * Extracts the vertexData from the geometry
  36255. * @param geometry the geometry from which to extract the VertexData
  36256. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36257. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36258. * @returns the object VertexData associated to the passed mesh
  36259. */
  36260. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36261. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36262. };
  36263. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36264. var result = new VertexData();
  36265. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36266. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36267. }
  36268. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36269. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36270. }
  36271. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36272. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36273. }
  36274. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36275. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36276. }
  36277. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36278. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36279. }
  36280. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36281. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36282. }
  36283. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36284. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36285. }
  36286. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36287. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36288. }
  36289. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36290. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36291. }
  36292. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36293. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36294. }
  36295. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36296. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36297. }
  36298. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36299. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36300. }
  36301. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36302. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36303. }
  36304. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36305. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36306. }
  36307. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36308. return result;
  36309. };
  36310. /**
  36311. * Creates the VertexData for a Ribbon
  36312. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36313. * * pathArray array of paths, each of which an array of successive Vector3
  36314. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36315. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36316. * * 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
  36317. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36318. * * 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)
  36319. * * 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)
  36320. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36321. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36322. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36323. * @returns the VertexData of the ribbon
  36324. */
  36325. VertexData.CreateRibbon = function (options) {
  36326. var pathArray = options.pathArray;
  36327. var closeArray = options.closeArray || false;
  36328. var closePath = options.closePath || false;
  36329. var invertUV = options.invertUV || false;
  36330. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36331. var offset = options.offset || defaultOffset;
  36332. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36333. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36334. var customUV = options.uvs;
  36335. var customColors = options.colors;
  36336. var positions = [];
  36337. var indices = [];
  36338. var normals = [];
  36339. var uvs = [];
  36340. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36341. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36342. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36343. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36344. var minlg; // minimal length among all paths from pathArray
  36345. var lg = []; // array of path lengths : nb of vertex per path
  36346. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36347. var p; // path iterator
  36348. var i; // point iterator
  36349. var j; // point iterator
  36350. // if single path in pathArray
  36351. if (pathArray.length < 2) {
  36352. var ar1 = [];
  36353. var ar2 = [];
  36354. for (i = 0; i < pathArray[0].length - offset; i++) {
  36355. ar1.push(pathArray[0][i]);
  36356. ar2.push(pathArray[0][i + offset]);
  36357. }
  36358. pathArray = [ar1, ar2];
  36359. }
  36360. // positions and horizontal distances (u)
  36361. var idc = 0;
  36362. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36363. var path;
  36364. var l;
  36365. minlg = pathArray[0].length;
  36366. var vectlg;
  36367. var dist;
  36368. for (p = 0; p < pathArray.length; p++) {
  36369. uTotalDistance[p] = 0;
  36370. us[p] = [0];
  36371. path = pathArray[p];
  36372. l = path.length;
  36373. minlg = (minlg < l) ? minlg : l;
  36374. j = 0;
  36375. while (j < l) {
  36376. positions.push(path[j].x, path[j].y, path[j].z);
  36377. if (j > 0) {
  36378. vectlg = path[j].subtract(path[j - 1]).length();
  36379. dist = vectlg + uTotalDistance[p];
  36380. us[p].push(dist);
  36381. uTotalDistance[p] = dist;
  36382. }
  36383. j++;
  36384. }
  36385. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36386. j--;
  36387. positions.push(path[0].x, path[0].y, path[0].z);
  36388. vectlg = path[j].subtract(path[0]).length();
  36389. dist = vectlg + uTotalDistance[p];
  36390. us[p].push(dist);
  36391. uTotalDistance[p] = dist;
  36392. }
  36393. lg[p] = l + closePathCorr;
  36394. idx[p] = idc;
  36395. idc += (l + closePathCorr);
  36396. }
  36397. // vertical distances (v)
  36398. var path1;
  36399. var path2;
  36400. var vertex1 = null;
  36401. var vertex2 = null;
  36402. for (i = 0; i < minlg + closePathCorr; i++) {
  36403. vTotalDistance[i] = 0;
  36404. vs[i] = [0];
  36405. for (p = 0; p < pathArray.length - 1; p++) {
  36406. path1 = pathArray[p];
  36407. path2 = pathArray[p + 1];
  36408. if (i === minlg) { // closePath
  36409. vertex1 = path1[0];
  36410. vertex2 = path2[0];
  36411. }
  36412. else {
  36413. vertex1 = path1[i];
  36414. vertex2 = path2[i];
  36415. }
  36416. vectlg = vertex2.subtract(vertex1).length();
  36417. dist = vectlg + vTotalDistance[i];
  36418. vs[i].push(dist);
  36419. vTotalDistance[i] = dist;
  36420. }
  36421. if (closeArray && vertex2 && vertex1) {
  36422. path1 = pathArray[p];
  36423. path2 = pathArray[0];
  36424. if (i === minlg) { // closePath
  36425. vertex2 = path2[0];
  36426. }
  36427. vectlg = vertex2.subtract(vertex1).length();
  36428. dist = vectlg + vTotalDistance[i];
  36429. vTotalDistance[i] = dist;
  36430. }
  36431. }
  36432. // uvs
  36433. var u;
  36434. var v;
  36435. if (customUV) {
  36436. for (p = 0; p < customUV.length; p++) {
  36437. uvs.push(customUV[p].x, customUV[p].y);
  36438. }
  36439. }
  36440. else {
  36441. for (p = 0; p < pathArray.length; p++) {
  36442. for (i = 0; i < minlg + closePathCorr; i++) {
  36443. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36444. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36445. if (invertUV) {
  36446. uvs.push(v, u);
  36447. }
  36448. else {
  36449. uvs.push(u, v);
  36450. }
  36451. }
  36452. }
  36453. }
  36454. // indices
  36455. p = 0; // path index
  36456. var pi = 0; // positions array index
  36457. var l1 = lg[p] - 1; // path1 length
  36458. var l2 = lg[p + 1] - 1; // path2 length
  36459. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36460. var shft = idx[1] - idx[0]; // shift
  36461. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36462. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36463. // 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
  36464. indices.push(pi, pi + shft, pi + 1);
  36465. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36466. pi += 1;
  36467. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36468. p++;
  36469. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36470. shft = idx[0] - idx[p];
  36471. l1 = lg[p] - 1;
  36472. l2 = lg[0] - 1;
  36473. }
  36474. else {
  36475. shft = idx[p + 1] - idx[p];
  36476. l1 = lg[p] - 1;
  36477. l2 = lg[p + 1] - 1;
  36478. }
  36479. pi = idx[p];
  36480. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36481. }
  36482. }
  36483. // normals
  36484. VertexData.ComputeNormals(positions, indices, normals);
  36485. if (closePath) { // update both the first and last vertex normals to their average value
  36486. var indexFirst = 0;
  36487. var indexLast = 0;
  36488. for (p = 0; p < pathArray.length; p++) {
  36489. indexFirst = idx[p] * 3;
  36490. if (p + 1 < pathArray.length) {
  36491. indexLast = (idx[p + 1] - 1) * 3;
  36492. }
  36493. else {
  36494. indexLast = normals.length - 3;
  36495. }
  36496. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36497. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36498. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36499. normals[indexLast] = normals[indexFirst];
  36500. normals[indexLast + 1] = normals[indexFirst + 1];
  36501. normals[indexLast + 2] = normals[indexFirst + 2];
  36502. }
  36503. }
  36504. // sides
  36505. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36506. // Colors
  36507. var colors = null;
  36508. if (customColors) {
  36509. colors = new Float32Array(customColors.length * 4);
  36510. for (var c = 0; c < customColors.length; c++) {
  36511. colors[c * 4] = customColors[c].r;
  36512. colors[c * 4 + 1] = customColors[c].g;
  36513. colors[c * 4 + 2] = customColors[c].b;
  36514. colors[c * 4 + 3] = customColors[c].a;
  36515. }
  36516. }
  36517. // Result
  36518. var vertexData = new VertexData();
  36519. var positions32 = new Float32Array(positions);
  36520. var normals32 = new Float32Array(normals);
  36521. var uvs32 = new Float32Array(uvs);
  36522. vertexData.indices = indices;
  36523. vertexData.positions = positions32;
  36524. vertexData.normals = normals32;
  36525. vertexData.uvs = uvs32;
  36526. if (colors) {
  36527. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36528. }
  36529. if (closePath) {
  36530. vertexData._idx = idx;
  36531. }
  36532. return vertexData;
  36533. };
  36534. /**
  36535. * Creates the VertexData for a box
  36536. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36537. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36538. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36539. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36540. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36541. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36542. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36543. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36544. * * 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)
  36545. * * 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)
  36546. * @returns the VertexData of the box
  36547. */
  36548. VertexData.CreateBox = function (options) {
  36549. var normalsSource = [
  36550. new BABYLON.Vector3(0, 0, 1),
  36551. new BABYLON.Vector3(0, 0, -1),
  36552. new BABYLON.Vector3(1, 0, 0),
  36553. new BABYLON.Vector3(-1, 0, 0),
  36554. new BABYLON.Vector3(0, 1, 0),
  36555. new BABYLON.Vector3(0, -1, 0)
  36556. ];
  36557. var indices = [];
  36558. var positions = [];
  36559. var normals = [];
  36560. var uvs = [];
  36561. var width = options.width || options.size || 1;
  36562. var height = options.height || options.size || 1;
  36563. var depth = options.depth || options.size || 1;
  36564. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36565. var faceUV = options.faceUV || new Array(6);
  36566. var faceColors = options.faceColors;
  36567. var colors = [];
  36568. // default face colors and UV if undefined
  36569. for (var f = 0; f < 6; f++) {
  36570. if (faceUV[f] === undefined) {
  36571. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36572. }
  36573. if (faceColors && faceColors[f] === undefined) {
  36574. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36575. }
  36576. }
  36577. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36578. // Create each face in turn.
  36579. for (var index = 0; index < normalsSource.length; index++) {
  36580. var normal = normalsSource[index];
  36581. // Get two vectors perpendicular to the face normal and to each other.
  36582. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36583. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36584. // Six indices (two triangles) per face.
  36585. var verticesLength = positions.length / 3;
  36586. indices.push(verticesLength);
  36587. indices.push(verticesLength + 1);
  36588. indices.push(verticesLength + 2);
  36589. indices.push(verticesLength);
  36590. indices.push(verticesLength + 2);
  36591. indices.push(verticesLength + 3);
  36592. // Four vertices per face.
  36593. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36594. positions.push(vertex.x, vertex.y, vertex.z);
  36595. normals.push(normal.x, normal.y, normal.z);
  36596. uvs.push(faceUV[index].z, faceUV[index].w);
  36597. if (faceColors) {
  36598. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36599. }
  36600. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36601. positions.push(vertex.x, vertex.y, vertex.z);
  36602. normals.push(normal.x, normal.y, normal.z);
  36603. uvs.push(faceUV[index].x, faceUV[index].w);
  36604. if (faceColors) {
  36605. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36606. }
  36607. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36608. positions.push(vertex.x, vertex.y, vertex.z);
  36609. normals.push(normal.x, normal.y, normal.z);
  36610. uvs.push(faceUV[index].x, faceUV[index].y);
  36611. if (faceColors) {
  36612. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36613. }
  36614. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36615. positions.push(vertex.x, vertex.y, vertex.z);
  36616. normals.push(normal.x, normal.y, normal.z);
  36617. uvs.push(faceUV[index].z, faceUV[index].y);
  36618. if (faceColors) {
  36619. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36620. }
  36621. }
  36622. // sides
  36623. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36624. // Result
  36625. var vertexData = new VertexData();
  36626. vertexData.indices = indices;
  36627. vertexData.positions = positions;
  36628. vertexData.normals = normals;
  36629. vertexData.uvs = uvs;
  36630. if (faceColors) {
  36631. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36632. vertexData.colors = totalColors;
  36633. }
  36634. return vertexData;
  36635. };
  36636. /**
  36637. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36638. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36639. * * segments sets the number of horizontal strips optional, default 32
  36640. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36641. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36642. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36643. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36644. * * 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
  36645. * * 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
  36646. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36647. * * 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)
  36648. * * 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)
  36649. * @returns the VertexData of the ellipsoid
  36650. */
  36651. VertexData.CreateSphere = function (options) {
  36652. var segments = options.segments || 32;
  36653. var diameterX = options.diameterX || options.diameter || 1;
  36654. var diameterY = options.diameterY || options.diameter || 1;
  36655. var diameterZ = options.diameterZ || options.diameter || 1;
  36656. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36657. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36658. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36659. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36660. var totalZRotationSteps = 2 + segments;
  36661. var totalYRotationSteps = 2 * totalZRotationSteps;
  36662. var indices = [];
  36663. var positions = [];
  36664. var normals = [];
  36665. var uvs = [];
  36666. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36667. var normalizedZ = zRotationStep / totalZRotationSteps;
  36668. var angleZ = normalizedZ * Math.PI * slice;
  36669. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36670. var normalizedY = yRotationStep / totalYRotationSteps;
  36671. var angleY = normalizedY * Math.PI * 2 * arc;
  36672. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36673. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36674. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36675. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36676. var vertex = complete.multiply(radius);
  36677. var normal = complete.divide(radius).normalize();
  36678. positions.push(vertex.x, vertex.y, vertex.z);
  36679. normals.push(normal.x, normal.y, normal.z);
  36680. uvs.push(normalizedY, normalizedZ);
  36681. }
  36682. if (zRotationStep > 0) {
  36683. var verticesCount = positions.length / 3;
  36684. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36685. indices.push((firstIndex));
  36686. indices.push((firstIndex + 1));
  36687. indices.push(firstIndex + totalYRotationSteps + 1);
  36688. indices.push((firstIndex + totalYRotationSteps + 1));
  36689. indices.push((firstIndex + 1));
  36690. indices.push((firstIndex + totalYRotationSteps + 2));
  36691. }
  36692. }
  36693. }
  36694. // Sides
  36695. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36696. // Result
  36697. var vertexData = new VertexData();
  36698. vertexData.indices = indices;
  36699. vertexData.positions = positions;
  36700. vertexData.normals = normals;
  36701. vertexData.uvs = uvs;
  36702. return vertexData;
  36703. };
  36704. /**
  36705. * Creates the VertexData for a cylinder, cone or prism
  36706. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36707. * * height sets the height (y direction) of the cylinder, optional, default 2
  36708. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36709. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36710. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36711. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36712. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36713. * * 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
  36714. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36715. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36716. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36717. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36718. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36719. * * 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)
  36720. * * 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)
  36721. * @returns the VertexData of the cylinder, cone or prism
  36722. */
  36723. VertexData.CreateCylinder = function (options) {
  36724. var height = options.height || 2;
  36725. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36726. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36727. var tessellation = options.tessellation || 24;
  36728. var subdivisions = options.subdivisions || 1;
  36729. var hasRings = options.hasRings ? true : false;
  36730. var enclose = options.enclose ? true : false;
  36731. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36732. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36733. var faceUV = options.faceUV || new Array(3);
  36734. var faceColors = options.faceColors;
  36735. // default face colors and UV if undefined
  36736. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36737. var ringNb = (hasRings) ? subdivisions : 1;
  36738. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36739. var f;
  36740. for (f = 0; f < surfaceNb; f++) {
  36741. if (faceColors && faceColors[f] === undefined) {
  36742. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36743. }
  36744. }
  36745. for (f = 0; f < surfaceNb; f++) {
  36746. if (faceUV && faceUV[f] === undefined) {
  36747. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36748. }
  36749. }
  36750. var indices = new Array();
  36751. var positions = new Array();
  36752. var normals = new Array();
  36753. var uvs = new Array();
  36754. var colors = new Array();
  36755. var angle_step = Math.PI * 2 * arc / tessellation;
  36756. var angle;
  36757. var h;
  36758. var radius;
  36759. var tan = (diameterBottom - diameterTop) / 2 / height;
  36760. var ringVertex = BABYLON.Vector3.Zero();
  36761. var ringNormal = BABYLON.Vector3.Zero();
  36762. var ringFirstVertex = BABYLON.Vector3.Zero();
  36763. var ringFirstNormal = BABYLON.Vector3.Zero();
  36764. var quadNormal = BABYLON.Vector3.Zero();
  36765. var Y = BABYLON.Axis.Y;
  36766. // positions, normals, uvs
  36767. var i;
  36768. var j;
  36769. var r;
  36770. var ringIdx = 1;
  36771. var s = 1; // surface index
  36772. var cs = 0;
  36773. var v = 0;
  36774. for (i = 0; i <= subdivisions; i++) {
  36775. h = i / subdivisions;
  36776. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36777. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36778. for (r = 0; r < ringIdx; r++) {
  36779. if (hasRings) {
  36780. s += r;
  36781. }
  36782. if (enclose) {
  36783. s += 2 * r;
  36784. }
  36785. for (j = 0; j <= tessellation; j++) {
  36786. angle = j * angle_step;
  36787. // position
  36788. ringVertex.x = Math.cos(-angle) * radius;
  36789. ringVertex.y = -height / 2 + h * height;
  36790. ringVertex.z = Math.sin(-angle) * radius;
  36791. // normal
  36792. if (diameterTop === 0 && i === subdivisions) {
  36793. // if no top cap, reuse former normals
  36794. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36795. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36796. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36797. }
  36798. else {
  36799. ringNormal.x = ringVertex.x;
  36800. ringNormal.z = ringVertex.z;
  36801. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36802. ringNormal.normalize();
  36803. }
  36804. // keep first ring vertex values for enclose
  36805. if (j === 0) {
  36806. ringFirstVertex.copyFrom(ringVertex);
  36807. ringFirstNormal.copyFrom(ringNormal);
  36808. }
  36809. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36810. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36811. if (hasRings) {
  36812. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36813. }
  36814. else {
  36815. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36816. }
  36817. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36818. if (faceColors) {
  36819. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36820. }
  36821. }
  36822. // if enclose, add four vertices and their dedicated normals
  36823. if (arc !== 1 && enclose) {
  36824. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36825. positions.push(0, ringVertex.y, 0);
  36826. positions.push(0, ringVertex.y, 0);
  36827. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36828. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36829. quadNormal.normalize();
  36830. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36831. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36832. quadNormal.normalize();
  36833. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36834. if (hasRings) {
  36835. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36836. }
  36837. else {
  36838. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36839. }
  36840. uvs.push(faceUV[s + 1].x, v);
  36841. uvs.push(faceUV[s + 1].z, v);
  36842. if (hasRings) {
  36843. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36844. }
  36845. else {
  36846. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36847. }
  36848. uvs.push(faceUV[s + 2].x, v);
  36849. uvs.push(faceUV[s + 2].z, v);
  36850. if (faceColors) {
  36851. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36852. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36853. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36854. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36855. }
  36856. }
  36857. if (cs !== s) {
  36858. cs = s;
  36859. }
  36860. }
  36861. }
  36862. // indices
  36863. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36864. var s;
  36865. i = 0;
  36866. for (s = 0; s < subdivisions; s++) {
  36867. var i0 = 0;
  36868. var i1 = 0;
  36869. var i2 = 0;
  36870. var i3 = 0;
  36871. for (j = 0; j < tessellation; j++) {
  36872. i0 = i * (e + 1) + j;
  36873. i1 = (i + 1) * (e + 1) + j;
  36874. i2 = i * (e + 1) + (j + 1);
  36875. i3 = (i + 1) * (e + 1) + (j + 1);
  36876. indices.push(i0, i1, i2);
  36877. indices.push(i3, i2, i1);
  36878. }
  36879. if (arc !== 1 && enclose) { // if enclose, add two quads
  36880. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36881. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36882. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36883. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36884. }
  36885. i = (hasRings) ? (i + 2) : (i + 1);
  36886. }
  36887. // Caps
  36888. var createCylinderCap = function (isTop) {
  36889. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36890. if (radius === 0) {
  36891. return;
  36892. }
  36893. // Cap positions, normals & uvs
  36894. var angle;
  36895. var circleVector;
  36896. var i;
  36897. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36898. var c = null;
  36899. if (faceColors) {
  36900. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36901. }
  36902. // cap center
  36903. var vbase = positions.length / 3;
  36904. var offset = isTop ? height / 2 : -height / 2;
  36905. var center = new BABYLON.Vector3(0, offset, 0);
  36906. positions.push(center.x, center.y, center.z);
  36907. normals.push(0, isTop ? 1 : -1, 0);
  36908. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36909. if (c) {
  36910. colors.push(c.r, c.g, c.b, c.a);
  36911. }
  36912. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36913. for (i = 0; i <= tessellation; i++) {
  36914. angle = Math.PI * 2 * i * arc / tessellation;
  36915. var cos = Math.cos(-angle);
  36916. var sin = Math.sin(-angle);
  36917. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36918. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36919. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36920. normals.push(0, isTop ? 1 : -1, 0);
  36921. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36922. if (c) {
  36923. colors.push(c.r, c.g, c.b, c.a);
  36924. }
  36925. }
  36926. // Cap indices
  36927. for (i = 0; i < tessellation; i++) {
  36928. if (!isTop) {
  36929. indices.push(vbase);
  36930. indices.push(vbase + (i + 1));
  36931. indices.push(vbase + (i + 2));
  36932. }
  36933. else {
  36934. indices.push(vbase);
  36935. indices.push(vbase + (i + 2));
  36936. indices.push(vbase + (i + 1));
  36937. }
  36938. }
  36939. };
  36940. // add caps to geometry
  36941. createCylinderCap(false);
  36942. createCylinderCap(true);
  36943. // Sides
  36944. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36945. var vertexData = new VertexData();
  36946. vertexData.indices = indices;
  36947. vertexData.positions = positions;
  36948. vertexData.normals = normals;
  36949. vertexData.uvs = uvs;
  36950. if (faceColors) {
  36951. vertexData.colors = colors;
  36952. }
  36953. return vertexData;
  36954. };
  36955. /**
  36956. * Creates the VertexData for a torus
  36957. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36958. * * diameter the diameter of the torus, optional default 1
  36959. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36960. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36961. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36962. * * 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)
  36963. * * 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)
  36964. * @returns the VertexData of the torus
  36965. */
  36966. VertexData.CreateTorus = function (options) {
  36967. var indices = [];
  36968. var positions = [];
  36969. var normals = [];
  36970. var uvs = [];
  36971. var diameter = options.diameter || 1;
  36972. var thickness = options.thickness || 0.5;
  36973. var tessellation = options.tessellation || 16;
  36974. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36975. var stride = tessellation + 1;
  36976. for (var i = 0; i <= tessellation; i++) {
  36977. var u = i / tessellation;
  36978. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36979. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36980. for (var j = 0; j <= tessellation; j++) {
  36981. var v = 1 - j / tessellation;
  36982. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36983. var dx = Math.cos(innerAngle);
  36984. var dy = Math.sin(innerAngle);
  36985. // Create a vertex.
  36986. var normal = new BABYLON.Vector3(dx, dy, 0);
  36987. var position = normal.scale(thickness / 2);
  36988. var textureCoordinate = new BABYLON.Vector2(u, v);
  36989. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36990. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36991. positions.push(position.x, position.y, position.z);
  36992. normals.push(normal.x, normal.y, normal.z);
  36993. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36994. // And create indices for two triangles.
  36995. var nextI = (i + 1) % stride;
  36996. var nextJ = (j + 1) % stride;
  36997. indices.push(i * stride + j);
  36998. indices.push(i * stride + nextJ);
  36999. indices.push(nextI * stride + j);
  37000. indices.push(i * stride + nextJ);
  37001. indices.push(nextI * stride + nextJ);
  37002. indices.push(nextI * stride + j);
  37003. }
  37004. }
  37005. // Sides
  37006. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37007. // Result
  37008. var vertexData = new VertexData();
  37009. vertexData.indices = indices;
  37010. vertexData.positions = positions;
  37011. vertexData.normals = normals;
  37012. vertexData.uvs = uvs;
  37013. return vertexData;
  37014. };
  37015. /**
  37016. * Creates the VertexData of the LineSystem
  37017. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37018. * - lines an array of lines, each line being an array of successive Vector3
  37019. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37020. * @returns the VertexData of the LineSystem
  37021. */
  37022. VertexData.CreateLineSystem = function (options) {
  37023. var indices = [];
  37024. var positions = [];
  37025. var lines = options.lines;
  37026. var colors = options.colors;
  37027. var vertexColors = [];
  37028. var idx = 0;
  37029. for (var l = 0; l < lines.length; l++) {
  37030. var points = lines[l];
  37031. for (var index = 0; index < points.length; index++) {
  37032. positions.push(points[index].x, points[index].y, points[index].z);
  37033. if (colors) {
  37034. var color = colors[l];
  37035. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37036. }
  37037. if (index > 0) {
  37038. indices.push(idx - 1);
  37039. indices.push(idx);
  37040. }
  37041. idx++;
  37042. }
  37043. }
  37044. var vertexData = new VertexData();
  37045. vertexData.indices = indices;
  37046. vertexData.positions = positions;
  37047. if (colors) {
  37048. vertexData.colors = vertexColors;
  37049. }
  37050. return vertexData;
  37051. };
  37052. /**
  37053. * Create the VertexData for a DashedLines
  37054. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37055. * - points an array successive Vector3
  37056. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37057. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37058. * - dashNb the intended total number of dashes, optional, default 200
  37059. * @returns the VertexData for the DashedLines
  37060. */
  37061. VertexData.CreateDashedLines = function (options) {
  37062. var dashSize = options.dashSize || 3;
  37063. var gapSize = options.gapSize || 1;
  37064. var dashNb = options.dashNb || 200;
  37065. var points = options.points;
  37066. var positions = new Array();
  37067. var indices = new Array();
  37068. var curvect = BABYLON.Vector3.Zero();
  37069. var lg = 0;
  37070. var nb = 0;
  37071. var shft = 0;
  37072. var dashshft = 0;
  37073. var curshft = 0;
  37074. var idx = 0;
  37075. var i = 0;
  37076. for (i = 0; i < points.length - 1; i++) {
  37077. points[i + 1].subtractToRef(points[i], curvect);
  37078. lg += curvect.length();
  37079. }
  37080. shft = lg / dashNb;
  37081. dashshft = dashSize * shft / (dashSize + gapSize);
  37082. for (i = 0; i < points.length - 1; i++) {
  37083. points[i + 1].subtractToRef(points[i], curvect);
  37084. nb = Math.floor(curvect.length() / shft);
  37085. curvect.normalize();
  37086. for (var j = 0; j < nb; j++) {
  37087. curshft = shft * j;
  37088. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37089. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37090. indices.push(idx, idx + 1);
  37091. idx += 2;
  37092. }
  37093. }
  37094. // Result
  37095. var vertexData = new VertexData();
  37096. vertexData.positions = positions;
  37097. vertexData.indices = indices;
  37098. return vertexData;
  37099. };
  37100. /**
  37101. * Creates the VertexData for a Ground
  37102. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37103. * - width the width (x direction) of the ground, optional, default 1
  37104. * - height the height (z direction) of the ground, optional, default 1
  37105. * - subdivisions the number of subdivisions per side, optional, default 1
  37106. * @returns the VertexData of the Ground
  37107. */
  37108. VertexData.CreateGround = function (options) {
  37109. var indices = [];
  37110. var positions = [];
  37111. var normals = [];
  37112. var uvs = [];
  37113. var row, col;
  37114. var width = options.width || 1;
  37115. var height = options.height || 1;
  37116. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37117. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37118. for (row = 0; row <= subdivisionsY; row++) {
  37119. for (col = 0; col <= subdivisionsX; col++) {
  37120. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37121. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37122. positions.push(position.x, position.y, position.z);
  37123. normals.push(normal.x, normal.y, normal.z);
  37124. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37125. }
  37126. }
  37127. for (row = 0; row < subdivisionsY; row++) {
  37128. for (col = 0; col < subdivisionsX; col++) {
  37129. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37130. indices.push(col + 1 + row * (subdivisionsX + 1));
  37131. indices.push(col + row * (subdivisionsX + 1));
  37132. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37133. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37134. indices.push(col + row * (subdivisionsX + 1));
  37135. }
  37136. }
  37137. // Result
  37138. var vertexData = new VertexData();
  37139. vertexData.indices = indices;
  37140. vertexData.positions = positions;
  37141. vertexData.normals = normals;
  37142. vertexData.uvs = uvs;
  37143. return vertexData;
  37144. };
  37145. /**
  37146. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37147. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37148. * * xmin the ground minimum X coordinate, optional, default -1
  37149. * * zmin the ground minimum Z coordinate, optional, default -1
  37150. * * xmax the ground maximum X coordinate, optional, default 1
  37151. * * zmax the ground maximum Z coordinate, optional, default 1
  37152. * * 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}
  37153. * * 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}
  37154. * @returns the VertexData of the TiledGround
  37155. */
  37156. VertexData.CreateTiledGround = function (options) {
  37157. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37158. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37159. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37160. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37161. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37162. var precision = options.precision || { w: 1, h: 1 };
  37163. var indices = new Array();
  37164. var positions = new Array();
  37165. var normals = new Array();
  37166. var uvs = new Array();
  37167. var row, col, tileRow, tileCol;
  37168. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37169. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37170. precision.w = (precision.w < 1) ? 1 : precision.w;
  37171. precision.h = (precision.h < 1) ? 1 : precision.h;
  37172. var tileSize = {
  37173. 'w': (xmax - xmin) / subdivisions.w,
  37174. 'h': (zmax - zmin) / subdivisions.h
  37175. };
  37176. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37177. // Indices
  37178. var base = positions.length / 3;
  37179. var rowLength = precision.w + 1;
  37180. for (row = 0; row < precision.h; row++) {
  37181. for (col = 0; col < precision.w; col++) {
  37182. var square = [
  37183. base + col + row * rowLength,
  37184. base + (col + 1) + row * rowLength,
  37185. base + (col + 1) + (row + 1) * rowLength,
  37186. base + col + (row + 1) * rowLength
  37187. ];
  37188. indices.push(square[1]);
  37189. indices.push(square[2]);
  37190. indices.push(square[3]);
  37191. indices.push(square[0]);
  37192. indices.push(square[1]);
  37193. indices.push(square[3]);
  37194. }
  37195. }
  37196. // Position, normals and uvs
  37197. var position = BABYLON.Vector3.Zero();
  37198. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37199. for (row = 0; row <= precision.h; row++) {
  37200. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37201. for (col = 0; col <= precision.w; col++) {
  37202. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37203. position.y = 0;
  37204. positions.push(position.x, position.y, position.z);
  37205. normals.push(normal.x, normal.y, normal.z);
  37206. uvs.push(col / precision.w, row / precision.h);
  37207. }
  37208. }
  37209. }
  37210. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37211. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37212. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37213. }
  37214. }
  37215. // Result
  37216. var vertexData = new VertexData();
  37217. vertexData.indices = indices;
  37218. vertexData.positions = positions;
  37219. vertexData.normals = normals;
  37220. vertexData.uvs = uvs;
  37221. return vertexData;
  37222. };
  37223. /**
  37224. * Creates the VertexData of the Ground designed from a heightmap
  37225. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37226. * * width the width (x direction) of the ground
  37227. * * height the height (z direction) of the ground
  37228. * * subdivisions the number of subdivisions per side
  37229. * * minHeight the minimum altitude on the ground, optional, default 0
  37230. * * maxHeight the maximum altitude on the ground, optional default 1
  37231. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37232. * * buffer the array holding the image color data
  37233. * * bufferWidth the width of image
  37234. * * bufferHeight the height of image
  37235. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37236. * @returns the VertexData of the Ground designed from a heightmap
  37237. */
  37238. VertexData.CreateGroundFromHeightMap = function (options) {
  37239. var indices = [];
  37240. var positions = [];
  37241. var normals = [];
  37242. var uvs = [];
  37243. var row, col;
  37244. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37245. var alphaFilter = options.alphaFilter || 0.0;
  37246. // Vertices
  37247. for (row = 0; row <= options.subdivisions; row++) {
  37248. for (col = 0; col <= options.subdivisions; col++) {
  37249. 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));
  37250. // Compute height
  37251. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37252. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37253. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37254. var r = options.buffer[pos] / 255.0;
  37255. var g = options.buffer[pos + 1] / 255.0;
  37256. var b = options.buffer[pos + 2] / 255.0;
  37257. var a = options.buffer[pos + 3] / 255.0;
  37258. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37259. // If our alpha channel is not within our filter then we will assign a 'special' height
  37260. // Then when building the indices, we will ignore any vertex that is using the special height
  37261. if (a >= alphaFilter)
  37262. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37263. else {
  37264. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37265. }
  37266. // Add vertex
  37267. positions.push(position.x, position.y, position.z);
  37268. normals.push(0, 0, 0);
  37269. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37270. }
  37271. }
  37272. // Indices
  37273. for (row = 0; row < options.subdivisions; row++) {
  37274. for (col = 0; col < options.subdivisions; col++) {
  37275. // Calculate Indices
  37276. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37277. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37278. var idx3 = (col + row * (options.subdivisions + 1));
  37279. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37280. // Check that all indices are visible (based on our special height)
  37281. // Only display the vertex if all Indices are visible
  37282. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37283. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37284. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37285. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37286. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37287. indices.push(idx1);
  37288. indices.push(idx2);
  37289. indices.push(idx3);
  37290. }
  37291. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37292. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37293. indices.push(idx4);
  37294. indices.push(idx1);
  37295. indices.push(idx3);
  37296. }
  37297. }
  37298. }
  37299. // Normals
  37300. VertexData.ComputeNormals(positions, indices, normals);
  37301. // Result
  37302. var vertexData = new VertexData();
  37303. vertexData.indices = indices;
  37304. vertexData.positions = positions;
  37305. vertexData.normals = normals;
  37306. vertexData.uvs = uvs;
  37307. return vertexData;
  37308. };
  37309. /**
  37310. * Creates the VertexData for a Plane
  37311. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37312. * * size sets the width and height of the plane to the value of size, optional default 1
  37313. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37314. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37315. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37316. * * 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)
  37317. * * 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)
  37318. * @returns the VertexData of the box
  37319. */
  37320. VertexData.CreatePlane = function (options) {
  37321. var indices = [];
  37322. var positions = [];
  37323. var normals = [];
  37324. var uvs = [];
  37325. var width = options.width || options.size || 1;
  37326. var height = options.height || options.size || 1;
  37327. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37328. // Vertices
  37329. var halfWidth = width / 2.0;
  37330. var halfHeight = height / 2.0;
  37331. positions.push(-halfWidth, -halfHeight, 0);
  37332. normals.push(0, 0, -1.0);
  37333. uvs.push(0.0, 0.0);
  37334. positions.push(halfWidth, -halfHeight, 0);
  37335. normals.push(0, 0, -1.0);
  37336. uvs.push(1.0, 0.0);
  37337. positions.push(halfWidth, halfHeight, 0);
  37338. normals.push(0, 0, -1.0);
  37339. uvs.push(1.0, 1.0);
  37340. positions.push(-halfWidth, halfHeight, 0);
  37341. normals.push(0, 0, -1.0);
  37342. uvs.push(0.0, 1.0);
  37343. // Indices
  37344. indices.push(0);
  37345. indices.push(1);
  37346. indices.push(2);
  37347. indices.push(0);
  37348. indices.push(2);
  37349. indices.push(3);
  37350. // Sides
  37351. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37352. // Result
  37353. var vertexData = new VertexData();
  37354. vertexData.indices = indices;
  37355. vertexData.positions = positions;
  37356. vertexData.normals = normals;
  37357. vertexData.uvs = uvs;
  37358. return vertexData;
  37359. };
  37360. /**
  37361. * Creates the VertexData of the Disc or regular Polygon
  37362. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37363. * * radius the radius of the disc, optional default 0.5
  37364. * * tessellation the number of polygon sides, optional, default 64
  37365. * * 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
  37366. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37367. * * 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)
  37368. * * 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)
  37369. * @returns the VertexData of the box
  37370. */
  37371. VertexData.CreateDisc = function (options) {
  37372. var positions = new Array();
  37373. var indices = new Array();
  37374. var normals = new Array();
  37375. var uvs = new Array();
  37376. var radius = options.radius || 0.5;
  37377. var tessellation = options.tessellation || 64;
  37378. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37379. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37380. // positions and uvs
  37381. positions.push(0, 0, 0); // disc center first
  37382. uvs.push(0.5, 0.5);
  37383. var theta = Math.PI * 2 * arc;
  37384. var step = theta / tessellation;
  37385. for (var a = 0; a < theta; a += step) {
  37386. var x = Math.cos(a);
  37387. var y = Math.sin(a);
  37388. var u = (x + 1) / 2;
  37389. var v = (1 - y) / 2;
  37390. positions.push(radius * x, radius * y, 0);
  37391. uvs.push(u, v);
  37392. }
  37393. if (arc === 1) {
  37394. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37395. uvs.push(uvs[2], uvs[3]);
  37396. }
  37397. //indices
  37398. var vertexNb = positions.length / 3;
  37399. for (var i = 1; i < vertexNb - 1; i++) {
  37400. indices.push(i + 1, 0, i);
  37401. }
  37402. // result
  37403. VertexData.ComputeNormals(positions, indices, normals);
  37404. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37405. var vertexData = new VertexData();
  37406. vertexData.indices = indices;
  37407. vertexData.positions = positions;
  37408. vertexData.normals = normals;
  37409. vertexData.uvs = uvs;
  37410. return vertexData;
  37411. };
  37412. /**
  37413. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37414. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37415. * @param polygon a mesh built from polygonTriangulation.build()
  37416. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37417. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37418. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37419. * @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)
  37420. * @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)
  37421. * @returns the VertexData of the Polygon
  37422. */
  37423. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37424. var faceUV = fUV || new Array(3);
  37425. var faceColors = fColors;
  37426. var colors = [];
  37427. // default face colors and UV if undefined
  37428. for (var f = 0; f < 3; f++) {
  37429. if (faceUV[f] === undefined) {
  37430. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37431. }
  37432. if (faceColors && faceColors[f] === undefined) {
  37433. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37434. }
  37435. }
  37436. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37437. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37438. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37439. var indices = polygon.getIndices();
  37440. // set face colours and textures
  37441. var idx = 0;
  37442. var face = 0;
  37443. for (var index = 0; index < normals.length; index += 3) {
  37444. //Edge Face no. 1
  37445. if (Math.abs(normals[index + 1]) < 0.001) {
  37446. face = 1;
  37447. }
  37448. //Top Face no. 0
  37449. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37450. face = 0;
  37451. }
  37452. //Bottom Face no. 2
  37453. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37454. face = 2;
  37455. }
  37456. idx = index / 3;
  37457. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37458. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37459. if (faceColors) {
  37460. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37461. }
  37462. }
  37463. // sides
  37464. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37465. // Result
  37466. var vertexData = new VertexData();
  37467. vertexData.indices = indices;
  37468. vertexData.positions = positions;
  37469. vertexData.normals = normals;
  37470. vertexData.uvs = uvs;
  37471. if (faceColors) {
  37472. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37473. vertexData.colors = totalColors;
  37474. }
  37475. return vertexData;
  37476. };
  37477. /**
  37478. * Creates the VertexData of the IcoSphere
  37479. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37480. * * radius the radius of the IcoSphere, optional default 1
  37481. * * radiusX allows stretching in the x direction, optional, default radius
  37482. * * radiusY allows stretching in the y direction, optional, default radius
  37483. * * radiusZ allows stretching in the z direction, optional, default radius
  37484. * * flat when true creates a flat shaded mesh, optional, default true
  37485. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37486. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37487. * * 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)
  37488. * * 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)
  37489. * @returns the VertexData of the IcoSphere
  37490. */
  37491. VertexData.CreateIcoSphere = function (options) {
  37492. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37493. var radius = options.radius || 1;
  37494. var flat = (options.flat === undefined) ? true : options.flat;
  37495. var subdivisions = options.subdivisions || 4;
  37496. var radiusX = options.radiusX || radius;
  37497. var radiusY = options.radiusY || radius;
  37498. var radiusZ = options.radiusZ || radius;
  37499. var t = (1 + Math.sqrt(5)) / 2;
  37500. // 12 vertex x,y,z
  37501. var ico_vertices = [
  37502. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37503. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37504. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37505. ];
  37506. // index of 3 vertex makes a face of icopshere
  37507. var ico_indices = [
  37508. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37509. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37510. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37511. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37512. ];
  37513. // vertex for uv have aliased position, not for UV
  37514. var vertices_unalias_id = [
  37515. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37516. // vertex alias
  37517. 0,
  37518. 2,
  37519. 3,
  37520. 3,
  37521. 3,
  37522. 4,
  37523. 7,
  37524. 8,
  37525. 9,
  37526. 9,
  37527. 10,
  37528. 11 // 23: B + 12
  37529. ];
  37530. // uv as integer step (not pixels !)
  37531. var ico_vertexuv = [
  37532. 5, 1, 3, 1, 6, 4, 0, 0,
  37533. 5, 3, 4, 2, 2, 2, 4, 0,
  37534. 2, 0, 1, 1, 6, 0, 6, 2,
  37535. // vertex alias (for same vertex on different faces)
  37536. 0, 4,
  37537. 3, 3,
  37538. 4, 4,
  37539. 3, 1,
  37540. 4, 2,
  37541. 4, 4,
  37542. 0, 2,
  37543. 1, 1,
  37544. 2, 2,
  37545. 3, 3,
  37546. 1, 3,
  37547. 2, 4 // 23: B + 12
  37548. ];
  37549. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37550. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37551. // First island of uv mapping
  37552. // v = 4h 3+ 2
  37553. // v = 3h 9+ 4
  37554. // v = 2h 9+ 5 B
  37555. // v = 1h 9 1 0
  37556. // v = 0h 3 8 7 A
  37557. // u = 0 1 2 3 4 5 6 *a
  37558. // Second island of uv mapping
  37559. // v = 4h 0+ B+ 4+
  37560. // v = 3h A+ 2+
  37561. // v = 2h 7+ 6 3+
  37562. // v = 1h 8+ 3+
  37563. // v = 0h
  37564. // u = 0 1 2 3 4 5 6 *a
  37565. // Face layout on texture UV mapping
  37566. // ============
  37567. // \ 4 /\ 16 / ======
  37568. // \ / \ / /\ 11 /
  37569. // \/ 7 \/ / \ /
  37570. // ======= / 10 \/
  37571. // /\ 17 /\ =======
  37572. // / \ / \ \ 15 /\
  37573. // / 8 \/ 12 \ \ / \
  37574. // ============ \/ 6 \
  37575. // \ 18 /\ ============
  37576. // \ / \ \ 5 /\ 0 /
  37577. // \/ 13 \ \ / \ /
  37578. // ======= \/ 1 \/
  37579. // =============
  37580. // /\ 19 /\ 2 /\
  37581. // / \ / \ / \
  37582. // / 14 \/ 9 \/ 3 \
  37583. // ===================
  37584. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37585. var ustep = 138 / 1024;
  37586. var vstep = 239 / 1024;
  37587. var uoffset = 60 / 1024;
  37588. var voffset = 26 / 1024;
  37589. // Second island should have margin, not to touch the first island
  37590. // avoid any borderline artefact in pixel rounding
  37591. var island_u_offset = -40 / 1024;
  37592. var island_v_offset = +20 / 1024;
  37593. // face is either island 0 or 1 :
  37594. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37595. var island = [
  37596. 0, 0, 0, 0, 1,
  37597. 0, 0, 1, 1, 0,
  37598. 0, 0, 1, 1, 0,
  37599. 0, 1, 1, 1, 0 // 15 - 19
  37600. ];
  37601. var indices = new Array();
  37602. var positions = new Array();
  37603. var normals = new Array();
  37604. var uvs = new Array();
  37605. var current_indice = 0;
  37606. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37607. var face_vertex_pos = new Array(3);
  37608. var face_vertex_uv = new Array(3);
  37609. var v012;
  37610. for (v012 = 0; v012 < 3; v012++) {
  37611. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37612. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37613. }
  37614. // create all with normals
  37615. for (var face = 0; face < 20; face++) {
  37616. // 3 vertex per face
  37617. for (v012 = 0; v012 < 3; v012++) {
  37618. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37619. var v_id = ico_indices[3 * face + v012];
  37620. // vertex have 3D position (x,y,z)
  37621. 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]);
  37622. // Normalize to get normal, then scale to radius
  37623. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37624. // uv Coordinates from vertex ID
  37625. 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);
  37626. }
  37627. // Subdivide the face (interpolate pos, norm, uv)
  37628. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37629. // - norm is linear interpolation of vertex corner normal
  37630. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37631. // - uv is linear interpolation
  37632. //
  37633. // Topology is as below for sub-divide by 2
  37634. // vertex shown as v0,v1,v2
  37635. // interp index is i1 to progress in range [v0,v1[
  37636. // interp index is i2 to progress in range [v0,v2[
  37637. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37638. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37639. //
  37640. //
  37641. // i2 v2
  37642. // ^ ^
  37643. // / / \
  37644. // / / \
  37645. // / / \
  37646. // / / (0,1) \
  37647. // / #---------\
  37648. // / / \ (0,0)'/ \
  37649. // / / \ / \
  37650. // / / \ / \
  37651. // / / (0,0) \ / (1,0) \
  37652. // / #---------#---------\
  37653. // v0 v1
  37654. //
  37655. // --------------------> i1
  37656. //
  37657. // interp of (i1,i2):
  37658. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37659. // along i1 : lerp(x0,x1, i1/(S-i2))
  37660. //
  37661. // centroid of triangle is needed to get help normal computation
  37662. // (c1,c2) are used for centroid location
  37663. var interp_vertex = function (i1, i2, c1, c2) {
  37664. // vertex is interpolated from
  37665. // - face_vertex_pos[0..2]
  37666. // - face_vertex_uv[0..2]
  37667. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37668. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37669. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37670. pos_interp.normalize();
  37671. var vertex_normal;
  37672. if (flat) {
  37673. // in flat mode, recalculate normal as face centroid normal
  37674. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37675. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37676. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37677. }
  37678. else {
  37679. // in smooth mode, recalculate normal from each single vertex position
  37680. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37681. }
  37682. // Vertex normal need correction due to X,Y,Z radius scaling
  37683. vertex_normal.x /= radiusX;
  37684. vertex_normal.y /= radiusY;
  37685. vertex_normal.z /= radiusZ;
  37686. vertex_normal.normalize();
  37687. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37688. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37689. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37690. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37691. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37692. uvs.push(uv_interp.x, uv_interp.y);
  37693. // push each vertex has member of a face
  37694. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37695. indices.push(current_indice);
  37696. current_indice++;
  37697. };
  37698. for (var i2 = 0; i2 < subdivisions; i2++) {
  37699. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37700. // face : (i1,i2) for /\ :
  37701. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37702. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37703. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37704. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37705. if (i1 + i2 + 1 < subdivisions) {
  37706. // face : (i1,i2)' for \/ :
  37707. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37708. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37709. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37710. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37711. }
  37712. }
  37713. }
  37714. }
  37715. // Sides
  37716. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37717. // Result
  37718. var vertexData = new VertexData();
  37719. vertexData.indices = indices;
  37720. vertexData.positions = positions;
  37721. vertexData.normals = normals;
  37722. vertexData.uvs = uvs;
  37723. return vertexData;
  37724. };
  37725. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37726. /**
  37727. * Creates the VertexData for a Polyhedron
  37728. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37729. * * type provided types are:
  37730. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37731. * * 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)
  37732. * * size the size of the IcoSphere, optional default 1
  37733. * * sizeX allows stretching in the x direction, optional, default size
  37734. * * sizeY allows stretching in the y direction, optional, default size
  37735. * * sizeZ allows stretching in the z direction, optional, default size
  37736. * * 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
  37737. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37738. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37739. * * flat when true creates a flat shaded mesh, optional, default true
  37740. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37741. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37742. * * 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)
  37743. * * 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)
  37744. * @returns the VertexData of the Polyhedron
  37745. */
  37746. VertexData.CreatePolyhedron = function (options) {
  37747. // provided polyhedron types :
  37748. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37749. // 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)
  37750. var polyhedra = [];
  37751. 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]] };
  37752. 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]] };
  37753. polyhedra[2] = {
  37754. 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]],
  37755. 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]]
  37756. };
  37757. polyhedra[3] = {
  37758. 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]],
  37759. 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]]
  37760. };
  37761. polyhedra[4] = {
  37762. 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]],
  37763. 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]]
  37764. };
  37765. 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]] };
  37766. 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]] };
  37767. 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]] };
  37768. 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]] };
  37769. 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]] };
  37770. 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]] };
  37771. 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]] };
  37772. 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]] };
  37773. 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]] };
  37774. polyhedra[14] = {
  37775. 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]],
  37776. 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]]
  37777. };
  37778. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37779. var size = options.size;
  37780. var sizeX = options.sizeX || size || 1;
  37781. var sizeY = options.sizeY || size || 1;
  37782. var sizeZ = options.sizeZ || size || 1;
  37783. var data = options.custom || polyhedra[type];
  37784. var nbfaces = data.face.length;
  37785. var faceUV = options.faceUV || new Array(nbfaces);
  37786. var faceColors = options.faceColors;
  37787. var flat = (options.flat === undefined) ? true : options.flat;
  37788. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37789. var positions = new Array();
  37790. var indices = new Array();
  37791. var normals = new Array();
  37792. var uvs = new Array();
  37793. var colors = new Array();
  37794. var index = 0;
  37795. var faceIdx = 0; // face cursor in the array "indexes"
  37796. var indexes = new Array();
  37797. var i = 0;
  37798. var f = 0;
  37799. var u, v, ang, x, y, tmp;
  37800. // default face colors and UV if undefined
  37801. if (flat) {
  37802. for (f = 0; f < nbfaces; f++) {
  37803. if (faceColors && faceColors[f] === undefined) {
  37804. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37805. }
  37806. if (faceUV && faceUV[f] === undefined) {
  37807. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37808. }
  37809. }
  37810. }
  37811. if (!flat) {
  37812. for (i = 0; i < data.vertex.length; i++) {
  37813. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37814. uvs.push(0, 0);
  37815. }
  37816. for (f = 0; f < nbfaces; f++) {
  37817. for (i = 0; i < data.face[f].length - 2; i++) {
  37818. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37819. }
  37820. }
  37821. }
  37822. else {
  37823. for (f = 0; f < nbfaces; f++) {
  37824. var fl = data.face[f].length; // number of vertices of the current face
  37825. ang = 2 * Math.PI / fl;
  37826. x = 0.5 * Math.tan(ang / 2);
  37827. y = 0.5;
  37828. // positions, uvs, colors
  37829. for (i = 0; i < fl; i++) {
  37830. // positions
  37831. 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);
  37832. indexes.push(index);
  37833. index++;
  37834. // uvs
  37835. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37836. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37837. uvs.push(u, v);
  37838. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37839. y = x * Math.sin(ang) + y * Math.cos(ang);
  37840. x = tmp;
  37841. // colors
  37842. if (faceColors) {
  37843. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37844. }
  37845. }
  37846. // indices from indexes
  37847. for (i = 0; i < fl - 2; i++) {
  37848. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37849. }
  37850. faceIdx += fl;
  37851. }
  37852. }
  37853. VertexData.ComputeNormals(positions, indices, normals);
  37854. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37855. var vertexData = new VertexData();
  37856. vertexData.positions = positions;
  37857. vertexData.indices = indices;
  37858. vertexData.normals = normals;
  37859. vertexData.uvs = uvs;
  37860. if (faceColors && flat) {
  37861. vertexData.colors = colors;
  37862. }
  37863. return vertexData;
  37864. };
  37865. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37866. /**
  37867. * Creates the VertexData for a TorusKnot
  37868. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37869. * * radius the radius of the torus knot, optional, default 2
  37870. * * tube the thickness of the tube, optional, default 0.5
  37871. * * radialSegments the number of sides on each tube segments, optional, default 32
  37872. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37873. * * p the number of windings around the z axis, optional, default 2
  37874. * * q the number of windings around the x axis, optional, default 3
  37875. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37876. * * 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)
  37877. * * 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)
  37878. * @returns the VertexData of the Torus Knot
  37879. */
  37880. VertexData.CreateTorusKnot = function (options) {
  37881. var indices = new Array();
  37882. var positions = new Array();
  37883. var normals = new Array();
  37884. var uvs = new Array();
  37885. var radius = options.radius || 2;
  37886. var tube = options.tube || 0.5;
  37887. var radialSegments = options.radialSegments || 32;
  37888. var tubularSegments = options.tubularSegments || 32;
  37889. var p = options.p || 2;
  37890. var q = options.q || 3;
  37891. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37892. // Helper
  37893. var getPos = function (angle) {
  37894. var cu = Math.cos(angle);
  37895. var su = Math.sin(angle);
  37896. var quOverP = q / p * angle;
  37897. var cs = Math.cos(quOverP);
  37898. var tx = radius * (2 + cs) * 0.5 * cu;
  37899. var ty = radius * (2 + cs) * su * 0.5;
  37900. var tz = radius * Math.sin(quOverP) * 0.5;
  37901. return new BABYLON.Vector3(tx, ty, tz);
  37902. };
  37903. // Vertices
  37904. var i;
  37905. var j;
  37906. for (i = 0; i <= radialSegments; i++) {
  37907. var modI = i % radialSegments;
  37908. var u = modI / radialSegments * 2 * p * Math.PI;
  37909. var p1 = getPos(u);
  37910. var p2 = getPos(u + 0.01);
  37911. var tang = p2.subtract(p1);
  37912. var n = p2.add(p1);
  37913. var bitan = BABYLON.Vector3.Cross(tang, n);
  37914. n = BABYLON.Vector3.Cross(bitan, tang);
  37915. bitan.normalize();
  37916. n.normalize();
  37917. for (j = 0; j < tubularSegments; j++) {
  37918. var modJ = j % tubularSegments;
  37919. var v = modJ / tubularSegments * 2 * Math.PI;
  37920. var cx = -tube * Math.cos(v);
  37921. var cy = tube * Math.sin(v);
  37922. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37923. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37924. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37925. uvs.push(i / radialSegments);
  37926. uvs.push(j / tubularSegments);
  37927. }
  37928. }
  37929. for (i = 0; i < radialSegments; i++) {
  37930. for (j = 0; j < tubularSegments; j++) {
  37931. var jNext = (j + 1) % tubularSegments;
  37932. var a = i * tubularSegments + j;
  37933. var b = (i + 1) * tubularSegments + j;
  37934. var c = (i + 1) * tubularSegments + jNext;
  37935. var d = i * tubularSegments + jNext;
  37936. indices.push(d);
  37937. indices.push(b);
  37938. indices.push(a);
  37939. indices.push(d);
  37940. indices.push(c);
  37941. indices.push(b);
  37942. }
  37943. }
  37944. // Normals
  37945. VertexData.ComputeNormals(positions, indices, normals);
  37946. // Sides
  37947. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.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. return vertexData;
  37955. };
  37956. // Tools
  37957. /**
  37958. * Compute normals for given positions and indices
  37959. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37960. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37961. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37962. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37963. * * facetNormals : optional array of facet normals (vector3)
  37964. * * facetPositions : optional array of facet positions (vector3)
  37965. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37966. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37967. * * bInfo : optional bounding info, required for facetPartitioning computation
  37968. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37969. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37970. * * useRightHandedSystem: optional boolean to for right handed system computation
  37971. * * depthSort : optional boolean to enable the facet depth sort computation
  37972. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37973. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37974. */
  37975. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37976. // temporary scalar variables
  37977. var index = 0; // facet index
  37978. var p1p2x = 0.0; // p1p2 vector x coordinate
  37979. var p1p2y = 0.0; // p1p2 vector y coordinate
  37980. var p1p2z = 0.0; // p1p2 vector z coordinate
  37981. var p3p2x = 0.0; // p3p2 vector x coordinate
  37982. var p3p2y = 0.0; // p3p2 vector y coordinate
  37983. var p3p2z = 0.0; // p3p2 vector z coordinate
  37984. var faceNormalx = 0.0; // facet normal x coordinate
  37985. var faceNormaly = 0.0; // facet normal y coordinate
  37986. var faceNormalz = 0.0; // facet normal z coordinate
  37987. var length = 0.0; // facet normal length before normalization
  37988. var v1x = 0; // vector1 x index in the positions array
  37989. var v1y = 0; // vector1 y index in the positions array
  37990. var v1z = 0; // vector1 z index in the positions array
  37991. var v2x = 0; // vector2 x index in the positions array
  37992. var v2y = 0; // vector2 y index in the positions array
  37993. var v2z = 0; // vector2 z index in the positions array
  37994. var v3x = 0; // vector3 x index in the positions array
  37995. var v3y = 0; // vector3 y index in the positions array
  37996. var v3z = 0; // vector3 z index in the positions array
  37997. var computeFacetNormals = false;
  37998. var computeFacetPositions = false;
  37999. var computeFacetPartitioning = false;
  38000. var computeDepthSort = false;
  38001. var faceNormalSign = 1;
  38002. var ratio = 0;
  38003. var distanceTo = null;
  38004. if (options) {
  38005. computeFacetNormals = (options.facetNormals) ? true : false;
  38006. computeFacetPositions = (options.facetPositions) ? true : false;
  38007. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38008. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38009. ratio = options.ratio || 0;
  38010. computeDepthSort = (options.depthSort) ? true : false;
  38011. distanceTo = (options.distanceTo);
  38012. if (computeDepthSort) {
  38013. if (distanceTo === undefined) {
  38014. distanceTo = BABYLON.Vector3.Zero();
  38015. }
  38016. var depthSortedFacets = options.depthSortedFacets;
  38017. }
  38018. }
  38019. // facetPartitioning reinit if needed
  38020. var xSubRatio = 0;
  38021. var ySubRatio = 0;
  38022. var zSubRatio = 0;
  38023. var subSq = 0;
  38024. if (computeFacetPartitioning && options && options.bbSize) {
  38025. var ox = 0; // X partitioning index for facet position
  38026. var oy = 0; // Y partinioning index for facet position
  38027. var oz = 0; // Z partinioning index for facet position
  38028. var b1x = 0; // X partitioning index for facet v1 vertex
  38029. var b1y = 0; // Y partitioning index for facet v1 vertex
  38030. var b1z = 0; // z partitioning index for facet v1 vertex
  38031. var b2x = 0; // X partitioning index for facet v2 vertex
  38032. var b2y = 0; // Y partitioning index for facet v2 vertex
  38033. var b2z = 0; // Z partitioning index for facet v2 vertex
  38034. var b3x = 0; // X partitioning index for facet v3 vertex
  38035. var b3y = 0; // Y partitioning index for facet v3 vertex
  38036. var b3z = 0; // Z partitioning index for facet v3 vertex
  38037. var block_idx_o = 0; // facet barycenter block index
  38038. var block_idx_v1 = 0; // v1 vertex block index
  38039. var block_idx_v2 = 0; // v2 vertex block index
  38040. var block_idx_v3 = 0; // v3 vertex block index
  38041. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38042. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38043. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38044. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38045. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38046. subSq = options.subDiv.max * options.subDiv.max;
  38047. options.facetPartitioning.length = 0;
  38048. }
  38049. // reset the normals
  38050. for (index = 0; index < positions.length; index++) {
  38051. normals[index] = 0.0;
  38052. }
  38053. // Loop : 1 indice triplet = 1 facet
  38054. var nbFaces = (indices.length / 3) | 0;
  38055. for (index = 0; index < nbFaces; index++) {
  38056. // get the indexes of the coordinates of each vertex of the facet
  38057. v1x = indices[index * 3] * 3;
  38058. v1y = v1x + 1;
  38059. v1z = v1x + 2;
  38060. v2x = indices[index * 3 + 1] * 3;
  38061. v2y = v2x + 1;
  38062. v2z = v2x + 2;
  38063. v3x = indices[index * 3 + 2] * 3;
  38064. v3y = v3x + 1;
  38065. v3z = v3x + 2;
  38066. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38067. p1p2y = positions[v1y] - positions[v2y];
  38068. p1p2z = positions[v1z] - positions[v2z];
  38069. p3p2x = positions[v3x] - positions[v2x];
  38070. p3p2y = positions[v3y] - positions[v2y];
  38071. p3p2z = positions[v3z] - positions[v2z];
  38072. // compute the face normal with the cross product
  38073. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38074. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38075. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38076. // normalize this normal and store it in the array facetData
  38077. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38078. length = (length === 0) ? 1.0 : length;
  38079. faceNormalx /= length;
  38080. faceNormaly /= length;
  38081. faceNormalz /= length;
  38082. if (computeFacetNormals && options) {
  38083. options.facetNormals[index].x = faceNormalx;
  38084. options.facetNormals[index].y = faceNormaly;
  38085. options.facetNormals[index].z = faceNormalz;
  38086. }
  38087. if (computeFacetPositions && options) {
  38088. // compute and the facet barycenter coordinates in the array facetPositions
  38089. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38090. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38091. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38092. }
  38093. if (computeFacetPartitioning && options) {
  38094. // store the facet indexes in arrays in the main facetPartitioning array :
  38095. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38096. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38097. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38098. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38099. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38100. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38101. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38102. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38103. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38104. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38105. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38106. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38107. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38108. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38109. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38110. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38111. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38112. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38113. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38114. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38115. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38116. // push each facet index in each block containing the vertex
  38117. options.facetPartitioning[block_idx_v1].push(index);
  38118. if (block_idx_v2 != block_idx_v1) {
  38119. options.facetPartitioning[block_idx_v2].push(index);
  38120. }
  38121. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38122. options.facetPartitioning[block_idx_v3].push(index);
  38123. }
  38124. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38125. options.facetPartitioning[block_idx_o].push(index);
  38126. }
  38127. }
  38128. if (computeDepthSort && options && options.facetPositions) {
  38129. var dsf = depthSortedFacets[index];
  38130. dsf.ind = index * 3;
  38131. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38132. }
  38133. // compute the normals anyway
  38134. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38135. normals[v1y] += faceNormaly;
  38136. normals[v1z] += faceNormalz;
  38137. normals[v2x] += faceNormalx;
  38138. normals[v2y] += faceNormaly;
  38139. normals[v2z] += faceNormalz;
  38140. normals[v3x] += faceNormalx;
  38141. normals[v3y] += faceNormaly;
  38142. normals[v3z] += faceNormalz;
  38143. }
  38144. // last normalization of each normal
  38145. for (index = 0; index < normals.length / 3; index++) {
  38146. faceNormalx = normals[index * 3];
  38147. faceNormaly = normals[index * 3 + 1];
  38148. faceNormalz = normals[index * 3 + 2];
  38149. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38150. length = (length === 0) ? 1.0 : length;
  38151. faceNormalx /= length;
  38152. faceNormaly /= length;
  38153. faceNormalz /= length;
  38154. normals[index * 3] = faceNormalx;
  38155. normals[index * 3 + 1] = faceNormaly;
  38156. normals[index * 3 + 2] = faceNormalz;
  38157. }
  38158. };
  38159. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38160. var li = indices.length;
  38161. var ln = normals.length;
  38162. var i;
  38163. var n;
  38164. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38165. switch (sideOrientation) {
  38166. case BABYLON.Mesh.FRONTSIDE:
  38167. // nothing changed
  38168. break;
  38169. case BABYLON.Mesh.BACKSIDE:
  38170. var tmp;
  38171. // indices
  38172. for (i = 0; i < li; i += 3) {
  38173. tmp = indices[i];
  38174. indices[i] = indices[i + 2];
  38175. indices[i + 2] = tmp;
  38176. }
  38177. // normals
  38178. for (n = 0; n < ln; n++) {
  38179. normals[n] = -normals[n];
  38180. }
  38181. break;
  38182. case BABYLON.Mesh.DOUBLESIDE:
  38183. // positions
  38184. var lp = positions.length;
  38185. var l = lp / 3;
  38186. for (var p = 0; p < lp; p++) {
  38187. positions[lp + p] = positions[p];
  38188. }
  38189. // indices
  38190. for (i = 0; i < li; i += 3) {
  38191. indices[i + li] = indices[i + 2] + l;
  38192. indices[i + 1 + li] = indices[i + 1] + l;
  38193. indices[i + 2 + li] = indices[i] + l;
  38194. }
  38195. // normals
  38196. for (n = 0; n < ln; n++) {
  38197. normals[ln + n] = -normals[n];
  38198. }
  38199. // uvs
  38200. var lu = uvs.length;
  38201. var u = 0;
  38202. for (u = 0; u < lu; u++) {
  38203. uvs[u + lu] = uvs[u];
  38204. }
  38205. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38206. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38207. u = 0;
  38208. for (i = 0; i < lu / 2; i++) {
  38209. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38210. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38211. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38212. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38213. u += 2;
  38214. }
  38215. break;
  38216. }
  38217. };
  38218. /**
  38219. * Applies VertexData created from the imported parameters to the geometry
  38220. * @param parsedVertexData the parsed data from an imported file
  38221. * @param geometry the geometry to apply the VertexData to
  38222. */
  38223. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38224. var vertexData = new VertexData();
  38225. // positions
  38226. var positions = parsedVertexData.positions;
  38227. if (positions) {
  38228. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38229. }
  38230. // normals
  38231. var normals = parsedVertexData.normals;
  38232. if (normals) {
  38233. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38234. }
  38235. // tangents
  38236. var tangents = parsedVertexData.tangents;
  38237. if (tangents) {
  38238. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38239. }
  38240. // uvs
  38241. var uvs = parsedVertexData.uvs;
  38242. if (uvs) {
  38243. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38244. }
  38245. // uv2s
  38246. var uv2s = parsedVertexData.uv2s;
  38247. if (uv2s) {
  38248. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38249. }
  38250. // uv3s
  38251. var uv3s = parsedVertexData.uv3s;
  38252. if (uv3s) {
  38253. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38254. }
  38255. // uv4s
  38256. var uv4s = parsedVertexData.uv4s;
  38257. if (uv4s) {
  38258. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38259. }
  38260. // uv5s
  38261. var uv5s = parsedVertexData.uv5s;
  38262. if (uv5s) {
  38263. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38264. }
  38265. // uv6s
  38266. var uv6s = parsedVertexData.uv6s;
  38267. if (uv6s) {
  38268. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38269. }
  38270. // colors
  38271. var colors = parsedVertexData.colors;
  38272. if (colors) {
  38273. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38274. }
  38275. // matricesIndices
  38276. var matricesIndices = parsedVertexData.matricesIndices;
  38277. if (matricesIndices) {
  38278. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38279. }
  38280. // matricesWeights
  38281. var matricesWeights = parsedVertexData.matricesWeights;
  38282. if (matricesWeights) {
  38283. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38284. }
  38285. // indices
  38286. var indices = parsedVertexData.indices;
  38287. if (indices) {
  38288. vertexData.indices = indices;
  38289. }
  38290. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38291. };
  38292. return VertexData;
  38293. }());
  38294. BABYLON.VertexData = VertexData;
  38295. })(BABYLON || (BABYLON = {}));
  38296. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38297. var BABYLON;
  38298. (function (BABYLON) {
  38299. /**
  38300. * Class used to store geometry data (vertex buffers + index buffer)
  38301. */
  38302. var Geometry = /** @class */ (function () {
  38303. /**
  38304. * Creates a new geometry
  38305. * @param id defines the unique ID
  38306. * @param scene defines the hosting scene
  38307. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38308. * @param updatable defines if geometry must be updatable (false by default)
  38309. * @param mesh defines the mesh that will be associated with the geometry
  38310. */
  38311. function Geometry(id, scene, vertexData, updatable, mesh) {
  38312. if (updatable === void 0) { updatable = false; }
  38313. if (mesh === void 0) { mesh = null; }
  38314. /**
  38315. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38316. */
  38317. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38318. this._totalVertices = 0;
  38319. this._isDisposed = false;
  38320. this._indexBufferIsUpdatable = false;
  38321. this.id = id;
  38322. this._engine = scene.getEngine();
  38323. this._meshes = [];
  38324. this._scene = scene;
  38325. //Init vertex buffer cache
  38326. this._vertexBuffers = {};
  38327. this._indices = [];
  38328. this._updatable = updatable;
  38329. // vertexData
  38330. if (vertexData) {
  38331. this.setAllVerticesData(vertexData, updatable);
  38332. }
  38333. else {
  38334. this._totalVertices = 0;
  38335. this._indices = [];
  38336. }
  38337. if (this._engine.getCaps().vertexArrayObject) {
  38338. this._vertexArrayObjects = {};
  38339. }
  38340. // applyToMesh
  38341. if (mesh) {
  38342. if (mesh.getClassName() === "LinesMesh") {
  38343. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38344. this._updateExtend();
  38345. }
  38346. this.applyToMesh(mesh);
  38347. mesh.computeWorldMatrix(true);
  38348. }
  38349. }
  38350. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38351. /**
  38352. * 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
  38353. */
  38354. get: function () {
  38355. return this._boundingBias;
  38356. },
  38357. /**
  38358. * 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
  38359. */
  38360. set: function (value) {
  38361. if (this._boundingBias && this._boundingBias.equals(value)) {
  38362. return;
  38363. }
  38364. this._boundingBias = value.clone();
  38365. this._updateBoundingInfo(true, null);
  38366. },
  38367. enumerable: true,
  38368. configurable: true
  38369. });
  38370. /**
  38371. * Static function used to attach a new empty geometry to a mesh
  38372. * @param mesh defines the mesh to attach the geometry to
  38373. * @returns the new {BABYLON.Geometry}
  38374. */
  38375. Geometry.CreateGeometryForMesh = function (mesh) {
  38376. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38377. geometry.applyToMesh(mesh);
  38378. return geometry;
  38379. };
  38380. Object.defineProperty(Geometry.prototype, "extend", {
  38381. /**
  38382. * Gets the current extend of the geometry
  38383. */
  38384. get: function () {
  38385. return this._extend;
  38386. },
  38387. enumerable: true,
  38388. configurable: true
  38389. });
  38390. /**
  38391. * Gets the hosting scene
  38392. * @returns the hosting {BABYLON.Scene}
  38393. */
  38394. Geometry.prototype.getScene = function () {
  38395. return this._scene;
  38396. };
  38397. /**
  38398. * Gets the hosting engine
  38399. * @returns the hosting {BABYLON.Engine}
  38400. */
  38401. Geometry.prototype.getEngine = function () {
  38402. return this._engine;
  38403. };
  38404. /**
  38405. * Defines if the geometry is ready to use
  38406. * @returns true if the geometry is ready to be used
  38407. */
  38408. Geometry.prototype.isReady = function () {
  38409. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38410. };
  38411. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38412. /**
  38413. * Gets a value indicating that the geometry should not be serialized
  38414. */
  38415. get: function () {
  38416. for (var index = 0; index < this._meshes.length; index++) {
  38417. if (!this._meshes[index].doNotSerialize) {
  38418. return false;
  38419. }
  38420. }
  38421. return true;
  38422. },
  38423. enumerable: true,
  38424. configurable: true
  38425. });
  38426. /** @hidden */
  38427. Geometry.prototype._rebuild = function () {
  38428. if (this._vertexArrayObjects) {
  38429. this._vertexArrayObjects = {};
  38430. }
  38431. // Index buffer
  38432. if (this._meshes.length !== 0 && this._indices) {
  38433. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38434. }
  38435. // Vertex buffers
  38436. for (var key in this._vertexBuffers) {
  38437. var vertexBuffer = this._vertexBuffers[key];
  38438. vertexBuffer._rebuild();
  38439. }
  38440. };
  38441. /**
  38442. * Affects all geometry data in one call
  38443. * @param vertexData defines the geometry data
  38444. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38445. */
  38446. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38447. vertexData.applyToGeometry(this, updatable);
  38448. this.notifyUpdate();
  38449. };
  38450. /**
  38451. * Set specific vertex data
  38452. * @param kind defines the data kind (Position, normal, etc...)
  38453. * @param data defines the vertex data to use
  38454. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38455. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38456. */
  38457. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38458. if (updatable === void 0) { updatable = false; }
  38459. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38460. this.setVerticesBuffer(buffer);
  38461. };
  38462. /**
  38463. * Removes a specific vertex data
  38464. * @param kind defines the data kind (Position, normal, etc...)
  38465. */
  38466. Geometry.prototype.removeVerticesData = function (kind) {
  38467. if (this._vertexBuffers[kind]) {
  38468. this._vertexBuffers[kind].dispose();
  38469. delete this._vertexBuffers[kind];
  38470. }
  38471. };
  38472. /**
  38473. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38474. * @param buffer defines the vertex buffer to use
  38475. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38476. */
  38477. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38478. if (totalVertices === void 0) { totalVertices = null; }
  38479. var kind = buffer.getKind();
  38480. if (this._vertexBuffers[kind]) {
  38481. this._vertexBuffers[kind].dispose();
  38482. }
  38483. this._vertexBuffers[kind] = buffer;
  38484. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38485. var data = buffer.getData();
  38486. if (totalVertices != null) {
  38487. this._totalVertices = totalVertices;
  38488. }
  38489. else {
  38490. if (data != null) {
  38491. this._totalVertices = data.length / (buffer.byteStride / 4);
  38492. }
  38493. }
  38494. this._updateExtend(data);
  38495. this._resetPointsArrayCache();
  38496. var meshes = this._meshes;
  38497. var numOfMeshes = meshes.length;
  38498. for (var index = 0; index < numOfMeshes; index++) {
  38499. var mesh = meshes[index];
  38500. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38501. mesh._createGlobalSubMesh(false);
  38502. mesh.computeWorldMatrix(true);
  38503. }
  38504. }
  38505. this.notifyUpdate(kind);
  38506. if (this._vertexArrayObjects) {
  38507. this._disposeVertexArrayObjects();
  38508. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38509. }
  38510. };
  38511. /**
  38512. * Update a specific vertex buffer
  38513. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38514. * It will do nothing if the buffer is not updatable
  38515. * @param kind defines the data kind (Position, normal, etc...)
  38516. * @param data defines the data to use
  38517. * @param offset defines the offset in the target buffer where to store the data
  38518. * @param useBytes set to true if the offset is in bytes
  38519. */
  38520. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38521. if (useBytes === void 0) { useBytes = false; }
  38522. var vertexBuffer = this.getVertexBuffer(kind);
  38523. if (!vertexBuffer) {
  38524. return;
  38525. }
  38526. vertexBuffer.updateDirectly(data, offset, useBytes);
  38527. this.notifyUpdate(kind);
  38528. };
  38529. /**
  38530. * Update a specific vertex buffer
  38531. * This function will create a new buffer if the current one is not updatable
  38532. * @param kind defines the data kind (Position, normal, etc...)
  38533. * @param data defines the data to use
  38534. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38535. */
  38536. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38537. if (updateExtends === void 0) { updateExtends = false; }
  38538. var vertexBuffer = this.getVertexBuffer(kind);
  38539. if (!vertexBuffer) {
  38540. return;
  38541. }
  38542. vertexBuffer.update(data);
  38543. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38544. this._updateBoundingInfo(updateExtends, data);
  38545. }
  38546. this.notifyUpdate(kind);
  38547. };
  38548. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38549. if (updateExtends) {
  38550. this._updateExtend(data);
  38551. }
  38552. var meshes = this._meshes;
  38553. var numOfMeshes = meshes.length;
  38554. this._resetPointsArrayCache();
  38555. for (var index = 0; index < numOfMeshes; index++) {
  38556. var mesh = meshes[index];
  38557. if (updateExtends) {
  38558. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38559. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38560. var subMesh = mesh.subMeshes[subIndex];
  38561. subMesh.refreshBoundingInfo();
  38562. }
  38563. }
  38564. }
  38565. };
  38566. /** @hidden */
  38567. Geometry.prototype._bind = function (effect, indexToBind) {
  38568. if (!effect) {
  38569. return;
  38570. }
  38571. if (indexToBind === undefined) {
  38572. indexToBind = this._indexBuffer;
  38573. }
  38574. var vbs = this.getVertexBuffers();
  38575. if (!vbs) {
  38576. return;
  38577. }
  38578. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38579. this._engine.bindBuffers(vbs, indexToBind, effect);
  38580. return;
  38581. }
  38582. // Using VAO
  38583. if (!this._vertexArrayObjects[effect.key]) {
  38584. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38585. }
  38586. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38587. };
  38588. /**
  38589. * Gets total number of vertices
  38590. * @returns the total number of vertices
  38591. */
  38592. Geometry.prototype.getTotalVertices = function () {
  38593. if (!this.isReady()) {
  38594. return 0;
  38595. }
  38596. return this._totalVertices;
  38597. };
  38598. /**
  38599. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38600. * @param kind defines the data kind (Position, normal, etc...)
  38601. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38602. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38603. * @returns a float array containing vertex data
  38604. */
  38605. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38606. var vertexBuffer = this.getVertexBuffer(kind);
  38607. if (!vertexBuffer) {
  38608. return null;
  38609. }
  38610. var data = vertexBuffer.getData();
  38611. if (!data) {
  38612. return null;
  38613. }
  38614. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38615. var count = this._totalVertices * vertexBuffer.getSize();
  38616. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38617. var copy_1 = new Array(count);
  38618. vertexBuffer.forEach(count, function (value, index) {
  38619. copy_1[index] = value;
  38620. });
  38621. return copy_1;
  38622. }
  38623. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38624. if (data instanceof Array) {
  38625. var offset = vertexBuffer.byteOffset / 4;
  38626. return BABYLON.Tools.Slice(data, offset, offset + count);
  38627. }
  38628. else if (data instanceof ArrayBuffer) {
  38629. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38630. }
  38631. else {
  38632. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38633. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38634. var result = new Float32Array(count);
  38635. var source = new Float32Array(data.buffer, offset, count);
  38636. result.set(source);
  38637. return result;
  38638. }
  38639. return new Float32Array(data.buffer, offset, count);
  38640. }
  38641. }
  38642. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38643. return BABYLON.Tools.Slice(data);
  38644. }
  38645. return data;
  38646. };
  38647. /**
  38648. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38649. * @param kind defines the data kind (Position, normal, etc...)
  38650. * @returns true if the vertex buffer with the specified kind is updatable
  38651. */
  38652. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38653. var vb = this._vertexBuffers[kind];
  38654. if (!vb) {
  38655. return false;
  38656. }
  38657. return vb.isUpdatable();
  38658. };
  38659. /**
  38660. * Gets a specific vertex buffer
  38661. * @param kind defines the data kind (Position, normal, etc...)
  38662. * @returns a {BABYLON.VertexBuffer}
  38663. */
  38664. Geometry.prototype.getVertexBuffer = function (kind) {
  38665. if (!this.isReady()) {
  38666. return null;
  38667. }
  38668. return this._vertexBuffers[kind];
  38669. };
  38670. /**
  38671. * Returns all vertex buffers
  38672. * @return an object holding all vertex buffers indexed by kind
  38673. */
  38674. Geometry.prototype.getVertexBuffers = function () {
  38675. if (!this.isReady()) {
  38676. return null;
  38677. }
  38678. return this._vertexBuffers;
  38679. };
  38680. /**
  38681. * Gets a boolean indicating if specific vertex buffer is present
  38682. * @param kind defines the data kind (Position, normal, etc...)
  38683. * @returns true if data is present
  38684. */
  38685. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38686. if (!this._vertexBuffers) {
  38687. if (this._delayInfo) {
  38688. return this._delayInfo.indexOf(kind) !== -1;
  38689. }
  38690. return false;
  38691. }
  38692. return this._vertexBuffers[kind] !== undefined;
  38693. };
  38694. /**
  38695. * Gets a list of all attached data kinds (Position, normal, etc...)
  38696. * @returns a list of string containing all kinds
  38697. */
  38698. Geometry.prototype.getVerticesDataKinds = function () {
  38699. var result = [];
  38700. var kind;
  38701. if (!this._vertexBuffers && this._delayInfo) {
  38702. for (kind in this._delayInfo) {
  38703. result.push(kind);
  38704. }
  38705. }
  38706. else {
  38707. for (kind in this._vertexBuffers) {
  38708. result.push(kind);
  38709. }
  38710. }
  38711. return result;
  38712. };
  38713. /**
  38714. * Update index buffer
  38715. * @param indices defines the indices to store in the index buffer
  38716. * @param offset defines the offset in the target buffer where to store the data
  38717. */
  38718. Geometry.prototype.updateIndices = function (indices, offset) {
  38719. if (!this._indexBuffer) {
  38720. return;
  38721. }
  38722. if (!this._indexBufferIsUpdatable) {
  38723. this.setIndices(indices, null, true);
  38724. }
  38725. else {
  38726. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38727. }
  38728. };
  38729. /**
  38730. * Creates a new index buffer
  38731. * @param indices defines the indices to store in the index buffer
  38732. * @param totalVertices defines the total number of vertices (could be null)
  38733. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38734. */
  38735. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38736. if (totalVertices === void 0) { totalVertices = null; }
  38737. if (updatable === void 0) { updatable = false; }
  38738. if (this._indexBuffer) {
  38739. this._engine._releaseBuffer(this._indexBuffer);
  38740. }
  38741. this._disposeVertexArrayObjects();
  38742. this._indices = indices;
  38743. this._indexBufferIsUpdatable = updatable;
  38744. if (this._meshes.length !== 0 && this._indices) {
  38745. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38746. }
  38747. if (totalVertices != undefined) { // including null and undefined
  38748. this._totalVertices = totalVertices;
  38749. }
  38750. var meshes = this._meshes;
  38751. var numOfMeshes = meshes.length;
  38752. for (var index = 0; index < numOfMeshes; index++) {
  38753. meshes[index]._createGlobalSubMesh(true);
  38754. }
  38755. this.notifyUpdate();
  38756. };
  38757. /**
  38758. * Return the total number of indices
  38759. * @returns the total number of indices
  38760. */
  38761. Geometry.prototype.getTotalIndices = function () {
  38762. if (!this.isReady()) {
  38763. return 0;
  38764. }
  38765. return this._indices.length;
  38766. };
  38767. /**
  38768. * Gets the index buffer array
  38769. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38770. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38771. * @returns the index buffer array
  38772. */
  38773. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  38774. if (!this.isReady()) {
  38775. return null;
  38776. }
  38777. var orig = this._indices;
  38778. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  38779. return orig;
  38780. }
  38781. else {
  38782. var len = orig.length;
  38783. var copy = [];
  38784. for (var i = 0; i < len; i++) {
  38785. copy.push(orig[i]);
  38786. }
  38787. return copy;
  38788. }
  38789. };
  38790. /**
  38791. * Gets the index buffer
  38792. * @return the index buffer
  38793. */
  38794. Geometry.prototype.getIndexBuffer = function () {
  38795. if (!this.isReady()) {
  38796. return null;
  38797. }
  38798. return this._indexBuffer;
  38799. };
  38800. /** @hidden */
  38801. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38802. if (effect === void 0) { effect = null; }
  38803. if (!effect || !this._vertexArrayObjects) {
  38804. return;
  38805. }
  38806. if (this._vertexArrayObjects[effect.key]) {
  38807. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38808. delete this._vertexArrayObjects[effect.key];
  38809. }
  38810. };
  38811. /**
  38812. * Release the associated resources for a specific mesh
  38813. * @param mesh defines the source mesh
  38814. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38815. */
  38816. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38817. var meshes = this._meshes;
  38818. var index = meshes.indexOf(mesh);
  38819. if (index === -1) {
  38820. return;
  38821. }
  38822. meshes.splice(index, 1);
  38823. mesh._geometry = null;
  38824. if (meshes.length === 0 && shouldDispose) {
  38825. this.dispose();
  38826. }
  38827. };
  38828. /**
  38829. * Apply current geometry to a given mesh
  38830. * @param mesh defines the mesh to apply geometry to
  38831. */
  38832. Geometry.prototype.applyToMesh = function (mesh) {
  38833. if (mesh._geometry === this) {
  38834. return;
  38835. }
  38836. var previousGeometry = mesh._geometry;
  38837. if (previousGeometry) {
  38838. previousGeometry.releaseForMesh(mesh);
  38839. }
  38840. var meshes = this._meshes;
  38841. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38842. mesh._geometry = this;
  38843. this._scene.pushGeometry(this);
  38844. meshes.push(mesh);
  38845. if (this.isReady()) {
  38846. this._applyToMesh(mesh);
  38847. }
  38848. else {
  38849. mesh._boundingInfo = this._boundingInfo;
  38850. }
  38851. };
  38852. Geometry.prototype._updateExtend = function (data) {
  38853. if (data === void 0) { data = null; }
  38854. if (!data) {
  38855. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38856. }
  38857. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38858. };
  38859. Geometry.prototype._applyToMesh = function (mesh) {
  38860. var numOfMeshes = this._meshes.length;
  38861. // vertexBuffers
  38862. for (var kind in this._vertexBuffers) {
  38863. if (numOfMeshes === 1) {
  38864. this._vertexBuffers[kind].create();
  38865. }
  38866. var buffer = this._vertexBuffers[kind].getBuffer();
  38867. if (buffer)
  38868. buffer.references = numOfMeshes;
  38869. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38870. if (!this._extend) {
  38871. this._updateExtend();
  38872. }
  38873. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38874. mesh._createGlobalSubMesh(false);
  38875. //bounding info was just created again, world matrix should be applied again.
  38876. mesh._updateBoundingInfo();
  38877. }
  38878. }
  38879. // indexBuffer
  38880. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38881. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38882. }
  38883. if (this._indexBuffer) {
  38884. this._indexBuffer.references = numOfMeshes;
  38885. }
  38886. };
  38887. Geometry.prototype.notifyUpdate = function (kind) {
  38888. if (this.onGeometryUpdated) {
  38889. this.onGeometryUpdated(this, kind);
  38890. }
  38891. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38892. var mesh = _a[_i];
  38893. mesh._markSubMeshesAsAttributesDirty();
  38894. }
  38895. };
  38896. /**
  38897. * Load the geometry if it was flagged as delay loaded
  38898. * @param scene defines the hosting scene
  38899. * @param onLoaded defines a callback called when the geometry is loaded
  38900. */
  38901. Geometry.prototype.load = function (scene, onLoaded) {
  38902. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38903. return;
  38904. }
  38905. if (this.isReady()) {
  38906. if (onLoaded) {
  38907. onLoaded();
  38908. }
  38909. return;
  38910. }
  38911. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38912. this._queueLoad(scene, onLoaded);
  38913. };
  38914. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38915. var _this = this;
  38916. if (!this.delayLoadingFile) {
  38917. return;
  38918. }
  38919. scene._addPendingData(this);
  38920. scene._loadFile(this.delayLoadingFile, function (data) {
  38921. if (!_this._delayLoadingFunction) {
  38922. return;
  38923. }
  38924. _this._delayLoadingFunction(JSON.parse(data), _this);
  38925. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38926. _this._delayInfo = [];
  38927. scene._removePendingData(_this);
  38928. var meshes = _this._meshes;
  38929. var numOfMeshes = meshes.length;
  38930. for (var index = 0; index < numOfMeshes; index++) {
  38931. _this._applyToMesh(meshes[index]);
  38932. }
  38933. if (onLoaded) {
  38934. onLoaded();
  38935. }
  38936. }, undefined, true);
  38937. };
  38938. /**
  38939. * Invert the geometry to move from a right handed system to a left handed one.
  38940. */
  38941. Geometry.prototype.toLeftHanded = function () {
  38942. // Flip faces
  38943. var tIndices = this.getIndices(false);
  38944. if (tIndices != null && tIndices.length > 0) {
  38945. for (var i = 0; i < tIndices.length; i += 3) {
  38946. var tTemp = tIndices[i + 0];
  38947. tIndices[i + 0] = tIndices[i + 2];
  38948. tIndices[i + 2] = tTemp;
  38949. }
  38950. this.setIndices(tIndices);
  38951. }
  38952. // Negate position.z
  38953. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38954. if (tPositions != null && tPositions.length > 0) {
  38955. for (var i = 0; i < tPositions.length; i += 3) {
  38956. tPositions[i + 2] = -tPositions[i + 2];
  38957. }
  38958. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38959. }
  38960. // Negate normal.z
  38961. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38962. if (tNormals != null && tNormals.length > 0) {
  38963. for (var i = 0; i < tNormals.length; i += 3) {
  38964. tNormals[i + 2] = -tNormals[i + 2];
  38965. }
  38966. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38967. }
  38968. };
  38969. // Cache
  38970. /** @hidden */
  38971. Geometry.prototype._resetPointsArrayCache = function () {
  38972. this._positions = null;
  38973. };
  38974. /** @hidden */
  38975. Geometry.prototype._generatePointsArray = function () {
  38976. if (this._positions)
  38977. return true;
  38978. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38979. if (!data || data.length === 0) {
  38980. return false;
  38981. }
  38982. this._positions = [];
  38983. for (var index = 0; index < data.length; index += 3) {
  38984. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38985. }
  38986. return true;
  38987. };
  38988. /**
  38989. * Gets a value indicating if the geometry is disposed
  38990. * @returns true if the geometry was disposed
  38991. */
  38992. Geometry.prototype.isDisposed = function () {
  38993. return this._isDisposed;
  38994. };
  38995. Geometry.prototype._disposeVertexArrayObjects = function () {
  38996. if (this._vertexArrayObjects) {
  38997. for (var kind in this._vertexArrayObjects) {
  38998. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38999. }
  39000. this._vertexArrayObjects = {};
  39001. }
  39002. };
  39003. /**
  39004. * Free all associated resources
  39005. */
  39006. Geometry.prototype.dispose = function () {
  39007. var meshes = this._meshes;
  39008. var numOfMeshes = meshes.length;
  39009. var index;
  39010. for (index = 0; index < numOfMeshes; index++) {
  39011. this.releaseForMesh(meshes[index]);
  39012. }
  39013. this._meshes = [];
  39014. this._disposeVertexArrayObjects();
  39015. for (var kind in this._vertexBuffers) {
  39016. this._vertexBuffers[kind].dispose();
  39017. }
  39018. this._vertexBuffers = {};
  39019. this._totalVertices = 0;
  39020. if (this._indexBuffer) {
  39021. this._engine._releaseBuffer(this._indexBuffer);
  39022. }
  39023. this._indexBuffer = null;
  39024. this._indices = [];
  39025. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39026. this.delayLoadingFile = null;
  39027. this._delayLoadingFunction = null;
  39028. this._delayInfo = [];
  39029. this._boundingInfo = null;
  39030. this._scene.removeGeometry(this);
  39031. this._isDisposed = true;
  39032. };
  39033. /**
  39034. * Clone the current geometry into a new geometry
  39035. * @param id defines the unique ID of the new geometry
  39036. * @returns a new geometry object
  39037. */
  39038. Geometry.prototype.copy = function (id) {
  39039. var vertexData = new BABYLON.VertexData();
  39040. vertexData.indices = [];
  39041. var indices = this.getIndices();
  39042. if (indices) {
  39043. for (var index = 0; index < indices.length; index++) {
  39044. vertexData.indices.push(indices[index]);
  39045. }
  39046. }
  39047. var updatable = false;
  39048. var stopChecking = false;
  39049. var kind;
  39050. for (kind in this._vertexBuffers) {
  39051. // using slice() to make a copy of the array and not just reference it
  39052. var data = this.getVerticesData(kind);
  39053. if (data instanceof Float32Array) {
  39054. vertexData.set(new Float32Array(data), kind);
  39055. }
  39056. else {
  39057. vertexData.set(data.slice(0), kind);
  39058. }
  39059. if (!stopChecking) {
  39060. var vb = this.getVertexBuffer(kind);
  39061. if (vb) {
  39062. updatable = vb.isUpdatable();
  39063. stopChecking = !updatable;
  39064. }
  39065. }
  39066. }
  39067. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39068. geometry.delayLoadState = this.delayLoadState;
  39069. geometry.delayLoadingFile = this.delayLoadingFile;
  39070. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39071. for (kind in this._delayInfo) {
  39072. geometry._delayInfo = geometry._delayInfo || [];
  39073. geometry._delayInfo.push(kind);
  39074. }
  39075. // Bounding info
  39076. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39077. return geometry;
  39078. };
  39079. /**
  39080. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39081. * @return a JSON representation of the current geometry data (without the vertices data)
  39082. */
  39083. Geometry.prototype.serialize = function () {
  39084. var serializationObject = {};
  39085. serializationObject.id = this.id;
  39086. serializationObject.updatable = this._updatable;
  39087. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39088. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39089. }
  39090. return serializationObject;
  39091. };
  39092. Geometry.prototype.toNumberArray = function (origin) {
  39093. if (Array.isArray(origin)) {
  39094. return origin;
  39095. }
  39096. else {
  39097. return Array.prototype.slice.call(origin);
  39098. }
  39099. };
  39100. /**
  39101. * Serialize all vertices data into a JSON oject
  39102. * @returns a JSON representation of the current geometry data
  39103. */
  39104. Geometry.prototype.serializeVerticeData = function () {
  39105. var serializationObject = this.serialize();
  39106. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39107. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39108. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39109. serializationObject.positions._updatable = true;
  39110. }
  39111. }
  39112. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39113. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39114. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39115. serializationObject.normals._updatable = true;
  39116. }
  39117. }
  39118. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39119. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39120. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39121. serializationObject.tangets._updatable = true;
  39122. }
  39123. }
  39124. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39125. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39126. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39127. serializationObject.uvs._updatable = true;
  39128. }
  39129. }
  39130. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39131. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39132. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39133. serializationObject.uv2s._updatable = true;
  39134. }
  39135. }
  39136. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39137. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39138. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39139. serializationObject.uv3s._updatable = true;
  39140. }
  39141. }
  39142. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39143. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39144. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39145. serializationObject.uv4s._updatable = true;
  39146. }
  39147. }
  39148. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39149. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39150. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39151. serializationObject.uv5s._updatable = true;
  39152. }
  39153. }
  39154. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39155. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39156. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39157. serializationObject.uv6s._updatable = true;
  39158. }
  39159. }
  39160. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39161. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39162. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39163. serializationObject.colors._updatable = true;
  39164. }
  39165. }
  39166. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39167. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39168. serializationObject.matricesIndices._isExpanded = true;
  39169. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39170. serializationObject.matricesIndices._updatable = true;
  39171. }
  39172. }
  39173. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39174. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39175. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39176. serializationObject.matricesWeights._updatable = true;
  39177. }
  39178. }
  39179. serializationObject.indices = this.toNumberArray(this.getIndices());
  39180. return serializationObject;
  39181. };
  39182. // Statics
  39183. /**
  39184. * Extracts a clone of a mesh geometry
  39185. * @param mesh defines the source mesh
  39186. * @param id defines the unique ID of the new geometry object
  39187. * @returns the new geometry object
  39188. */
  39189. Geometry.ExtractFromMesh = function (mesh, id) {
  39190. var geometry = mesh._geometry;
  39191. if (!geometry) {
  39192. return null;
  39193. }
  39194. return geometry.copy(id);
  39195. };
  39196. /**
  39197. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39198. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39199. * Be aware Math.random() could cause collisions, but:
  39200. * "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"
  39201. * @returns a string containing a new GUID
  39202. */
  39203. Geometry.RandomId = function () {
  39204. return BABYLON.Tools.RandomId();
  39205. };
  39206. /** @hidden */
  39207. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39208. var scene = mesh.getScene();
  39209. // Geometry
  39210. var geometryId = parsedGeometry.geometryId;
  39211. if (geometryId) {
  39212. var geometry = scene.getGeometryByID(geometryId);
  39213. if (geometry) {
  39214. geometry.applyToMesh(mesh);
  39215. }
  39216. }
  39217. else if (parsedGeometry instanceof ArrayBuffer) {
  39218. var binaryInfo = mesh._binaryInfo;
  39219. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39220. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39221. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39222. }
  39223. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39224. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39225. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39226. }
  39227. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39228. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39229. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39230. }
  39231. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39232. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39233. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39234. }
  39235. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39236. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39237. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39238. }
  39239. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39240. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39241. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39242. }
  39243. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39244. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39245. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39246. }
  39247. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39248. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39249. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39250. }
  39251. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39252. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39253. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39254. }
  39255. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39256. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39257. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39258. }
  39259. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39260. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39261. var floatIndices = [];
  39262. for (var i = 0; i < matricesIndicesData.length; i++) {
  39263. var index = matricesIndicesData[i];
  39264. floatIndices.push(index & 0x000000FF);
  39265. floatIndices.push((index & 0x0000FF00) >> 8);
  39266. floatIndices.push((index & 0x00FF0000) >> 16);
  39267. floatIndices.push(index >> 24);
  39268. }
  39269. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39270. }
  39271. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39272. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39273. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39274. }
  39275. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39276. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39277. mesh.setIndices(indicesData, null);
  39278. }
  39279. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39280. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39281. mesh.subMeshes = [];
  39282. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39283. var materialIndex = subMeshesData[(i * 5) + 0];
  39284. var verticesStart = subMeshesData[(i * 5) + 1];
  39285. var verticesCount = subMeshesData[(i * 5) + 2];
  39286. var indexStart = subMeshesData[(i * 5) + 3];
  39287. var indexCount = subMeshesData[(i * 5) + 4];
  39288. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39289. }
  39290. }
  39291. }
  39292. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39293. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39294. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39295. if (parsedGeometry.tangents) {
  39296. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39297. }
  39298. if (parsedGeometry.uvs) {
  39299. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39300. }
  39301. if (parsedGeometry.uvs2) {
  39302. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39303. }
  39304. if (parsedGeometry.uvs3) {
  39305. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39306. }
  39307. if (parsedGeometry.uvs4) {
  39308. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39309. }
  39310. if (parsedGeometry.uvs5) {
  39311. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39312. }
  39313. if (parsedGeometry.uvs6) {
  39314. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39315. }
  39316. if (parsedGeometry.colors) {
  39317. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39318. }
  39319. if (parsedGeometry.matricesIndices) {
  39320. if (!parsedGeometry.matricesIndices._isExpanded) {
  39321. var floatIndices = [];
  39322. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39323. var matricesIndex = parsedGeometry.matricesIndices[i];
  39324. floatIndices.push(matricesIndex & 0x000000FF);
  39325. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39326. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39327. floatIndices.push(matricesIndex >> 24);
  39328. }
  39329. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39330. }
  39331. else {
  39332. delete parsedGeometry.matricesIndices._isExpanded;
  39333. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39334. }
  39335. }
  39336. if (parsedGeometry.matricesIndicesExtra) {
  39337. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39338. var floatIndices = [];
  39339. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39340. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39341. floatIndices.push(matricesIndex & 0x000000FF);
  39342. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39343. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39344. floatIndices.push(matricesIndex >> 24);
  39345. }
  39346. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39347. }
  39348. else {
  39349. delete parsedGeometry.matricesIndices._isExpanded;
  39350. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39351. }
  39352. }
  39353. if (parsedGeometry.matricesWeights) {
  39354. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39355. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39356. }
  39357. if (parsedGeometry.matricesWeightsExtra) {
  39358. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39359. }
  39360. mesh.setIndices(parsedGeometry.indices, null);
  39361. }
  39362. // SubMeshes
  39363. if (parsedGeometry.subMeshes) {
  39364. mesh.subMeshes = [];
  39365. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39366. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39367. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39368. }
  39369. }
  39370. // Flat shading
  39371. if (mesh._shouldGenerateFlatShading) {
  39372. mesh.convertToFlatShadedMesh();
  39373. delete mesh._shouldGenerateFlatShading;
  39374. }
  39375. // Update
  39376. mesh.computeWorldMatrix(true);
  39377. scene.onMeshImportedObservable.notifyObservers(mesh);
  39378. };
  39379. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39380. var epsilon = 1e-3;
  39381. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39382. return;
  39383. }
  39384. var noInfluenceBoneIndex = 0.0;
  39385. if (parsedGeometry.skeletonId > -1) {
  39386. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39387. if (!skeleton) {
  39388. return;
  39389. }
  39390. noInfluenceBoneIndex = skeleton.bones.length;
  39391. }
  39392. else {
  39393. return;
  39394. }
  39395. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39396. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39397. var matricesWeights = parsedGeometry.matricesWeights;
  39398. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39399. var influencers = parsedGeometry.numBoneInfluencer;
  39400. var size = matricesWeights.length;
  39401. for (var i = 0; i < size; i += 4) {
  39402. var weight = 0.0;
  39403. var firstZeroWeight = -1;
  39404. for (var j = 0; j < 4; j++) {
  39405. var w = matricesWeights[i + j];
  39406. weight += w;
  39407. if (w < epsilon && firstZeroWeight < 0) {
  39408. firstZeroWeight = j;
  39409. }
  39410. }
  39411. if (matricesWeightsExtra) {
  39412. for (var j = 0; j < 4; j++) {
  39413. var w = matricesWeightsExtra[i + j];
  39414. weight += w;
  39415. if (w < epsilon && firstZeroWeight < 0) {
  39416. firstZeroWeight = j + 4;
  39417. }
  39418. }
  39419. }
  39420. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39421. firstZeroWeight = influencers - 1;
  39422. }
  39423. if (weight > epsilon) {
  39424. var mweight = 1.0 / weight;
  39425. for (var j = 0; j < 4; j++) {
  39426. matricesWeights[i + j] *= mweight;
  39427. }
  39428. if (matricesWeightsExtra) {
  39429. for (var j = 0; j < 4; j++) {
  39430. matricesWeightsExtra[i + j] *= mweight;
  39431. }
  39432. }
  39433. }
  39434. else {
  39435. if (firstZeroWeight >= 4) {
  39436. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39437. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39438. }
  39439. else {
  39440. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39441. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39442. }
  39443. }
  39444. }
  39445. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39446. if (parsedGeometry.matricesWeightsExtra) {
  39447. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39448. }
  39449. };
  39450. /**
  39451. * Create a new geometry from persisted data (Using .babylon file format)
  39452. * @param parsedVertexData defines the persisted data
  39453. * @param scene defines the hosting scene
  39454. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39455. * @returns the new geometry object
  39456. */
  39457. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39458. if (scene.getGeometryByID(parsedVertexData.id)) {
  39459. return null; // null since geometry could be something else than a box...
  39460. }
  39461. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39462. if (BABYLON.Tags) {
  39463. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39464. }
  39465. if (parsedVertexData.delayLoadingFile) {
  39466. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39467. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39468. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39469. geometry._delayInfo = [];
  39470. if (parsedVertexData.hasUVs) {
  39471. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39472. }
  39473. if (parsedVertexData.hasUVs2) {
  39474. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39475. }
  39476. if (parsedVertexData.hasUVs3) {
  39477. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39478. }
  39479. if (parsedVertexData.hasUVs4) {
  39480. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39481. }
  39482. if (parsedVertexData.hasUVs5) {
  39483. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39484. }
  39485. if (parsedVertexData.hasUVs6) {
  39486. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39487. }
  39488. if (parsedVertexData.hasColors) {
  39489. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39490. }
  39491. if (parsedVertexData.hasMatricesIndices) {
  39492. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39493. }
  39494. if (parsedVertexData.hasMatricesWeights) {
  39495. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39496. }
  39497. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39498. }
  39499. else {
  39500. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39501. }
  39502. scene.pushGeometry(geometry, true);
  39503. return geometry;
  39504. };
  39505. return Geometry;
  39506. }());
  39507. BABYLON.Geometry = Geometry;
  39508. // Primitives
  39509. /// Abstract class
  39510. /**
  39511. * Abstract class used to provide common services for all typed geometries
  39512. * @hidden
  39513. */
  39514. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39515. __extends(_PrimitiveGeometry, _super);
  39516. /**
  39517. * Creates a new typed geometry
  39518. * @param id defines the unique ID of the geometry
  39519. * @param scene defines the hosting scene
  39520. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39521. * @param mesh defines the hosting mesh (can be null)
  39522. */
  39523. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39524. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39525. if (mesh === void 0) { mesh = null; }
  39526. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39527. _this._canBeRegenerated = _canBeRegenerated;
  39528. _this._beingRegenerated = true;
  39529. _this.regenerate();
  39530. _this._beingRegenerated = false;
  39531. return _this;
  39532. }
  39533. /**
  39534. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39535. * @returns true if the geometry can be regenerated
  39536. */
  39537. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39538. return this._canBeRegenerated;
  39539. };
  39540. /**
  39541. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39542. */
  39543. _PrimitiveGeometry.prototype.regenerate = function () {
  39544. if (!this._canBeRegenerated) {
  39545. return;
  39546. }
  39547. this._beingRegenerated = true;
  39548. this.setAllVerticesData(this._regenerateVertexData(), false);
  39549. this._beingRegenerated = false;
  39550. };
  39551. /**
  39552. * Clone the geometry
  39553. * @param id defines the unique ID of the new geometry
  39554. * @returns the new geometry
  39555. */
  39556. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39557. return _super.prototype.copy.call(this, id);
  39558. };
  39559. // overrides
  39560. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39561. if (!this._beingRegenerated) {
  39562. return;
  39563. }
  39564. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39565. };
  39566. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39567. if (!this._beingRegenerated) {
  39568. return;
  39569. }
  39570. _super.prototype.setVerticesData.call(this, kind, data, false);
  39571. };
  39572. // to override
  39573. /** @hidden */
  39574. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39575. throw new Error("Abstract method");
  39576. };
  39577. _PrimitiveGeometry.prototype.copy = function (id) {
  39578. throw new Error("Must be overriden in sub-classes.");
  39579. };
  39580. _PrimitiveGeometry.prototype.serialize = function () {
  39581. var serializationObject = _super.prototype.serialize.call(this);
  39582. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39583. return serializationObject;
  39584. };
  39585. return _PrimitiveGeometry;
  39586. }(Geometry));
  39587. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39588. /**
  39589. * Creates a ribbon geometry
  39590. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39591. */
  39592. var RibbonGeometry = /** @class */ (function (_super) {
  39593. __extends(RibbonGeometry, _super);
  39594. /**
  39595. * Creates a ribbon geometry
  39596. * @param id defines the unique ID of the geometry
  39597. * @param scene defines the hosting scene
  39598. * @param pathArray defines the array of paths to use
  39599. * @param closeArray defines if the last path and the first path must be joined
  39600. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39601. * @param offset defines the offset between points
  39602. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39603. * @param mesh defines the hosting mesh (can be null)
  39604. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39605. */
  39606. function RibbonGeometry(id, scene,
  39607. /**
  39608. * Defines the array of paths to use
  39609. */
  39610. pathArray,
  39611. /**
  39612. * Defines if the last and first points of each path in your pathArray must be joined
  39613. */
  39614. closeArray,
  39615. /**
  39616. * Defines if the last and first points of each path in your pathArray must be joined
  39617. */
  39618. closePath,
  39619. /**
  39620. * Defines the offset between points
  39621. */
  39622. offset, canBeRegenerated, mesh,
  39623. /**
  39624. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39625. */
  39626. side) {
  39627. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39628. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39629. _this.pathArray = pathArray;
  39630. _this.closeArray = closeArray;
  39631. _this.closePath = closePath;
  39632. _this.offset = offset;
  39633. _this.side = side;
  39634. return _this;
  39635. }
  39636. /** @hidden */
  39637. RibbonGeometry.prototype._regenerateVertexData = function () {
  39638. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39639. };
  39640. RibbonGeometry.prototype.copy = function (id) {
  39641. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39642. };
  39643. return RibbonGeometry;
  39644. }(_PrimitiveGeometry));
  39645. BABYLON.RibbonGeometry = RibbonGeometry;
  39646. /**
  39647. * Creates a box geometry
  39648. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39649. */
  39650. var BoxGeometry = /** @class */ (function (_super) {
  39651. __extends(BoxGeometry, _super);
  39652. /**
  39653. * Creates a box geometry
  39654. * @param id defines the unique ID of the geometry
  39655. * @param scene defines the hosting scene
  39656. * @param size defines the zise of the box (width, height and depth are the same)
  39657. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39658. * @param mesh defines the hosting mesh (can be null)
  39659. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39660. */
  39661. function BoxGeometry(id, scene,
  39662. /**
  39663. * Defines the zise of the box (width, height and depth are the same)
  39664. */
  39665. size, canBeRegenerated, mesh,
  39666. /**
  39667. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39668. */
  39669. side) {
  39670. if (mesh === void 0) { mesh = null; }
  39671. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39672. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39673. _this.size = size;
  39674. _this.side = side;
  39675. return _this;
  39676. }
  39677. /** @hidden */
  39678. BoxGeometry.prototype._regenerateVertexData = function () {
  39679. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39680. };
  39681. BoxGeometry.prototype.copy = function (id) {
  39682. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39683. };
  39684. BoxGeometry.prototype.serialize = function () {
  39685. var serializationObject = _super.prototype.serialize.call(this);
  39686. serializationObject.size = this.size;
  39687. return serializationObject;
  39688. };
  39689. BoxGeometry.Parse = function (parsedBox, scene) {
  39690. if (scene.getGeometryByID(parsedBox.id)) {
  39691. return null; // null since geometry could be something else than a box...
  39692. }
  39693. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39694. if (BABYLON.Tags) {
  39695. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39696. }
  39697. scene.pushGeometry(box, true);
  39698. return box;
  39699. };
  39700. return BoxGeometry;
  39701. }(_PrimitiveGeometry));
  39702. BABYLON.BoxGeometry = BoxGeometry;
  39703. /**
  39704. * Creates a sphere geometry
  39705. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39706. */
  39707. var SphereGeometry = /** @class */ (function (_super) {
  39708. __extends(SphereGeometry, _super);
  39709. /**
  39710. * Create a new sphere geometry
  39711. * @param id defines the unique ID of the geometry
  39712. * @param scene defines the hosting scene
  39713. * @param segments defines the number of segments to use to create the sphere
  39714. * @param diameter defines the diameter of the sphere
  39715. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39716. * @param mesh defines the hosting mesh (can be null)
  39717. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39718. */
  39719. function SphereGeometry(id, scene,
  39720. /**
  39721. * Defines the number of segments to use to create the sphere
  39722. */
  39723. segments,
  39724. /**
  39725. * Defines the diameter of the sphere
  39726. */
  39727. diameter, canBeRegenerated, mesh,
  39728. /**
  39729. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39730. */
  39731. side) {
  39732. if (mesh === void 0) { mesh = null; }
  39733. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39734. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39735. _this.segments = segments;
  39736. _this.diameter = diameter;
  39737. _this.side = side;
  39738. return _this;
  39739. }
  39740. /** @hidden */
  39741. SphereGeometry.prototype._regenerateVertexData = function () {
  39742. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39743. };
  39744. SphereGeometry.prototype.copy = function (id) {
  39745. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39746. };
  39747. SphereGeometry.prototype.serialize = function () {
  39748. var serializationObject = _super.prototype.serialize.call(this);
  39749. serializationObject.segments = this.segments;
  39750. serializationObject.diameter = this.diameter;
  39751. return serializationObject;
  39752. };
  39753. SphereGeometry.Parse = function (parsedSphere, scene) {
  39754. if (scene.getGeometryByID(parsedSphere.id)) {
  39755. return null; // null since geometry could be something else than a sphere...
  39756. }
  39757. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39758. if (BABYLON.Tags) {
  39759. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39760. }
  39761. scene.pushGeometry(sphere, true);
  39762. return sphere;
  39763. };
  39764. return SphereGeometry;
  39765. }(_PrimitiveGeometry));
  39766. BABYLON.SphereGeometry = SphereGeometry;
  39767. /**
  39768. * Creates a disc geometry
  39769. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39770. */
  39771. var DiscGeometry = /** @class */ (function (_super) {
  39772. __extends(DiscGeometry, _super);
  39773. /**
  39774. * Creates a new disc geometry
  39775. * @param id defines the unique ID of the geometry
  39776. * @param scene defines the hosting scene
  39777. * @param radius defines the radius of the disc
  39778. * @param tessellation defines the tesselation factor to apply to the disc
  39779. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39780. * @param mesh defines the hosting mesh (can be null)
  39781. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39782. */
  39783. function DiscGeometry(id, scene,
  39784. /**
  39785. * Defines the radius of the disc
  39786. */
  39787. radius,
  39788. /**
  39789. * Defines the tesselation factor to apply to the disc
  39790. */
  39791. tessellation, canBeRegenerated, mesh,
  39792. /**
  39793. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39794. */
  39795. side) {
  39796. if (mesh === void 0) { mesh = null; }
  39797. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39798. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39799. _this.radius = radius;
  39800. _this.tessellation = tessellation;
  39801. _this.side = side;
  39802. return _this;
  39803. }
  39804. /** @hidden */
  39805. DiscGeometry.prototype._regenerateVertexData = function () {
  39806. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39807. };
  39808. DiscGeometry.prototype.copy = function (id) {
  39809. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39810. };
  39811. return DiscGeometry;
  39812. }(_PrimitiveGeometry));
  39813. BABYLON.DiscGeometry = DiscGeometry;
  39814. /**
  39815. * Creates a new cylinder geometry
  39816. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39817. */
  39818. var CylinderGeometry = /** @class */ (function (_super) {
  39819. __extends(CylinderGeometry, _super);
  39820. /**
  39821. * Creates a new cylinder geometry
  39822. * @param id defines the unique ID of the geometry
  39823. * @param scene defines the hosting scene
  39824. * @param height defines the height of the cylinder
  39825. * @param diameterTop defines the diameter of the cylinder's top cap
  39826. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39827. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39828. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39829. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39830. * @param mesh defines the hosting mesh (can be null)
  39831. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39832. */
  39833. function CylinderGeometry(id, scene,
  39834. /**
  39835. * Defines the height of the cylinder
  39836. */
  39837. height,
  39838. /**
  39839. * Defines the diameter of the cylinder's top cap
  39840. */
  39841. diameterTop,
  39842. /**
  39843. * Defines the diameter of the cylinder's bottom cap
  39844. */
  39845. diameterBottom,
  39846. /**
  39847. * Defines the tessellation factor to apply to the cylinder
  39848. */
  39849. tessellation,
  39850. /**
  39851. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39852. */
  39853. subdivisions, canBeRegenerated, mesh,
  39854. /**
  39855. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39856. */
  39857. side) {
  39858. if (subdivisions === void 0) { subdivisions = 1; }
  39859. if (mesh === void 0) { mesh = null; }
  39860. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39861. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39862. _this.height = height;
  39863. _this.diameterTop = diameterTop;
  39864. _this.diameterBottom = diameterBottom;
  39865. _this.tessellation = tessellation;
  39866. _this.subdivisions = subdivisions;
  39867. _this.side = side;
  39868. return _this;
  39869. }
  39870. /** @hidden */
  39871. CylinderGeometry.prototype._regenerateVertexData = function () {
  39872. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39873. };
  39874. CylinderGeometry.prototype.copy = function (id) {
  39875. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39876. };
  39877. CylinderGeometry.prototype.serialize = function () {
  39878. var serializationObject = _super.prototype.serialize.call(this);
  39879. serializationObject.height = this.height;
  39880. serializationObject.diameterTop = this.diameterTop;
  39881. serializationObject.diameterBottom = this.diameterBottom;
  39882. serializationObject.tessellation = this.tessellation;
  39883. return serializationObject;
  39884. };
  39885. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39886. if (scene.getGeometryByID(parsedCylinder.id)) {
  39887. return null; // null since geometry could be something else than a cylinder...
  39888. }
  39889. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39890. if (BABYLON.Tags) {
  39891. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39892. }
  39893. scene.pushGeometry(cylinder, true);
  39894. return cylinder;
  39895. };
  39896. return CylinderGeometry;
  39897. }(_PrimitiveGeometry));
  39898. BABYLON.CylinderGeometry = CylinderGeometry;
  39899. /**
  39900. * Creates a new torus geometry
  39901. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39902. */
  39903. var TorusGeometry = /** @class */ (function (_super) {
  39904. __extends(TorusGeometry, _super);
  39905. /**
  39906. * Creates a new torus geometry
  39907. * @param id defines the unique ID of the geometry
  39908. * @param scene defines the hosting scene
  39909. * @param diameter defines the diameter of the torus
  39910. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39911. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39912. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39913. * @param mesh defines the hosting mesh (can be null)
  39914. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39915. */
  39916. function TorusGeometry(id, scene,
  39917. /**
  39918. * Defines the diameter of the torus
  39919. */
  39920. diameter,
  39921. /**
  39922. * Defines the thickness of the torus (ie. internal diameter)
  39923. */
  39924. thickness,
  39925. /**
  39926. * Defines the tesselation factor to apply to the torus
  39927. */
  39928. tessellation, canBeRegenerated, mesh,
  39929. /**
  39930. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39931. */
  39932. side) {
  39933. if (mesh === void 0) { mesh = null; }
  39934. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39935. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39936. _this.diameter = diameter;
  39937. _this.thickness = thickness;
  39938. _this.tessellation = tessellation;
  39939. _this.side = side;
  39940. return _this;
  39941. }
  39942. /** @hidden */
  39943. TorusGeometry.prototype._regenerateVertexData = function () {
  39944. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39945. };
  39946. TorusGeometry.prototype.copy = function (id) {
  39947. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39948. };
  39949. TorusGeometry.prototype.serialize = function () {
  39950. var serializationObject = _super.prototype.serialize.call(this);
  39951. serializationObject.diameter = this.diameter;
  39952. serializationObject.thickness = this.thickness;
  39953. serializationObject.tessellation = this.tessellation;
  39954. return serializationObject;
  39955. };
  39956. TorusGeometry.Parse = function (parsedTorus, scene) {
  39957. if (scene.getGeometryByID(parsedTorus.id)) {
  39958. return null; // null since geometry could be something else than a torus...
  39959. }
  39960. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39961. if (BABYLON.Tags) {
  39962. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39963. }
  39964. scene.pushGeometry(torus, true);
  39965. return torus;
  39966. };
  39967. return TorusGeometry;
  39968. }(_PrimitiveGeometry));
  39969. BABYLON.TorusGeometry = TorusGeometry;
  39970. /**
  39971. * Creates a new ground geometry
  39972. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39973. */
  39974. var GroundGeometry = /** @class */ (function (_super) {
  39975. __extends(GroundGeometry, _super);
  39976. /**
  39977. * Creates a new ground geometry
  39978. * @param id defines the unique ID of the geometry
  39979. * @param scene defines the hosting scene
  39980. * @param width defines the width of the ground
  39981. * @param height defines the height of the ground
  39982. * @param subdivisions defines the subdivisions to apply to the ground
  39983. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39984. * @param mesh defines the hosting mesh (can be null)
  39985. */
  39986. function GroundGeometry(id, scene,
  39987. /**
  39988. * Defines the width of the ground
  39989. */
  39990. width,
  39991. /**
  39992. * Defines the height of the ground
  39993. */
  39994. height,
  39995. /**
  39996. * Defines the subdivisions to apply to the ground
  39997. */
  39998. subdivisions, canBeRegenerated, mesh) {
  39999. if (mesh === void 0) { mesh = null; }
  40000. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40001. _this.width = width;
  40002. _this.height = height;
  40003. _this.subdivisions = subdivisions;
  40004. return _this;
  40005. }
  40006. /** @hidden */
  40007. GroundGeometry.prototype._regenerateVertexData = function () {
  40008. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40009. };
  40010. GroundGeometry.prototype.copy = function (id) {
  40011. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40012. };
  40013. GroundGeometry.prototype.serialize = function () {
  40014. var serializationObject = _super.prototype.serialize.call(this);
  40015. serializationObject.width = this.width;
  40016. serializationObject.height = this.height;
  40017. serializationObject.subdivisions = this.subdivisions;
  40018. return serializationObject;
  40019. };
  40020. GroundGeometry.Parse = function (parsedGround, scene) {
  40021. if (scene.getGeometryByID(parsedGround.id)) {
  40022. return null; // null since geometry could be something else than a ground...
  40023. }
  40024. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40025. if (BABYLON.Tags) {
  40026. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40027. }
  40028. scene.pushGeometry(ground, true);
  40029. return ground;
  40030. };
  40031. return GroundGeometry;
  40032. }(_PrimitiveGeometry));
  40033. BABYLON.GroundGeometry = GroundGeometry;
  40034. /**
  40035. * Creates a tiled ground geometry
  40036. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40037. */
  40038. var TiledGroundGeometry = /** @class */ (function (_super) {
  40039. __extends(TiledGroundGeometry, _super);
  40040. /**
  40041. * Creates a tiled ground geometry
  40042. * @param id defines the unique ID of the geometry
  40043. * @param scene defines the hosting scene
  40044. * @param xmin defines the minimum value on X axis
  40045. * @param zmin defines the minimum value on Z axis
  40046. * @param xmax defines the maximum value on X axis
  40047. * @param zmax defines the maximum value on Z axis
  40048. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40049. * @param precision defines the precision to use when computing the tiles
  40050. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40051. * @param mesh defines the hosting mesh (can be null)
  40052. */
  40053. function TiledGroundGeometry(id, scene,
  40054. /**
  40055. * Defines the minimum value on X axis
  40056. */
  40057. xmin,
  40058. /**
  40059. * Defines the minimum value on Z axis
  40060. */
  40061. zmin,
  40062. /**
  40063. * Defines the maximum value on X axis
  40064. */
  40065. xmax,
  40066. /**
  40067. * Defines the maximum value on Z axis
  40068. */
  40069. zmax,
  40070. /**
  40071. * Defines the subdivisions to apply to the ground
  40072. */
  40073. subdivisions,
  40074. /**
  40075. * Defines the precision to use when computing the tiles
  40076. */
  40077. precision, canBeRegenerated, mesh) {
  40078. if (mesh === void 0) { mesh = null; }
  40079. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40080. _this.xmin = xmin;
  40081. _this.zmin = zmin;
  40082. _this.xmax = xmax;
  40083. _this.zmax = zmax;
  40084. _this.subdivisions = subdivisions;
  40085. _this.precision = precision;
  40086. return _this;
  40087. }
  40088. /** @hidden */
  40089. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40090. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40091. };
  40092. TiledGroundGeometry.prototype.copy = function (id) {
  40093. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40094. };
  40095. return TiledGroundGeometry;
  40096. }(_PrimitiveGeometry));
  40097. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40098. /**
  40099. * Creates a plane geometry
  40100. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40101. */
  40102. var PlaneGeometry = /** @class */ (function (_super) {
  40103. __extends(PlaneGeometry, _super);
  40104. /**
  40105. * Creates a plane geometry
  40106. * @param id defines the unique ID of the geometry
  40107. * @param scene defines the hosting scene
  40108. * @param size defines the size of the plane (width === height)
  40109. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40110. * @param mesh defines the hosting mesh (can be null)
  40111. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40112. */
  40113. function PlaneGeometry(id, scene,
  40114. /**
  40115. * Defines the size of the plane (width === height)
  40116. */
  40117. size, canBeRegenerated, mesh,
  40118. /**
  40119. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40120. */
  40121. side) {
  40122. if (mesh === void 0) { mesh = null; }
  40123. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40124. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40125. _this.size = size;
  40126. _this.side = side;
  40127. return _this;
  40128. }
  40129. /** @hidden */
  40130. PlaneGeometry.prototype._regenerateVertexData = function () {
  40131. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40132. };
  40133. PlaneGeometry.prototype.copy = function (id) {
  40134. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40135. };
  40136. PlaneGeometry.prototype.serialize = function () {
  40137. var serializationObject = _super.prototype.serialize.call(this);
  40138. serializationObject.size = this.size;
  40139. return serializationObject;
  40140. };
  40141. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40142. if (scene.getGeometryByID(parsedPlane.id)) {
  40143. return null; // null since geometry could be something else than a ground...
  40144. }
  40145. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40146. if (BABYLON.Tags) {
  40147. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40148. }
  40149. scene.pushGeometry(plane, true);
  40150. return plane;
  40151. };
  40152. return PlaneGeometry;
  40153. }(_PrimitiveGeometry));
  40154. BABYLON.PlaneGeometry = PlaneGeometry;
  40155. /**
  40156. * Creates a torus knot geometry
  40157. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40158. */
  40159. var TorusKnotGeometry = /** @class */ (function (_super) {
  40160. __extends(TorusKnotGeometry, _super);
  40161. /**
  40162. * Creates a torus knot geometry
  40163. * @param id defines the unique ID of the geometry
  40164. * @param scene defines the hosting scene
  40165. * @param radius defines the radius of the torus knot
  40166. * @param tube defines the thickness of the torus knot tube
  40167. * @param radialSegments defines the number of radial segments
  40168. * @param tubularSegments defines the number of tubular segments
  40169. * @param p defines the first number of windings
  40170. * @param q defines the second number of windings
  40171. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40172. * @param mesh defines the hosting mesh (can be null)
  40173. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40174. */
  40175. function TorusKnotGeometry(id, scene,
  40176. /**
  40177. * Defines the radius of the torus knot
  40178. */
  40179. radius,
  40180. /**
  40181. * Defines the thickness of the torus knot tube
  40182. */
  40183. tube,
  40184. /**
  40185. * Defines the number of radial segments
  40186. */
  40187. radialSegments,
  40188. /**
  40189. * Defines the number of tubular segments
  40190. */
  40191. tubularSegments,
  40192. /**
  40193. * Defines the first number of windings
  40194. */
  40195. p,
  40196. /**
  40197. * Defines the second number of windings
  40198. */
  40199. q, canBeRegenerated, mesh,
  40200. /**
  40201. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40202. */
  40203. side) {
  40204. if (mesh === void 0) { mesh = null; }
  40205. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40206. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40207. _this.radius = radius;
  40208. _this.tube = tube;
  40209. _this.radialSegments = radialSegments;
  40210. _this.tubularSegments = tubularSegments;
  40211. _this.p = p;
  40212. _this.q = q;
  40213. _this.side = side;
  40214. return _this;
  40215. }
  40216. /** @hidden */
  40217. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40218. 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 });
  40219. };
  40220. TorusKnotGeometry.prototype.copy = function (id) {
  40221. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40222. };
  40223. TorusKnotGeometry.prototype.serialize = function () {
  40224. var serializationObject = _super.prototype.serialize.call(this);
  40225. serializationObject.radius = this.radius;
  40226. serializationObject.tube = this.tube;
  40227. serializationObject.radialSegments = this.radialSegments;
  40228. serializationObject.tubularSegments = this.tubularSegments;
  40229. serializationObject.p = this.p;
  40230. serializationObject.q = this.q;
  40231. return serializationObject;
  40232. };
  40233. ;
  40234. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40235. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40236. return null; // null since geometry could be something else than a ground...
  40237. }
  40238. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40239. if (BABYLON.Tags) {
  40240. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40241. }
  40242. scene.pushGeometry(torusKnot, true);
  40243. return torusKnot;
  40244. };
  40245. return TorusKnotGeometry;
  40246. }(_PrimitiveGeometry));
  40247. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40248. //}
  40249. })(BABYLON || (BABYLON = {}));
  40250. //# sourceMappingURL=babylon.geometry.js.map
  40251. var BABYLON;
  40252. (function (BABYLON) {
  40253. /**
  40254. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40255. */
  40256. var PerformanceMonitor = /** @class */ (function () {
  40257. /**
  40258. * constructor
  40259. * @param frameSampleSize The number of samples required to saturate the sliding window
  40260. */
  40261. function PerformanceMonitor(frameSampleSize) {
  40262. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40263. this._enabled = true;
  40264. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40265. }
  40266. /**
  40267. * Samples current frame
  40268. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40269. */
  40270. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40271. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40272. if (!this._enabled)
  40273. return;
  40274. if (this._lastFrameTimeMs != null) {
  40275. var dt = timeMs - this._lastFrameTimeMs;
  40276. this._rollingFrameTime.add(dt);
  40277. }
  40278. this._lastFrameTimeMs = timeMs;
  40279. };
  40280. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40281. /**
  40282. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40283. * @return Average frame time in milliseconds
  40284. */
  40285. get: function () {
  40286. return this._rollingFrameTime.average;
  40287. },
  40288. enumerable: true,
  40289. configurable: true
  40290. });
  40291. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40292. /**
  40293. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40294. * @return Frame time variance in milliseconds squared
  40295. */
  40296. get: function () {
  40297. return this._rollingFrameTime.variance;
  40298. },
  40299. enumerable: true,
  40300. configurable: true
  40301. });
  40302. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40303. /**
  40304. * Returns the frame time of the most recent frame
  40305. * @return Frame time in milliseconds
  40306. */
  40307. get: function () {
  40308. return this._rollingFrameTime.history(0);
  40309. },
  40310. enumerable: true,
  40311. configurable: true
  40312. });
  40313. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40314. /**
  40315. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40316. * @return Framerate in frames per second
  40317. */
  40318. get: function () {
  40319. return 1000.0 / this._rollingFrameTime.average;
  40320. },
  40321. enumerable: true,
  40322. configurable: true
  40323. });
  40324. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40325. /**
  40326. * Returns the average framerate in frames per second using the most recent frame time
  40327. * @return Framerate in frames per second
  40328. */
  40329. get: function () {
  40330. var history = this._rollingFrameTime.history(0);
  40331. if (history === 0) {
  40332. return 0;
  40333. }
  40334. return 1000.0 / history;
  40335. },
  40336. enumerable: true,
  40337. configurable: true
  40338. });
  40339. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40340. /**
  40341. * Returns true if enough samples have been taken to completely fill the sliding window
  40342. * @return true if saturated
  40343. */
  40344. get: function () {
  40345. return this._rollingFrameTime.isSaturated();
  40346. },
  40347. enumerable: true,
  40348. configurable: true
  40349. });
  40350. /**
  40351. * Enables contributions to the sliding window sample set
  40352. */
  40353. PerformanceMonitor.prototype.enable = function () {
  40354. this._enabled = true;
  40355. };
  40356. /**
  40357. * Disables contributions to the sliding window sample set
  40358. * Samples will not be interpolated over the disabled period
  40359. */
  40360. PerformanceMonitor.prototype.disable = function () {
  40361. this._enabled = false;
  40362. //clear last sample to avoid interpolating over the disabled period when next enabled
  40363. this._lastFrameTimeMs = null;
  40364. };
  40365. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40366. /**
  40367. * Returns true if sampling is enabled
  40368. * @return true if enabled
  40369. */
  40370. get: function () {
  40371. return this._enabled;
  40372. },
  40373. enumerable: true,
  40374. configurable: true
  40375. });
  40376. /**
  40377. * Resets performance monitor
  40378. */
  40379. PerformanceMonitor.prototype.reset = function () {
  40380. //clear last sample to avoid interpolating over the disabled period when next enabled
  40381. this._lastFrameTimeMs = null;
  40382. //wipe record
  40383. this._rollingFrameTime.reset();
  40384. };
  40385. return PerformanceMonitor;
  40386. }());
  40387. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40388. /**
  40389. * RollingAverage
  40390. *
  40391. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40392. */
  40393. var RollingAverage = /** @class */ (function () {
  40394. /**
  40395. * constructor
  40396. * @param length The number of samples required to saturate the sliding window
  40397. */
  40398. function RollingAverage(length) {
  40399. this._samples = new Array(length);
  40400. this.reset();
  40401. }
  40402. /**
  40403. * Adds a sample to the sample set
  40404. * @param v The sample value
  40405. */
  40406. RollingAverage.prototype.add = function (v) {
  40407. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40408. var delta;
  40409. //we need to check if we've already wrapped round
  40410. if (this.isSaturated()) {
  40411. //remove bottom of stack from mean
  40412. var bottomValue = this._samples[this._pos];
  40413. delta = bottomValue - this.average;
  40414. this.average -= delta / (this._sampleCount - 1);
  40415. this._m2 -= delta * (bottomValue - this.average);
  40416. }
  40417. else {
  40418. this._sampleCount++;
  40419. }
  40420. //add new value to mean
  40421. delta = v - this.average;
  40422. this.average += delta / (this._sampleCount);
  40423. this._m2 += delta * (v - this.average);
  40424. //set the new variance
  40425. this.variance = this._m2 / (this._sampleCount - 1);
  40426. this._samples[this._pos] = v;
  40427. this._pos++;
  40428. this._pos %= this._samples.length; //positive wrap around
  40429. };
  40430. /**
  40431. * Returns previously added values or null if outside of history or outside the sliding window domain
  40432. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40433. * @return Value previously recorded with add() or null if outside of range
  40434. */
  40435. RollingAverage.prototype.history = function (i) {
  40436. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40437. return 0;
  40438. }
  40439. var i0 = this._wrapPosition(this._pos - 1.0);
  40440. return this._samples[this._wrapPosition(i0 - i)];
  40441. };
  40442. /**
  40443. * Returns true if enough samples have been taken to completely fill the sliding window
  40444. * @return true if sample-set saturated
  40445. */
  40446. RollingAverage.prototype.isSaturated = function () {
  40447. return this._sampleCount >= this._samples.length;
  40448. };
  40449. /**
  40450. * Resets the rolling average (equivalent to 0 samples taken so far)
  40451. */
  40452. RollingAverage.prototype.reset = function () {
  40453. this.average = 0;
  40454. this.variance = 0;
  40455. this._sampleCount = 0;
  40456. this._pos = 0;
  40457. this._m2 = 0;
  40458. };
  40459. /**
  40460. * Wraps a value around the sample range boundaries
  40461. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40462. * @return Wrapped position in sample range
  40463. */
  40464. RollingAverage.prototype._wrapPosition = function (i) {
  40465. var max = this._samples.length;
  40466. return ((i % max) + max) % max;
  40467. };
  40468. return RollingAverage;
  40469. }());
  40470. BABYLON.RollingAverage = RollingAverage;
  40471. })(BABYLON || (BABYLON = {}));
  40472. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40473. var BABYLON;
  40474. (function (BABYLON) {
  40475. /**
  40476. * "Static Class" containing the most commonly used helper while dealing with material for
  40477. * rendering purpose.
  40478. *
  40479. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40480. *
  40481. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40482. */
  40483. var MaterialHelper = /** @class */ (function () {
  40484. function MaterialHelper() {
  40485. }
  40486. /**
  40487. * Bind the current view position to an effect.
  40488. * @param effect The effect to be bound
  40489. * @param scene The scene the eyes position is used from
  40490. */
  40491. MaterialHelper.BindEyePosition = function (effect, scene) {
  40492. if (scene._forcedViewPosition) {
  40493. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40494. return;
  40495. }
  40496. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40497. };
  40498. /**
  40499. * Helps preparing the defines values about the UVs in used in the effect.
  40500. * UVs are shared as much as we can accross chanels in the shaders.
  40501. * @param texture The texture we are preparing the UVs for
  40502. * @param defines The defines to update
  40503. * @param key The chanel key "diffuse", "specular"... used in the shader
  40504. */
  40505. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40506. defines._needUVs = true;
  40507. defines[key] = true;
  40508. if (texture.getTextureMatrix().isIdentity(true)) {
  40509. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40510. if (texture.coordinatesIndex === 0) {
  40511. defines["MAINUV1"] = true;
  40512. }
  40513. else {
  40514. defines["MAINUV2"] = true;
  40515. }
  40516. }
  40517. else {
  40518. defines[key + "DIRECTUV"] = 0;
  40519. }
  40520. };
  40521. /**
  40522. * Binds a texture matrix value to its corrsponding uniform
  40523. * @param texture The texture to bind the matrix for
  40524. * @param uniformBuffer The uniform buffer receivin the data
  40525. * @param key The chanel key "diffuse", "specular"... used in the shader
  40526. */
  40527. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40528. var matrix = texture.getTextureMatrix();
  40529. if (!matrix.isIdentity(true)) {
  40530. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40531. }
  40532. };
  40533. /**
  40534. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40535. * @param mesh defines the current mesh
  40536. * @param scene defines the current scene
  40537. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40538. * @param pointsCloud defines if point cloud rendering has to be turned on
  40539. * @param fogEnabled defines if fog has to be turned on
  40540. * @param alphaTest defines if alpha testing has to be turned on
  40541. * @param defines defines the current list of defines
  40542. */
  40543. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40544. if (defines._areMiscDirty) {
  40545. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40546. defines["POINTSIZE"] = pointsCloud;
  40547. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40548. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40549. defines["ALPHATEST"] = alphaTest;
  40550. }
  40551. };
  40552. /**
  40553. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40554. * @param scene defines the current scene
  40555. * @param engine defines the current engine
  40556. * @param defines specifies the list of active defines
  40557. * @param useInstances defines if instances have to be turned on
  40558. * @param useClipPlane defines if clip plane have to be turned on
  40559. */
  40560. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40561. if (useClipPlane === void 0) { useClipPlane = null; }
  40562. var changed = false;
  40563. var useClipPlane1 = false;
  40564. var useClipPlane2 = false;
  40565. var useClipPlane3 = false;
  40566. var useClipPlane4 = false;
  40567. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40568. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40569. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40570. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40571. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40572. defines["CLIPPLANE"] = useClipPlane1;
  40573. changed = true;
  40574. }
  40575. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40576. defines["CLIPPLANE2"] = useClipPlane2;
  40577. changed = true;
  40578. }
  40579. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40580. defines["CLIPPLANE3"] = useClipPlane3;
  40581. changed = true;
  40582. }
  40583. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40584. defines["CLIPPLANE4"] = useClipPlane4;
  40585. changed = true;
  40586. }
  40587. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40588. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40589. changed = true;
  40590. }
  40591. if (defines["INSTANCES"] !== useInstances) {
  40592. defines["INSTANCES"] = useInstances;
  40593. changed = true;
  40594. }
  40595. if (changed) {
  40596. defines.markAsUnprocessed();
  40597. }
  40598. };
  40599. /**
  40600. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40601. * @param mesh The mesh containing the geometry data we will draw
  40602. * @param defines The defines to update
  40603. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40604. * @param useBones Precise whether bones should be used or not (override mesh info)
  40605. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40606. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40607. * @returns false if defines are considered not dirty and have not been checked
  40608. */
  40609. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40610. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40611. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40612. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40613. return false;
  40614. }
  40615. defines._normals = defines._needNormals;
  40616. defines._uvs = defines._needUVs;
  40617. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40618. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40619. defines["TANGENT"] = true;
  40620. }
  40621. if (defines._needUVs) {
  40622. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40623. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40624. }
  40625. else {
  40626. defines["UV1"] = false;
  40627. defines["UV2"] = false;
  40628. }
  40629. if (useVertexColor) {
  40630. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40631. defines["VERTEXCOLOR"] = hasVertexColors;
  40632. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40633. }
  40634. if (useBones) {
  40635. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40636. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40637. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40638. }
  40639. else {
  40640. defines["NUM_BONE_INFLUENCERS"] = 0;
  40641. defines["BonesPerMesh"] = 0;
  40642. }
  40643. }
  40644. if (useMorphTargets) {
  40645. var manager = mesh.morphTargetManager;
  40646. if (manager) {
  40647. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40648. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40649. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40650. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40651. }
  40652. else {
  40653. defines["MORPHTARGETS_TANGENT"] = false;
  40654. defines["MORPHTARGETS_NORMAL"] = false;
  40655. defines["MORPHTARGETS"] = false;
  40656. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40657. }
  40658. }
  40659. return true;
  40660. };
  40661. /**
  40662. * Prepares the defines related to the light information passed in parameter
  40663. * @param scene The scene we are intending to draw
  40664. * @param mesh The mesh the effect is compiling for
  40665. * @param defines The defines to update
  40666. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40667. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40668. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40669. * @returns true if normals will be required for the rest of the effect
  40670. */
  40671. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40672. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40673. if (disableLighting === void 0) { disableLighting = false; }
  40674. if (!defines._areLightsDirty) {
  40675. return defines._needNormals;
  40676. }
  40677. var lightIndex = 0;
  40678. var needNormals = false;
  40679. var needRebuild = false;
  40680. var lightmapMode = false;
  40681. var shadowEnabled = false;
  40682. var specularEnabled = false;
  40683. if (scene.lightsEnabled && !disableLighting) {
  40684. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40685. var light = _a[_i];
  40686. needNormals = true;
  40687. if (defines["LIGHT" + lightIndex] === undefined) {
  40688. needRebuild = true;
  40689. }
  40690. defines["LIGHT" + lightIndex] = true;
  40691. defines["SPOTLIGHT" + lightIndex] = false;
  40692. defines["HEMILIGHT" + lightIndex] = false;
  40693. defines["POINTLIGHT" + lightIndex] = false;
  40694. defines["DIRLIGHT" + lightIndex] = false;
  40695. light.prepareLightSpecificDefines(defines, lightIndex);
  40696. // FallOff.
  40697. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40698. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40699. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40700. switch (light.falloffType) {
  40701. case BABYLON.Light.FALLOFF_GLTF:
  40702. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40703. break;
  40704. case BABYLON.Light.FALLOFF_PHYSICAL:
  40705. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40706. break;
  40707. case BABYLON.Light.FALLOFF_STANDARD:
  40708. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40709. break;
  40710. }
  40711. // Specular
  40712. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40713. specularEnabled = true;
  40714. }
  40715. // Shadows
  40716. defines["SHADOW" + lightIndex] = false;
  40717. defines["SHADOWPCF" + lightIndex] = false;
  40718. defines["SHADOWPCSS" + lightIndex] = false;
  40719. defines["SHADOWPOISSON" + lightIndex] = false;
  40720. defines["SHADOWESM" + lightIndex] = false;
  40721. defines["SHADOWCUBE" + lightIndex] = false;
  40722. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40723. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40724. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40725. var shadowGenerator = light.getShadowGenerator();
  40726. if (shadowGenerator) {
  40727. var shadowMap = shadowGenerator.getShadowMap();
  40728. if (shadowMap) {
  40729. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40730. shadowEnabled = true;
  40731. shadowGenerator.prepareDefines(defines, lightIndex);
  40732. }
  40733. }
  40734. }
  40735. }
  40736. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40737. lightmapMode = true;
  40738. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40739. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40740. }
  40741. else {
  40742. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40743. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40744. }
  40745. lightIndex++;
  40746. if (lightIndex === maxSimultaneousLights)
  40747. break;
  40748. }
  40749. }
  40750. defines["SPECULARTERM"] = specularEnabled;
  40751. defines["SHADOWS"] = shadowEnabled;
  40752. // Resetting all other lights if any
  40753. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40754. if (defines["LIGHT" + index] !== undefined) {
  40755. defines["LIGHT" + index] = false;
  40756. defines["HEMILIGHT" + lightIndex] = false;
  40757. defines["POINTLIGHT" + lightIndex] = false;
  40758. defines["DIRLIGHT" + lightIndex] = false;
  40759. defines["SPOTLIGHT" + lightIndex] = false;
  40760. defines["SHADOW" + lightIndex] = false;
  40761. }
  40762. }
  40763. var caps = scene.getEngine().getCaps();
  40764. if (defines["SHADOWFLOAT"] === undefined) {
  40765. needRebuild = true;
  40766. }
  40767. defines["SHADOWFLOAT"] = shadowEnabled &&
  40768. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40769. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40770. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40771. if (needRebuild) {
  40772. defines.rebuild();
  40773. }
  40774. return needNormals;
  40775. };
  40776. /**
  40777. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40778. * that won t be acctive due to defines being turned off.
  40779. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40780. * @param samplersList The samplers list
  40781. * @param defines The defines helping in the list generation
  40782. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40783. */
  40784. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40785. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40786. var uniformsList;
  40787. var uniformBuffersList = null;
  40788. if (uniformsListOrOptions.uniformsNames) {
  40789. var options = uniformsListOrOptions;
  40790. uniformsList = options.uniformsNames;
  40791. uniformBuffersList = options.uniformBuffersNames;
  40792. samplersList = options.samplers;
  40793. defines = options.defines;
  40794. maxSimultaneousLights = options.maxSimultaneousLights;
  40795. }
  40796. else {
  40797. uniformsList = uniformsListOrOptions;
  40798. if (!samplersList) {
  40799. samplersList = [];
  40800. }
  40801. }
  40802. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40803. if (!defines["LIGHT" + lightIndex]) {
  40804. break;
  40805. }
  40806. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40807. if (uniformBuffersList) {
  40808. uniformBuffersList.push("Light" + lightIndex);
  40809. }
  40810. samplersList.push("shadowSampler" + lightIndex);
  40811. samplersList.push("depthSampler" + lightIndex);
  40812. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40813. samplersList.push("projectionLightSampler" + lightIndex);
  40814. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40815. }
  40816. }
  40817. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40818. uniformsList.push("morphTargetInfluences");
  40819. }
  40820. };
  40821. /**
  40822. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40823. * @param defines The defines to update while falling back
  40824. * @param fallbacks The authorized effect fallbacks
  40825. * @param maxSimultaneousLights The maximum number of lights allowed
  40826. * @param rank the current rank of the Effect
  40827. * @returns The newly affected rank
  40828. */
  40829. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40830. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40831. if (rank === void 0) { rank = 0; }
  40832. var lightFallbackRank = 0;
  40833. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40834. if (!defines["LIGHT" + lightIndex]) {
  40835. break;
  40836. }
  40837. if (lightIndex > 0) {
  40838. lightFallbackRank = rank + lightIndex;
  40839. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  40840. }
  40841. if (!defines["SHADOWS"]) {
  40842. if (defines["SHADOW" + lightIndex]) {
  40843. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  40844. }
  40845. if (defines["SHADOWPCF" + lightIndex]) {
  40846. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  40847. }
  40848. if (defines["SHADOWPCSS" + lightIndex]) {
  40849. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  40850. }
  40851. if (defines["SHADOWPOISSON" + lightIndex]) {
  40852. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  40853. }
  40854. if (defines["SHADOWESM" + lightIndex]) {
  40855. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  40856. }
  40857. }
  40858. }
  40859. return lightFallbackRank++;
  40860. };
  40861. /**
  40862. * Prepares the list of attributes required for morph targets according to the effect defines.
  40863. * @param attribs The current list of supported attribs
  40864. * @param mesh The mesh to prepare the morph targets attributes for
  40865. * @param defines The current Defines of the effect
  40866. */
  40867. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  40868. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  40869. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  40870. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  40871. var manager = mesh.morphTargetManager;
  40872. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  40873. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  40874. for (var index = 0; index < influencers; index++) {
  40875. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  40876. if (normal) {
  40877. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  40878. }
  40879. if (tangent) {
  40880. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  40881. }
  40882. if (attribs.length > maxAttributesCount) {
  40883. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  40884. }
  40885. }
  40886. }
  40887. };
  40888. /**
  40889. * Prepares the list of attributes required for bones according to the effect defines.
  40890. * @param attribs The current list of supported attribs
  40891. * @param mesh The mesh to prepare the bones attributes for
  40892. * @param defines The current Defines of the effect
  40893. * @param fallbacks The current efffect fallback strategy
  40894. */
  40895. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  40896. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  40897. fallbacks.addCPUSkinningFallback(0, mesh);
  40898. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40899. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40900. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  40901. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40902. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40903. }
  40904. }
  40905. };
  40906. /**
  40907. * Prepares the list of attributes required for instances according to the effect defines.
  40908. * @param attribs The current list of supported attribs
  40909. * @param defines The current Defines of the effect
  40910. */
  40911. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  40912. if (defines["INSTANCES"]) {
  40913. attribs.push("world0");
  40914. attribs.push("world1");
  40915. attribs.push("world2");
  40916. attribs.push("world3");
  40917. }
  40918. };
  40919. /**
  40920. * Binds the light shadow information to the effect for the given mesh.
  40921. * @param light The light containing the generator
  40922. * @param scene The scene the lights belongs to
  40923. * @param mesh The mesh we are binding the information to render
  40924. * @param lightIndex The light index in the effect used to render the mesh
  40925. * @param effect The effect we are binding the data to
  40926. */
  40927. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  40928. if (light.shadowEnabled && mesh.receiveShadows) {
  40929. var shadowGenerator = light.getShadowGenerator();
  40930. if (shadowGenerator) {
  40931. shadowGenerator.bindShadowLight(lightIndex, effect);
  40932. }
  40933. }
  40934. };
  40935. /**
  40936. * Binds the light information to the effect.
  40937. * @param light The light containing the generator
  40938. * @param effect The effect we are binding the data to
  40939. * @param lightIndex The light index in the effect used to render
  40940. */
  40941. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  40942. light.transferToEffect(effect, lightIndex + "");
  40943. };
  40944. /**
  40945. * Binds the lights information from the scene to the effect for the given mesh.
  40946. * @param scene The scene the lights belongs to
  40947. * @param mesh The mesh we are binding the information to render
  40948. * @param effect The effect we are binding the data to
  40949. * @param defines The generated defines for the effect
  40950. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  40951. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  40952. */
  40953. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  40954. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40955. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  40956. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  40957. for (var i = 0; i < len; i++) {
  40958. var light = mesh._lightSources[i];
  40959. var iAsString = i.toString();
  40960. var scaledIntensity = light.getScaledIntensity();
  40961. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  40962. MaterialHelper.BindLightProperties(light, effect, i);
  40963. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  40964. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  40965. if (defines["SPECULARTERM"]) {
  40966. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  40967. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  40968. }
  40969. // Shadows
  40970. if (scene.shadowsEnabled) {
  40971. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  40972. }
  40973. light._uniformBuffer.update();
  40974. }
  40975. };
  40976. /**
  40977. * Binds the fog information from the scene to the effect for the given mesh.
  40978. * @param scene The scene the lights belongs to
  40979. * @param mesh The mesh we are binding the information to render
  40980. * @param effect The effect we are binding the data to
  40981. */
  40982. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  40983. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  40984. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  40985. effect.setColor3("vFogColor", scene.fogColor);
  40986. }
  40987. };
  40988. /**
  40989. * Binds the bones information from the mesh to the effect.
  40990. * @param mesh The mesh we are binding the information to render
  40991. * @param effect The effect we are binding the data to
  40992. */
  40993. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  40994. if (!effect || !mesh) {
  40995. return;
  40996. }
  40997. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  40998. mesh.computeBonesUsingShaders = false;
  40999. }
  41000. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41001. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41002. if (matrices) {
  41003. effect.setMatrices("mBones", matrices);
  41004. }
  41005. }
  41006. };
  41007. /**
  41008. * Binds the morph targets information from the mesh to the effect.
  41009. * @param abstractMesh The mesh we are binding the information to render
  41010. * @param effect The effect we are binding the data to
  41011. */
  41012. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41013. var manager = abstractMesh.morphTargetManager;
  41014. if (!abstractMesh || !manager) {
  41015. return;
  41016. }
  41017. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41018. };
  41019. /**
  41020. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41021. * @param defines The generated defines used in the effect
  41022. * @param effect The effect we are binding the data to
  41023. * @param scene The scene we are willing to render with logarithmic scale for
  41024. */
  41025. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41026. if (defines["LOGARITHMICDEPTH"]) {
  41027. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41028. }
  41029. };
  41030. /**
  41031. * Binds the clip plane information from the scene to the effect.
  41032. * @param scene The scene the clip plane information are extracted from
  41033. * @param effect The effect we are binding the data to
  41034. */
  41035. MaterialHelper.BindClipPlane = function (effect, scene) {
  41036. if (scene.clipPlane) {
  41037. var clipPlane = scene.clipPlane;
  41038. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41039. }
  41040. if (scene.clipPlane2) {
  41041. var clipPlane = scene.clipPlane2;
  41042. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41043. }
  41044. if (scene.clipPlane3) {
  41045. var clipPlane = scene.clipPlane3;
  41046. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41047. }
  41048. if (scene.clipPlane4) {
  41049. var clipPlane = scene.clipPlane4;
  41050. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41051. }
  41052. };
  41053. return MaterialHelper;
  41054. }());
  41055. BABYLON.MaterialHelper = MaterialHelper;
  41056. })(BABYLON || (BABYLON = {}));
  41057. //# sourceMappingURL=babylon.materialHelper.js.map
  41058. var BABYLON;
  41059. (function (BABYLON) {
  41060. var PushMaterial = /** @class */ (function (_super) {
  41061. __extends(PushMaterial, _super);
  41062. function PushMaterial(name, scene) {
  41063. var _this = _super.call(this, name, scene) || this;
  41064. _this._normalMatrix = new BABYLON.Matrix();
  41065. _this.storeEffectOnSubMeshes = true;
  41066. return _this;
  41067. }
  41068. PushMaterial.prototype.getEffect = function () {
  41069. return this._activeEffect;
  41070. };
  41071. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41072. if (!mesh) {
  41073. return false;
  41074. }
  41075. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41076. return true;
  41077. }
  41078. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41079. };
  41080. /**
  41081. * Binds the given world matrix to the active effect
  41082. *
  41083. * @param world the matrix to bind
  41084. */
  41085. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41086. this._activeEffect.setMatrix("world", world);
  41087. };
  41088. /**
  41089. * Binds the given normal matrix to the active effect
  41090. *
  41091. * @param normalMatrix the matrix to bind
  41092. */
  41093. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41094. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41095. };
  41096. PushMaterial.prototype.bind = function (world, mesh) {
  41097. if (!mesh) {
  41098. return;
  41099. }
  41100. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41101. };
  41102. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41103. if (effect === void 0) { effect = null; }
  41104. _super.prototype._afterBind.call(this, mesh);
  41105. this.getScene()._cachedEffect = effect;
  41106. };
  41107. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41108. if (visibility === void 0) { visibility = 1; }
  41109. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41110. };
  41111. return PushMaterial;
  41112. }(BABYLON.Material));
  41113. BABYLON.PushMaterial = PushMaterial;
  41114. })(BABYLON || (BABYLON = {}));
  41115. //# sourceMappingURL=babylon.pushMaterial.js.map
  41116. var BABYLON;
  41117. (function (BABYLON) {
  41118. /** @hidden */
  41119. var StandardMaterialDefines = /** @class */ (function (_super) {
  41120. __extends(StandardMaterialDefines, _super);
  41121. function StandardMaterialDefines() {
  41122. var _this = _super.call(this) || this;
  41123. _this.MAINUV1 = false;
  41124. _this.MAINUV2 = false;
  41125. _this.DIFFUSE = false;
  41126. _this.DIFFUSEDIRECTUV = 0;
  41127. _this.AMBIENT = false;
  41128. _this.AMBIENTDIRECTUV = 0;
  41129. _this.OPACITY = false;
  41130. _this.OPACITYDIRECTUV = 0;
  41131. _this.OPACITYRGB = false;
  41132. _this.REFLECTION = false;
  41133. _this.EMISSIVE = false;
  41134. _this.EMISSIVEDIRECTUV = 0;
  41135. _this.SPECULAR = false;
  41136. _this.SPECULARDIRECTUV = 0;
  41137. _this.BUMP = false;
  41138. _this.BUMPDIRECTUV = 0;
  41139. _this.PARALLAX = false;
  41140. _this.PARALLAXOCCLUSION = false;
  41141. _this.SPECULAROVERALPHA = false;
  41142. _this.CLIPPLANE = false;
  41143. _this.CLIPPLANE2 = false;
  41144. _this.CLIPPLANE3 = false;
  41145. _this.CLIPPLANE4 = false;
  41146. _this.ALPHATEST = false;
  41147. _this.DEPTHPREPASS = false;
  41148. _this.ALPHAFROMDIFFUSE = false;
  41149. _this.POINTSIZE = false;
  41150. _this.FOG = false;
  41151. _this.SPECULARTERM = false;
  41152. _this.DIFFUSEFRESNEL = false;
  41153. _this.OPACITYFRESNEL = false;
  41154. _this.REFLECTIONFRESNEL = false;
  41155. _this.REFRACTIONFRESNEL = false;
  41156. _this.EMISSIVEFRESNEL = false;
  41157. _this.FRESNEL = false;
  41158. _this.NORMAL = false;
  41159. _this.UV1 = false;
  41160. _this.UV2 = false;
  41161. _this.VERTEXCOLOR = false;
  41162. _this.VERTEXALPHA = false;
  41163. _this.NUM_BONE_INFLUENCERS = 0;
  41164. _this.BonesPerMesh = 0;
  41165. _this.INSTANCES = false;
  41166. _this.GLOSSINESS = false;
  41167. _this.ROUGHNESS = false;
  41168. _this.EMISSIVEASILLUMINATION = false;
  41169. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41170. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41171. _this.LIGHTMAP = false;
  41172. _this.LIGHTMAPDIRECTUV = 0;
  41173. _this.OBJECTSPACE_NORMALMAP = false;
  41174. _this.USELIGHTMAPASSHADOWMAP = false;
  41175. _this.REFLECTIONMAP_3D = false;
  41176. _this.REFLECTIONMAP_SPHERICAL = false;
  41177. _this.REFLECTIONMAP_PLANAR = false;
  41178. _this.REFLECTIONMAP_CUBIC = false;
  41179. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41180. _this.REFLECTIONMAP_PROJECTION = false;
  41181. _this.REFLECTIONMAP_SKYBOX = false;
  41182. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41183. _this.REFLECTIONMAP_EXPLICIT = false;
  41184. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41185. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41186. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41187. _this.INVERTCUBICMAP = false;
  41188. _this.LOGARITHMICDEPTH = false;
  41189. _this.REFRACTION = false;
  41190. _this.REFRACTIONMAP_3D = false;
  41191. _this.REFLECTIONOVERALPHA = false;
  41192. _this.TWOSIDEDLIGHTING = false;
  41193. _this.SHADOWFLOAT = false;
  41194. _this.MORPHTARGETS = false;
  41195. _this.MORPHTARGETS_NORMAL = false;
  41196. _this.MORPHTARGETS_TANGENT = false;
  41197. _this.NUM_MORPH_INFLUENCERS = 0;
  41198. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41199. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41200. _this.IMAGEPROCESSING = false;
  41201. _this.VIGNETTE = false;
  41202. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41203. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41204. _this.TONEMAPPING = false;
  41205. _this.TONEMAPPING_ACES = false;
  41206. _this.CONTRAST = false;
  41207. _this.COLORCURVES = false;
  41208. _this.COLORGRADING = false;
  41209. _this.COLORGRADING3D = false;
  41210. _this.SAMPLER3DGREENDEPTH = false;
  41211. _this.SAMPLER3DBGRMAP = false;
  41212. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41213. /**
  41214. * If the reflection texture on this material is in linear color space
  41215. * @hidden
  41216. */
  41217. _this.IS_REFLECTION_LINEAR = false;
  41218. /**
  41219. * If the refraction texture on this material is in linear color space
  41220. * @hidden
  41221. */
  41222. _this.IS_REFRACTION_LINEAR = false;
  41223. _this.EXPOSURE = false;
  41224. _this.rebuild();
  41225. return _this;
  41226. }
  41227. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41228. var modes = [
  41229. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41230. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41231. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41232. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41233. ];
  41234. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41235. var mode = modes_1[_i];
  41236. this[mode] = (mode === modeToEnable);
  41237. }
  41238. };
  41239. return StandardMaterialDefines;
  41240. }(BABYLON.MaterialDefines));
  41241. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41242. var StandardMaterial = /** @class */ (function (_super) {
  41243. __extends(StandardMaterial, _super);
  41244. function StandardMaterial(name, scene) {
  41245. var _this = _super.call(this, name, scene) || this;
  41246. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41247. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41248. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41249. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41250. _this.specularPower = 64;
  41251. _this._useAlphaFromDiffuseTexture = false;
  41252. _this._useEmissiveAsIllumination = false;
  41253. _this._linkEmissiveWithDiffuse = false;
  41254. _this._useSpecularOverAlpha = false;
  41255. _this._useReflectionOverAlpha = false;
  41256. _this._disableLighting = false;
  41257. _this._useObjectSpaceNormalMap = false;
  41258. _this._useParallax = false;
  41259. _this._useParallaxOcclusion = false;
  41260. _this.parallaxScaleBias = 0.05;
  41261. _this._roughness = 0;
  41262. _this.indexOfRefraction = 0.98;
  41263. _this.invertRefractionY = true;
  41264. /**
  41265. * Defines the alpha limits in alpha test mode
  41266. */
  41267. _this.alphaCutOff = 0.4;
  41268. _this._useLightmapAsShadowmap = false;
  41269. _this._useReflectionFresnelFromSpecular = false;
  41270. _this._useGlossinessFromSpecularMapAlpha = false;
  41271. _this._maxSimultaneousLights = 4;
  41272. /**
  41273. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41274. */
  41275. _this._invertNormalMapX = false;
  41276. /**
  41277. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41278. */
  41279. _this._invertNormalMapY = false;
  41280. /**
  41281. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41282. */
  41283. _this._twoSidedLighting = false;
  41284. _this._renderTargets = new BABYLON.SmartArray(16);
  41285. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41286. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41287. // Setup the default processing configuration to the scene.
  41288. _this._attachImageProcessingConfiguration(null);
  41289. _this.getRenderTargetTextures = function () {
  41290. _this._renderTargets.reset();
  41291. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41292. _this._renderTargets.push(_this._reflectionTexture);
  41293. }
  41294. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41295. _this._renderTargets.push(_this._refractionTexture);
  41296. }
  41297. return _this._renderTargets;
  41298. };
  41299. return _this;
  41300. }
  41301. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41302. /**
  41303. * Gets the image processing configuration used either in this material.
  41304. */
  41305. get: function () {
  41306. return this._imageProcessingConfiguration;
  41307. },
  41308. /**
  41309. * Sets the Default image processing configuration used either in the this material.
  41310. *
  41311. * If sets to null, the scene one is in use.
  41312. */
  41313. set: function (value) {
  41314. this._attachImageProcessingConfiguration(value);
  41315. // Ensure the effect will be rebuilt.
  41316. this._markAllSubMeshesAsTexturesDirty();
  41317. },
  41318. enumerable: true,
  41319. configurable: true
  41320. });
  41321. /**
  41322. * Attaches a new image processing configuration to the Standard Material.
  41323. * @param configuration
  41324. */
  41325. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41326. var _this = this;
  41327. if (configuration === this._imageProcessingConfiguration) {
  41328. return;
  41329. }
  41330. // Detaches observer.
  41331. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41332. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41333. }
  41334. // Pick the scene configuration if needed.
  41335. if (!configuration) {
  41336. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41337. }
  41338. else {
  41339. this._imageProcessingConfiguration = configuration;
  41340. }
  41341. // Attaches observer.
  41342. if (this._imageProcessingConfiguration) {
  41343. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41344. _this._markAllSubMeshesAsImageProcessingDirty();
  41345. });
  41346. }
  41347. };
  41348. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41349. /**
  41350. * Gets wether the color curves effect is enabled.
  41351. */
  41352. get: function () {
  41353. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41354. },
  41355. /**
  41356. * Sets wether the color curves effect is enabled.
  41357. */
  41358. set: function (value) {
  41359. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41360. },
  41361. enumerable: true,
  41362. configurable: true
  41363. });
  41364. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41365. /**
  41366. * Gets wether the color grading effect is enabled.
  41367. */
  41368. get: function () {
  41369. return this.imageProcessingConfiguration.colorGradingEnabled;
  41370. },
  41371. /**
  41372. * Gets wether the color grading effect is enabled.
  41373. */
  41374. set: function (value) {
  41375. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41376. },
  41377. enumerable: true,
  41378. configurable: true
  41379. });
  41380. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41381. /**
  41382. * Gets wether tonemapping is enabled or not.
  41383. */
  41384. get: function () {
  41385. return this._imageProcessingConfiguration.toneMappingEnabled;
  41386. },
  41387. /**
  41388. * Sets wether tonemapping is enabled or not
  41389. */
  41390. set: function (value) {
  41391. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41392. },
  41393. enumerable: true,
  41394. configurable: true
  41395. });
  41396. ;
  41397. ;
  41398. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41399. /**
  41400. * The camera exposure used on this material.
  41401. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41402. * This corresponds to a photographic exposure.
  41403. */
  41404. get: function () {
  41405. return this._imageProcessingConfiguration.exposure;
  41406. },
  41407. /**
  41408. * The camera exposure used on this material.
  41409. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41410. * This corresponds to a photographic exposure.
  41411. */
  41412. set: function (value) {
  41413. this._imageProcessingConfiguration.exposure = value;
  41414. },
  41415. enumerable: true,
  41416. configurable: true
  41417. });
  41418. ;
  41419. ;
  41420. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41421. /**
  41422. * Gets The camera contrast used on this material.
  41423. */
  41424. get: function () {
  41425. return this._imageProcessingConfiguration.contrast;
  41426. },
  41427. /**
  41428. * Sets The camera contrast used on this material.
  41429. */
  41430. set: function (value) {
  41431. this._imageProcessingConfiguration.contrast = value;
  41432. },
  41433. enumerable: true,
  41434. configurable: true
  41435. });
  41436. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41437. /**
  41438. * Gets the Color Grading 2D Lookup Texture.
  41439. */
  41440. get: function () {
  41441. return this._imageProcessingConfiguration.colorGradingTexture;
  41442. },
  41443. /**
  41444. * Sets the Color Grading 2D Lookup Texture.
  41445. */
  41446. set: function (value) {
  41447. this._imageProcessingConfiguration.colorGradingTexture = value;
  41448. },
  41449. enumerable: true,
  41450. configurable: true
  41451. });
  41452. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41453. /**
  41454. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41455. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41456. * 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;
  41457. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41458. */
  41459. get: function () {
  41460. return this._imageProcessingConfiguration.colorCurves;
  41461. },
  41462. /**
  41463. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41464. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41465. * 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;
  41466. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41467. */
  41468. set: function (value) {
  41469. this._imageProcessingConfiguration.colorCurves = value;
  41470. },
  41471. enumerable: true,
  41472. configurable: true
  41473. });
  41474. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41475. /**
  41476. * Gets a boolean indicating that current material needs to register RTT
  41477. */
  41478. get: function () {
  41479. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41480. return true;
  41481. }
  41482. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41483. return true;
  41484. }
  41485. return false;
  41486. },
  41487. enumerable: true,
  41488. configurable: true
  41489. });
  41490. StandardMaterial.prototype.getClassName = function () {
  41491. return "StandardMaterial";
  41492. };
  41493. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41494. get: function () {
  41495. return this._useLogarithmicDepth;
  41496. },
  41497. set: function (value) {
  41498. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41499. this._markAllSubMeshesAsMiscDirty();
  41500. },
  41501. enumerable: true,
  41502. configurable: true
  41503. });
  41504. StandardMaterial.prototype.needAlphaBlending = function () {
  41505. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41506. };
  41507. StandardMaterial.prototype.needAlphaTesting = function () {
  41508. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41509. };
  41510. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41511. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41512. };
  41513. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41514. return this._diffuseTexture;
  41515. };
  41516. /**
  41517. * Child classes can use it to update shaders
  41518. */
  41519. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41520. if (useInstances === void 0) { useInstances = false; }
  41521. if (subMesh.effect && this.isFrozen) {
  41522. if (this._wasPreviouslyReady) {
  41523. return true;
  41524. }
  41525. }
  41526. if (!subMesh._materialDefines) {
  41527. subMesh._materialDefines = new StandardMaterialDefines();
  41528. }
  41529. var scene = this.getScene();
  41530. var defines = subMesh._materialDefines;
  41531. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41532. if (defines._renderId === scene.getRenderId()) {
  41533. return true;
  41534. }
  41535. }
  41536. var engine = scene.getEngine();
  41537. // Lights
  41538. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41539. // Textures
  41540. if (defines._areTexturesDirty) {
  41541. defines._needUVs = false;
  41542. defines.MAINUV1 = false;
  41543. defines.MAINUV2 = false;
  41544. if (scene.texturesEnabled) {
  41545. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41546. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41547. return false;
  41548. }
  41549. else {
  41550. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41551. }
  41552. }
  41553. else {
  41554. defines.DIFFUSE = false;
  41555. }
  41556. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41557. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41558. return false;
  41559. }
  41560. else {
  41561. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41562. }
  41563. }
  41564. else {
  41565. defines.AMBIENT = false;
  41566. }
  41567. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41568. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41569. return false;
  41570. }
  41571. else {
  41572. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41573. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41574. }
  41575. }
  41576. else {
  41577. defines.OPACITY = false;
  41578. }
  41579. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41580. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41581. return false;
  41582. }
  41583. else {
  41584. defines._needNormals = true;
  41585. defines.REFLECTION = true;
  41586. defines.ROUGHNESS = (this._roughness > 0);
  41587. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41588. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41589. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41590. switch (this._reflectionTexture.coordinatesMode) {
  41591. case BABYLON.Texture.EXPLICIT_MODE:
  41592. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41593. break;
  41594. case BABYLON.Texture.PLANAR_MODE:
  41595. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41596. break;
  41597. case BABYLON.Texture.PROJECTION_MODE:
  41598. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41599. break;
  41600. case BABYLON.Texture.SKYBOX_MODE:
  41601. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41602. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41603. break;
  41604. case BABYLON.Texture.SPHERICAL_MODE:
  41605. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41606. break;
  41607. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41608. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41609. break;
  41610. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41611. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41612. break;
  41613. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41614. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41615. break;
  41616. case BABYLON.Texture.CUBIC_MODE:
  41617. case BABYLON.Texture.INVCUBIC_MODE:
  41618. default:
  41619. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41620. break;
  41621. }
  41622. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41623. }
  41624. }
  41625. else {
  41626. defines.REFLECTION = false;
  41627. }
  41628. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41629. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41630. return false;
  41631. }
  41632. else {
  41633. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41634. }
  41635. }
  41636. else {
  41637. defines.EMISSIVE = false;
  41638. }
  41639. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41640. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41641. return false;
  41642. }
  41643. else {
  41644. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41645. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41646. }
  41647. }
  41648. else {
  41649. defines.LIGHTMAP = false;
  41650. }
  41651. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41652. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41653. return false;
  41654. }
  41655. else {
  41656. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41657. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41658. }
  41659. }
  41660. else {
  41661. defines.SPECULAR = false;
  41662. }
  41663. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41664. // Bump texure can not be not blocking.
  41665. if (!this._bumpTexture.isReady()) {
  41666. return false;
  41667. }
  41668. else {
  41669. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41670. defines.PARALLAX = this._useParallax;
  41671. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41672. }
  41673. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41674. }
  41675. else {
  41676. defines.BUMP = false;
  41677. }
  41678. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41679. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41680. return false;
  41681. }
  41682. else {
  41683. defines._needUVs = true;
  41684. defines.REFRACTION = true;
  41685. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41686. }
  41687. }
  41688. else {
  41689. defines.REFRACTION = false;
  41690. }
  41691. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41692. }
  41693. else {
  41694. defines.DIFFUSE = false;
  41695. defines.AMBIENT = false;
  41696. defines.OPACITY = false;
  41697. defines.REFLECTION = false;
  41698. defines.EMISSIVE = false;
  41699. defines.LIGHTMAP = false;
  41700. defines.BUMP = false;
  41701. defines.REFRACTION = false;
  41702. }
  41703. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41704. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41705. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41706. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41707. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41708. }
  41709. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41710. if (!this._imageProcessingConfiguration.isReady()) {
  41711. return false;
  41712. }
  41713. this._imageProcessingConfiguration.prepareDefines(defines);
  41714. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41715. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41716. }
  41717. if (defines._areFresnelDirty) {
  41718. if (StandardMaterial.FresnelEnabled) {
  41719. // Fresnel
  41720. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41721. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41722. this._reflectionFresnelParameters) {
  41723. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41724. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41725. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41726. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41727. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41728. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41729. defines._needNormals = true;
  41730. defines.FRESNEL = true;
  41731. }
  41732. }
  41733. else {
  41734. defines.FRESNEL = false;
  41735. }
  41736. }
  41737. // Misc.
  41738. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41739. // Attribs
  41740. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41741. // Values that need to be evaluated on every frame
  41742. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41743. // Get correct effect
  41744. if (defines.isDirty) {
  41745. defines.markAsProcessed();
  41746. scene.resetCachedMaterial();
  41747. // Fallbacks
  41748. var fallbacks = new BABYLON.EffectFallbacks();
  41749. if (defines.REFLECTION) {
  41750. fallbacks.addFallback(0, "REFLECTION");
  41751. }
  41752. if (defines.SPECULAR) {
  41753. fallbacks.addFallback(0, "SPECULAR");
  41754. }
  41755. if (defines.BUMP) {
  41756. fallbacks.addFallback(0, "BUMP");
  41757. }
  41758. if (defines.PARALLAX) {
  41759. fallbacks.addFallback(1, "PARALLAX");
  41760. }
  41761. if (defines.PARALLAXOCCLUSION) {
  41762. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41763. }
  41764. if (defines.SPECULAROVERALPHA) {
  41765. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41766. }
  41767. if (defines.FOG) {
  41768. fallbacks.addFallback(1, "FOG");
  41769. }
  41770. if (defines.POINTSIZE) {
  41771. fallbacks.addFallback(0, "POINTSIZE");
  41772. }
  41773. if (defines.LOGARITHMICDEPTH) {
  41774. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41775. }
  41776. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41777. if (defines.SPECULARTERM) {
  41778. fallbacks.addFallback(0, "SPECULARTERM");
  41779. }
  41780. if (defines.DIFFUSEFRESNEL) {
  41781. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41782. }
  41783. if (defines.OPACITYFRESNEL) {
  41784. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41785. }
  41786. if (defines.REFLECTIONFRESNEL) {
  41787. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41788. }
  41789. if (defines.EMISSIVEFRESNEL) {
  41790. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41791. }
  41792. if (defines.FRESNEL) {
  41793. fallbacks.addFallback(4, "FRESNEL");
  41794. }
  41795. //Attributes
  41796. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41797. if (defines.NORMAL) {
  41798. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41799. }
  41800. if (defines.UV1) {
  41801. attribs.push(BABYLON.VertexBuffer.UVKind);
  41802. }
  41803. if (defines.UV2) {
  41804. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41805. }
  41806. if (defines.VERTEXCOLOR) {
  41807. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41808. }
  41809. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41810. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41811. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41812. var shaderName = "default";
  41813. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41814. "vFogInfos", "vFogColor", "pointSize",
  41815. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41816. "mBones",
  41817. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41818. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41819. "vReflectionPosition", "vReflectionSize",
  41820. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41821. ];
  41822. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41823. var uniformBuffers = ["Material", "Scene"];
  41824. if (BABYLON.ImageProcessingConfiguration) {
  41825. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41826. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41827. }
  41828. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41829. uniformsNames: uniforms,
  41830. uniformBuffersNames: uniformBuffers,
  41831. samplers: samplers,
  41832. defines: defines,
  41833. maxSimultaneousLights: this._maxSimultaneousLights
  41834. });
  41835. if (this.customShaderNameResolve) {
  41836. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41837. }
  41838. var join = defines.toString();
  41839. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41840. attributes: attribs,
  41841. uniformsNames: uniforms,
  41842. uniformBuffersNames: uniformBuffers,
  41843. samplers: samplers,
  41844. defines: join,
  41845. fallbacks: fallbacks,
  41846. onCompiled: this.onCompiled,
  41847. onError: this.onError,
  41848. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41849. }, engine), defines);
  41850. this.buildUniformLayout();
  41851. }
  41852. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41853. return false;
  41854. }
  41855. defines._renderId = scene.getRenderId();
  41856. this._wasPreviouslyReady = true;
  41857. return true;
  41858. };
  41859. StandardMaterial.prototype.buildUniformLayout = function () {
  41860. // Order is important !
  41861. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41862. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41863. this._uniformBuffer.addUniform("opacityParts", 4);
  41864. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41865. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41866. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41867. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41868. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41869. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41870. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41871. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41872. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41873. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41874. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41875. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41876. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41877. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41878. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41879. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41880. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41881. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41882. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41883. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41884. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41885. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41886. this._uniformBuffer.addUniform("specularMatrix", 16);
  41887. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41888. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41889. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41890. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41891. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41892. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41893. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41894. this._uniformBuffer.addUniform("pointSize", 1);
  41895. this._uniformBuffer.create();
  41896. };
  41897. StandardMaterial.prototype.unbind = function () {
  41898. if (this._activeEffect) {
  41899. var needFlag = false;
  41900. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41901. this._activeEffect.setTexture("reflection2DSampler", null);
  41902. needFlag = true;
  41903. }
  41904. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41905. this._activeEffect.setTexture("refraction2DSampler", null);
  41906. needFlag = true;
  41907. }
  41908. if (needFlag) {
  41909. this._markAllSubMeshesAsTexturesDirty();
  41910. }
  41911. }
  41912. _super.prototype.unbind.call(this);
  41913. };
  41914. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41915. var scene = this.getScene();
  41916. var defines = subMesh._materialDefines;
  41917. if (!defines) {
  41918. return;
  41919. }
  41920. var effect = subMesh.effect;
  41921. if (!effect) {
  41922. return;
  41923. }
  41924. this._activeEffect = effect;
  41925. // Matrices
  41926. this.bindOnlyWorldMatrix(world);
  41927. // Normal Matrix
  41928. if (defines.OBJECTSPACE_NORMALMAP) {
  41929. world.toNormalMatrix(this._normalMatrix);
  41930. this.bindOnlyNormalMatrix(this._normalMatrix);
  41931. }
  41932. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41933. // Bones
  41934. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  41935. if (mustRebind) {
  41936. this._uniformBuffer.bindToEffect(effect, "Material");
  41937. this.bindViewProjection(effect);
  41938. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41939. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  41940. // Fresnel
  41941. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  41942. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  41943. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  41944. }
  41945. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  41946. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  41947. }
  41948. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  41949. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  41950. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  41951. }
  41952. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  41953. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  41954. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  41955. }
  41956. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  41957. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  41958. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  41959. }
  41960. }
  41961. // Textures
  41962. if (scene.texturesEnabled) {
  41963. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41964. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  41965. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  41966. if (this._diffuseTexture.hasAlpha) {
  41967. effect.setFloat("alphaCutOff", this.alphaCutOff);
  41968. }
  41969. }
  41970. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41971. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  41972. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41973. }
  41974. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41975. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41976. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41977. }
  41978. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41979. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  41980. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  41981. if (this._reflectionTexture.boundingBoxSize) {
  41982. var cubeTexture = this._reflectionTexture;
  41983. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41984. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41985. }
  41986. }
  41987. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41988. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41989. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41990. }
  41991. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41992. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41993. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41994. }
  41995. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41996. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  41997. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  41998. }
  41999. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42000. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42001. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42002. if (scene._mirroredCameraPosition) {
  42003. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42004. }
  42005. else {
  42006. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42007. }
  42008. }
  42009. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42010. var depth = 1.0;
  42011. if (!this._refractionTexture.isCube) {
  42012. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42013. if (this._refractionTexture.depth) {
  42014. depth = this._refractionTexture.depth;
  42015. }
  42016. }
  42017. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42018. }
  42019. }
  42020. // Point size
  42021. if (this.pointsCloud) {
  42022. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42023. }
  42024. if (defines.SPECULARTERM) {
  42025. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42026. }
  42027. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42028. // Diffuse
  42029. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42030. }
  42031. // Textures
  42032. if (scene.texturesEnabled) {
  42033. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42034. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42035. }
  42036. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42037. effect.setTexture("ambientSampler", this._ambientTexture);
  42038. }
  42039. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42040. effect.setTexture("opacitySampler", this._opacityTexture);
  42041. }
  42042. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42043. if (this._reflectionTexture.isCube) {
  42044. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42045. }
  42046. else {
  42047. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42048. }
  42049. }
  42050. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42051. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42052. }
  42053. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42054. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42055. }
  42056. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42057. effect.setTexture("specularSampler", this._specularTexture);
  42058. }
  42059. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42060. effect.setTexture("bumpSampler", this._bumpTexture);
  42061. }
  42062. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42063. var depth = 1.0;
  42064. if (this._refractionTexture.isCube) {
  42065. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42066. }
  42067. else {
  42068. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42069. }
  42070. }
  42071. }
  42072. // Clip plane
  42073. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42074. // Colors
  42075. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42076. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42077. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42078. }
  42079. if (mustRebind || !this.isFrozen) {
  42080. // Lights
  42081. if (scene.lightsEnabled && !this._disableLighting) {
  42082. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42083. }
  42084. // View
  42085. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42086. this.bindView(effect);
  42087. }
  42088. // Fog
  42089. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42090. // Morph targets
  42091. if (defines.NUM_MORPH_INFLUENCERS) {
  42092. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42093. }
  42094. // Log. depth
  42095. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42096. // image processing
  42097. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42098. this._imageProcessingConfiguration.bind(this._activeEffect);
  42099. }
  42100. }
  42101. this._uniformBuffer.update();
  42102. this._afterBind(mesh, this._activeEffect);
  42103. };
  42104. StandardMaterial.prototype.getAnimatables = function () {
  42105. var results = [];
  42106. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42107. results.push(this._diffuseTexture);
  42108. }
  42109. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42110. results.push(this._ambientTexture);
  42111. }
  42112. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42113. results.push(this._opacityTexture);
  42114. }
  42115. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42116. results.push(this._reflectionTexture);
  42117. }
  42118. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42119. results.push(this._emissiveTexture);
  42120. }
  42121. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42122. results.push(this._specularTexture);
  42123. }
  42124. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42125. results.push(this._bumpTexture);
  42126. }
  42127. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42128. results.push(this._lightmapTexture);
  42129. }
  42130. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42131. results.push(this._refractionTexture);
  42132. }
  42133. return results;
  42134. };
  42135. StandardMaterial.prototype.getActiveTextures = function () {
  42136. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42137. if (this._diffuseTexture) {
  42138. activeTextures.push(this._diffuseTexture);
  42139. }
  42140. if (this._ambientTexture) {
  42141. activeTextures.push(this._ambientTexture);
  42142. }
  42143. if (this._opacityTexture) {
  42144. activeTextures.push(this._opacityTexture);
  42145. }
  42146. if (this._reflectionTexture) {
  42147. activeTextures.push(this._reflectionTexture);
  42148. }
  42149. if (this._emissiveTexture) {
  42150. activeTextures.push(this._emissiveTexture);
  42151. }
  42152. if (this._specularTexture) {
  42153. activeTextures.push(this._specularTexture);
  42154. }
  42155. if (this._bumpTexture) {
  42156. activeTextures.push(this._bumpTexture);
  42157. }
  42158. if (this._lightmapTexture) {
  42159. activeTextures.push(this._lightmapTexture);
  42160. }
  42161. if (this._refractionTexture) {
  42162. activeTextures.push(this._refractionTexture);
  42163. }
  42164. return activeTextures;
  42165. };
  42166. StandardMaterial.prototype.hasTexture = function (texture) {
  42167. if (_super.prototype.hasTexture.call(this, texture)) {
  42168. return true;
  42169. }
  42170. if (this._diffuseTexture === texture) {
  42171. return true;
  42172. }
  42173. if (this._ambientTexture === texture) {
  42174. return true;
  42175. }
  42176. if (this._opacityTexture === texture) {
  42177. return true;
  42178. }
  42179. if (this._reflectionTexture === texture) {
  42180. return true;
  42181. }
  42182. if (this._emissiveTexture === texture) {
  42183. return true;
  42184. }
  42185. if (this._specularTexture === texture) {
  42186. return true;
  42187. }
  42188. if (this._bumpTexture === texture) {
  42189. return true;
  42190. }
  42191. if (this._lightmapTexture === texture) {
  42192. return true;
  42193. }
  42194. if (this._refractionTexture === texture) {
  42195. return true;
  42196. }
  42197. return false;
  42198. };
  42199. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42200. if (forceDisposeTextures) {
  42201. if (this._diffuseTexture) {
  42202. this._diffuseTexture.dispose();
  42203. }
  42204. if (this._ambientTexture) {
  42205. this._ambientTexture.dispose();
  42206. }
  42207. if (this._opacityTexture) {
  42208. this._opacityTexture.dispose();
  42209. }
  42210. if (this._reflectionTexture) {
  42211. this._reflectionTexture.dispose();
  42212. }
  42213. if (this._emissiveTexture) {
  42214. this._emissiveTexture.dispose();
  42215. }
  42216. if (this._specularTexture) {
  42217. this._specularTexture.dispose();
  42218. }
  42219. if (this._bumpTexture) {
  42220. this._bumpTexture.dispose();
  42221. }
  42222. if (this._lightmapTexture) {
  42223. this._lightmapTexture.dispose();
  42224. }
  42225. if (this._refractionTexture) {
  42226. this._refractionTexture.dispose();
  42227. }
  42228. }
  42229. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42230. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42231. }
  42232. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42233. };
  42234. StandardMaterial.prototype.clone = function (name) {
  42235. var _this = this;
  42236. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42237. result.name = name;
  42238. result.id = name;
  42239. return result;
  42240. };
  42241. StandardMaterial.prototype.serialize = function () {
  42242. return BABYLON.SerializationHelper.Serialize(this);
  42243. };
  42244. // Statics
  42245. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42246. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42247. };
  42248. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42249. get: function () {
  42250. return StandardMaterial._DiffuseTextureEnabled;
  42251. },
  42252. set: function (value) {
  42253. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42254. return;
  42255. }
  42256. StandardMaterial._DiffuseTextureEnabled = value;
  42257. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42258. },
  42259. enumerable: true,
  42260. configurable: true
  42261. });
  42262. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42263. get: function () {
  42264. return StandardMaterial._AmbientTextureEnabled;
  42265. },
  42266. set: function (value) {
  42267. if (StandardMaterial._AmbientTextureEnabled === value) {
  42268. return;
  42269. }
  42270. StandardMaterial._AmbientTextureEnabled = value;
  42271. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42272. },
  42273. enumerable: true,
  42274. configurable: true
  42275. });
  42276. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42277. get: function () {
  42278. return StandardMaterial._OpacityTextureEnabled;
  42279. },
  42280. set: function (value) {
  42281. if (StandardMaterial._OpacityTextureEnabled === value) {
  42282. return;
  42283. }
  42284. StandardMaterial._OpacityTextureEnabled = value;
  42285. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42286. },
  42287. enumerable: true,
  42288. configurable: true
  42289. });
  42290. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42291. get: function () {
  42292. return StandardMaterial._ReflectionTextureEnabled;
  42293. },
  42294. set: function (value) {
  42295. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42296. return;
  42297. }
  42298. StandardMaterial._ReflectionTextureEnabled = value;
  42299. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42300. },
  42301. enumerable: true,
  42302. configurable: true
  42303. });
  42304. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42305. get: function () {
  42306. return StandardMaterial._EmissiveTextureEnabled;
  42307. },
  42308. set: function (value) {
  42309. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42310. return;
  42311. }
  42312. StandardMaterial._EmissiveTextureEnabled = value;
  42313. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42314. },
  42315. enumerable: true,
  42316. configurable: true
  42317. });
  42318. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42319. get: function () {
  42320. return StandardMaterial._SpecularTextureEnabled;
  42321. },
  42322. set: function (value) {
  42323. if (StandardMaterial._SpecularTextureEnabled === value) {
  42324. return;
  42325. }
  42326. StandardMaterial._SpecularTextureEnabled = value;
  42327. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42328. },
  42329. enumerable: true,
  42330. configurable: true
  42331. });
  42332. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42333. get: function () {
  42334. return StandardMaterial._BumpTextureEnabled;
  42335. },
  42336. set: function (value) {
  42337. if (StandardMaterial._BumpTextureEnabled === value) {
  42338. return;
  42339. }
  42340. StandardMaterial._BumpTextureEnabled = value;
  42341. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42342. },
  42343. enumerable: true,
  42344. configurable: true
  42345. });
  42346. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42347. get: function () {
  42348. return StandardMaterial._LightmapTextureEnabled;
  42349. },
  42350. set: function (value) {
  42351. if (StandardMaterial._LightmapTextureEnabled === value) {
  42352. return;
  42353. }
  42354. StandardMaterial._LightmapTextureEnabled = value;
  42355. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42356. },
  42357. enumerable: true,
  42358. configurable: true
  42359. });
  42360. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42361. get: function () {
  42362. return StandardMaterial._RefractionTextureEnabled;
  42363. },
  42364. set: function (value) {
  42365. if (StandardMaterial._RefractionTextureEnabled === value) {
  42366. return;
  42367. }
  42368. StandardMaterial._RefractionTextureEnabled = value;
  42369. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42370. },
  42371. enumerable: true,
  42372. configurable: true
  42373. });
  42374. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42375. get: function () {
  42376. return StandardMaterial._ColorGradingTextureEnabled;
  42377. },
  42378. set: function (value) {
  42379. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42380. return;
  42381. }
  42382. StandardMaterial._ColorGradingTextureEnabled = value;
  42383. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42384. },
  42385. enumerable: true,
  42386. configurable: true
  42387. });
  42388. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42389. get: function () {
  42390. return StandardMaterial._FresnelEnabled;
  42391. },
  42392. set: function (value) {
  42393. if (StandardMaterial._FresnelEnabled === value) {
  42394. return;
  42395. }
  42396. StandardMaterial._FresnelEnabled = value;
  42397. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42398. },
  42399. enumerable: true,
  42400. configurable: true
  42401. });
  42402. // Flags used to enable or disable a type of texture for all Standard Materials
  42403. StandardMaterial._DiffuseTextureEnabled = true;
  42404. StandardMaterial._AmbientTextureEnabled = true;
  42405. StandardMaterial._OpacityTextureEnabled = true;
  42406. StandardMaterial._ReflectionTextureEnabled = true;
  42407. StandardMaterial._EmissiveTextureEnabled = true;
  42408. StandardMaterial._SpecularTextureEnabled = true;
  42409. StandardMaterial._BumpTextureEnabled = true;
  42410. StandardMaterial._LightmapTextureEnabled = true;
  42411. StandardMaterial._RefractionTextureEnabled = true;
  42412. StandardMaterial._ColorGradingTextureEnabled = true;
  42413. StandardMaterial._FresnelEnabled = true;
  42414. __decorate([
  42415. BABYLON.serializeAsTexture("diffuseTexture")
  42416. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42417. __decorate([
  42418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42419. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42420. __decorate([
  42421. BABYLON.serializeAsTexture("ambientTexture")
  42422. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42423. __decorate([
  42424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42425. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42426. __decorate([
  42427. BABYLON.serializeAsTexture("opacityTexture")
  42428. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42429. __decorate([
  42430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42431. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42432. __decorate([
  42433. BABYLON.serializeAsTexture("reflectionTexture")
  42434. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42435. __decorate([
  42436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42437. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42438. __decorate([
  42439. BABYLON.serializeAsTexture("emissiveTexture")
  42440. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42441. __decorate([
  42442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42443. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42444. __decorate([
  42445. BABYLON.serializeAsTexture("specularTexture")
  42446. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42447. __decorate([
  42448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42449. ], StandardMaterial.prototype, "specularTexture", void 0);
  42450. __decorate([
  42451. BABYLON.serializeAsTexture("bumpTexture")
  42452. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42453. __decorate([
  42454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42455. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42456. __decorate([
  42457. BABYLON.serializeAsTexture("lightmapTexture")
  42458. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42459. __decorate([
  42460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42461. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42462. __decorate([
  42463. BABYLON.serializeAsTexture("refractionTexture")
  42464. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42465. __decorate([
  42466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42467. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42468. __decorate([
  42469. BABYLON.serializeAsColor3("ambient")
  42470. ], StandardMaterial.prototype, "ambientColor", void 0);
  42471. __decorate([
  42472. BABYLON.serializeAsColor3("diffuse")
  42473. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42474. __decorate([
  42475. BABYLON.serializeAsColor3("specular")
  42476. ], StandardMaterial.prototype, "specularColor", void 0);
  42477. __decorate([
  42478. BABYLON.serializeAsColor3("emissive")
  42479. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42480. __decorate([
  42481. BABYLON.serialize()
  42482. ], StandardMaterial.prototype, "specularPower", void 0);
  42483. __decorate([
  42484. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42485. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42486. __decorate([
  42487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42488. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42489. __decorate([
  42490. BABYLON.serialize("useEmissiveAsIllumination")
  42491. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42492. __decorate([
  42493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42494. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42495. __decorate([
  42496. BABYLON.serialize("linkEmissiveWithDiffuse")
  42497. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42498. __decorate([
  42499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42500. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42501. __decorate([
  42502. BABYLON.serialize("useSpecularOverAlpha")
  42503. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42504. __decorate([
  42505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42506. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42507. __decorate([
  42508. BABYLON.serialize("useReflectionOverAlpha")
  42509. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42510. __decorate([
  42511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42512. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42513. __decorate([
  42514. BABYLON.serialize("disableLighting")
  42515. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42516. __decorate([
  42517. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42518. ], StandardMaterial.prototype, "disableLighting", void 0);
  42519. __decorate([
  42520. BABYLON.serialize("useObjectSpaceNormalMap")
  42521. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42522. __decorate([
  42523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42524. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42525. __decorate([
  42526. BABYLON.serialize("useParallax")
  42527. ], StandardMaterial.prototype, "_useParallax", void 0);
  42528. __decorate([
  42529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42530. ], StandardMaterial.prototype, "useParallax", void 0);
  42531. __decorate([
  42532. BABYLON.serialize("useParallaxOcclusion")
  42533. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42534. __decorate([
  42535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42536. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42537. __decorate([
  42538. BABYLON.serialize()
  42539. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42540. __decorate([
  42541. BABYLON.serialize("roughness")
  42542. ], StandardMaterial.prototype, "_roughness", void 0);
  42543. __decorate([
  42544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42545. ], StandardMaterial.prototype, "roughness", void 0);
  42546. __decorate([
  42547. BABYLON.serialize()
  42548. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42549. __decorate([
  42550. BABYLON.serialize()
  42551. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42552. __decorate([
  42553. BABYLON.serialize()
  42554. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42555. __decorate([
  42556. BABYLON.serialize("useLightmapAsShadowmap")
  42557. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42558. __decorate([
  42559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42560. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42561. __decorate([
  42562. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42563. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42564. __decorate([
  42565. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42566. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42567. __decorate([
  42568. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42569. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42570. __decorate([
  42571. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42572. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42573. __decorate([
  42574. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42575. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42576. __decorate([
  42577. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42578. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42579. __decorate([
  42580. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42581. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42582. __decorate([
  42583. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42584. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42585. __decorate([
  42586. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42587. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42588. __decorate([
  42589. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42590. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42591. __decorate([
  42592. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42593. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42594. __decorate([
  42595. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42596. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42597. __decorate([
  42598. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42599. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42600. __decorate([
  42601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42602. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42603. __decorate([
  42604. BABYLON.serialize("maxSimultaneousLights")
  42605. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42606. __decorate([
  42607. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42608. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42609. __decorate([
  42610. BABYLON.serialize("invertNormalMapX")
  42611. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42612. __decorate([
  42613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42614. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42615. __decorate([
  42616. BABYLON.serialize("invertNormalMapY")
  42617. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42618. __decorate([
  42619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42620. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42621. __decorate([
  42622. BABYLON.serialize("twoSidedLighting")
  42623. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42624. __decorate([
  42625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42626. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42627. __decorate([
  42628. BABYLON.serialize()
  42629. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42630. return StandardMaterial;
  42631. }(BABYLON.PushMaterial));
  42632. BABYLON.StandardMaterial = StandardMaterial;
  42633. })(BABYLON || (BABYLON = {}));
  42634. //# sourceMappingURL=babylon.standardMaterial.js.map
  42635. var BABYLON;
  42636. (function (BABYLON) {
  42637. /**
  42638. * Class representing spherical polynomial coefficients to the 3rd degree
  42639. */
  42640. var SphericalPolynomial = /** @class */ (function () {
  42641. function SphericalPolynomial() {
  42642. /**
  42643. * The x coefficients of the spherical polynomial
  42644. */
  42645. this.x = BABYLON.Vector3.Zero();
  42646. /**
  42647. * The y coefficients of the spherical polynomial
  42648. */
  42649. this.y = BABYLON.Vector3.Zero();
  42650. /**
  42651. * The z coefficients of the spherical polynomial
  42652. */
  42653. this.z = BABYLON.Vector3.Zero();
  42654. /**
  42655. * The xx coefficients of the spherical polynomial
  42656. */
  42657. this.xx = BABYLON.Vector3.Zero();
  42658. /**
  42659. * The yy coefficients of the spherical polynomial
  42660. */
  42661. this.yy = BABYLON.Vector3.Zero();
  42662. /**
  42663. * The zz coefficients of the spherical polynomial
  42664. */
  42665. this.zz = BABYLON.Vector3.Zero();
  42666. /**
  42667. * The xy coefficients of the spherical polynomial
  42668. */
  42669. this.xy = BABYLON.Vector3.Zero();
  42670. /**
  42671. * The yz coefficients of the spherical polynomial
  42672. */
  42673. this.yz = BABYLON.Vector3.Zero();
  42674. /**
  42675. * The zx coefficients of the spherical polynomial
  42676. */
  42677. this.zx = BABYLON.Vector3.Zero();
  42678. }
  42679. /**
  42680. * Adds an ambient color to the spherical polynomial
  42681. * @param color the color to add
  42682. */
  42683. SphericalPolynomial.prototype.addAmbient = function (color) {
  42684. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42685. this.xx = this.xx.add(colorVector);
  42686. this.yy = this.yy.add(colorVector);
  42687. this.zz = this.zz.add(colorVector);
  42688. };
  42689. /**
  42690. * Scales the spherical polynomial by the given amount
  42691. * @param scale the amount to scale
  42692. */
  42693. SphericalPolynomial.prototype.scale = function (scale) {
  42694. this.x = this.x.scale(scale);
  42695. this.y = this.y.scale(scale);
  42696. this.z = this.z.scale(scale);
  42697. this.xx = this.xx.scale(scale);
  42698. this.yy = this.yy.scale(scale);
  42699. this.zz = this.zz.scale(scale);
  42700. this.yz = this.yz.scale(scale);
  42701. this.zx = this.zx.scale(scale);
  42702. this.xy = this.xy.scale(scale);
  42703. };
  42704. /**
  42705. * Gets the spherical polynomial from harmonics
  42706. * @param harmonics the spherical harmonics
  42707. * @returns the spherical polynomial
  42708. */
  42709. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42710. var result = new SphericalPolynomial();
  42711. result.x = harmonics.l11.scale(1.02333);
  42712. result.y = harmonics.l1_1.scale(1.02333);
  42713. result.z = harmonics.l10.scale(1.02333);
  42714. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42715. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42716. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42717. result.yz = harmonics.l2_1.scale(0.858086);
  42718. result.zx = harmonics.l21.scale(0.858086);
  42719. result.xy = harmonics.l2_2.scale(0.858086);
  42720. result.scale(1.0 / Math.PI);
  42721. return result;
  42722. };
  42723. /**
  42724. * Constructs a spherical polynomial from an array.
  42725. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42726. * @returns the spherical polynomial
  42727. */
  42728. SphericalPolynomial.FromArray = function (data) {
  42729. var sp = new SphericalPolynomial();
  42730. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42731. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42732. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42733. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42734. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42735. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42736. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42737. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42738. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42739. return sp;
  42740. };
  42741. return SphericalPolynomial;
  42742. }());
  42743. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42744. /**
  42745. * Class representing spherical harmonics coefficients to the 3rd degree
  42746. */
  42747. var SphericalHarmonics = /** @class */ (function () {
  42748. function SphericalHarmonics() {
  42749. /**
  42750. * The l0,0 coefficients of the spherical harmonics
  42751. */
  42752. this.l00 = BABYLON.Vector3.Zero();
  42753. /**
  42754. * The l1,-1 coefficients of the spherical harmonics
  42755. */
  42756. this.l1_1 = BABYLON.Vector3.Zero();
  42757. /**
  42758. * The l1,0 coefficients of the spherical harmonics
  42759. */
  42760. this.l10 = BABYLON.Vector3.Zero();
  42761. /**
  42762. * The l1,1 coefficients of the spherical harmonics
  42763. */
  42764. this.l11 = BABYLON.Vector3.Zero();
  42765. /**
  42766. * The l2,-2 coefficients of the spherical harmonics
  42767. */
  42768. this.l2_2 = BABYLON.Vector3.Zero();
  42769. /**
  42770. * The l2,-1 coefficients of the spherical harmonics
  42771. */
  42772. this.l2_1 = BABYLON.Vector3.Zero();
  42773. /**
  42774. * The l2,0 coefficients of the spherical harmonics
  42775. */
  42776. this.l20 = BABYLON.Vector3.Zero();
  42777. /**
  42778. * The l2,1 coefficients of the spherical harmonics
  42779. */
  42780. this.l21 = BABYLON.Vector3.Zero();
  42781. /**
  42782. * The l2,2 coefficients of the spherical harmonics
  42783. */
  42784. this.lL22 = BABYLON.Vector3.Zero();
  42785. }
  42786. /**
  42787. * Adds a light to the spherical harmonics
  42788. * @param direction the direction of the light
  42789. * @param color the color of the light
  42790. * @param deltaSolidAngle the delta solid angle of the light
  42791. */
  42792. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  42793. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42794. var c = colorVector.scale(deltaSolidAngle);
  42795. this.l00 = this.l00.add(c.scale(0.282095));
  42796. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  42797. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  42798. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  42799. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  42800. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  42801. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  42802. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  42803. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  42804. };
  42805. /**
  42806. * Scales the spherical harmonics by the given amount
  42807. * @param scale the amount to scale
  42808. */
  42809. SphericalHarmonics.prototype.scale = function (scale) {
  42810. this.l00 = this.l00.scale(scale);
  42811. this.l1_1 = this.l1_1.scale(scale);
  42812. this.l10 = this.l10.scale(scale);
  42813. this.l11 = this.l11.scale(scale);
  42814. this.l2_2 = this.l2_2.scale(scale);
  42815. this.l2_1 = this.l2_1.scale(scale);
  42816. this.l20 = this.l20.scale(scale);
  42817. this.l21 = this.l21.scale(scale);
  42818. this.lL22 = this.lL22.scale(scale);
  42819. };
  42820. /**
  42821. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  42822. *
  42823. * ```
  42824. * E_lm = A_l * L_lm
  42825. * ```
  42826. *
  42827. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  42828. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  42829. * the scaling factors are given in equation 9.
  42830. */
  42831. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  42832. // Constant (Band 0)
  42833. this.l00 = this.l00.scale(3.141593);
  42834. // Linear (Band 1)
  42835. this.l1_1 = this.l1_1.scale(2.094395);
  42836. this.l10 = this.l10.scale(2.094395);
  42837. this.l11 = this.l11.scale(2.094395);
  42838. // Quadratic (Band 2)
  42839. this.l2_2 = this.l2_2.scale(0.785398);
  42840. this.l2_1 = this.l2_1.scale(0.785398);
  42841. this.l20 = this.l20.scale(0.785398);
  42842. this.l21 = this.l21.scale(0.785398);
  42843. this.lL22 = this.lL22.scale(0.785398);
  42844. };
  42845. /**
  42846. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  42847. *
  42848. * ```
  42849. * L = (1/pi) * E * rho
  42850. * ```
  42851. *
  42852. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  42853. */
  42854. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  42855. this.scale(1.0 / Math.PI);
  42856. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  42857. // (The pixel shader must apply albedo after texture fetches, etc).
  42858. };
  42859. /**
  42860. * Gets the spherical harmonics from polynomial
  42861. * @param polynomial the spherical polynomial
  42862. * @returns the spherical harmonics
  42863. */
  42864. SphericalHarmonics.FromPolynomial = function (polynomial) {
  42865. var result = new SphericalHarmonics();
  42866. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  42867. result.l1_1 = polynomial.y.scale(0.977204);
  42868. result.l10 = polynomial.z.scale(0.977204);
  42869. result.l11 = polynomial.x.scale(0.977204);
  42870. result.l2_2 = polynomial.xy.scale(1.16538);
  42871. result.l2_1 = polynomial.yz.scale(1.16538);
  42872. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  42873. result.l21 = polynomial.zx.scale(1.16538);
  42874. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  42875. result.scale(Math.PI);
  42876. return result;
  42877. };
  42878. /**
  42879. * Constructs a spherical harmonics from an array.
  42880. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  42881. * @returns the spherical harmonics
  42882. */
  42883. SphericalHarmonics.FromArray = function (data) {
  42884. var sh = new SphericalHarmonics();
  42885. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  42886. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  42887. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  42888. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  42889. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  42890. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  42891. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  42892. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  42893. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  42894. return sh;
  42895. };
  42896. return SphericalHarmonics;
  42897. }());
  42898. BABYLON.SphericalHarmonics = SphericalHarmonics;
  42899. })(BABYLON || (BABYLON = {}));
  42900. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  42901. var BABYLON;
  42902. (function (BABYLON) {
  42903. var FileFaceOrientation = /** @class */ (function () {
  42904. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42905. this.name = name;
  42906. this.worldAxisForNormal = worldAxisForNormal;
  42907. this.worldAxisForFileX = worldAxisForFileX;
  42908. this.worldAxisForFileY = worldAxisForFileY;
  42909. }
  42910. return FileFaceOrientation;
  42911. }());
  42912. ;
  42913. /**
  42914. * Helper class dealing with the extraction of spherical polynomial dataArray
  42915. * from a cube map.
  42916. */
  42917. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  42918. function CubeMapToSphericalPolynomialTools() {
  42919. }
  42920. /**
  42921. * Converts a texture to the according Spherical Polynomial data.
  42922. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42923. *
  42924. * @param texture The texture to extract the information from.
  42925. * @return The Spherical Polynomial data.
  42926. */
  42927. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  42928. if (!texture.isCube) {
  42929. // Only supports cube Textures currently.
  42930. return null;
  42931. }
  42932. var size = texture.getSize().width;
  42933. var right = texture.readPixels(0);
  42934. var left = texture.readPixels(1);
  42935. var up;
  42936. var down;
  42937. if (texture.isRenderTarget) {
  42938. up = texture.readPixels(3);
  42939. down = texture.readPixels(2);
  42940. }
  42941. else {
  42942. up = texture.readPixels(2);
  42943. down = texture.readPixels(3);
  42944. }
  42945. var front = texture.readPixels(4);
  42946. var back = texture.readPixels(5);
  42947. var gammaSpace = texture.gammaSpace;
  42948. // Always read as RGBA.
  42949. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  42950. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42951. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  42952. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42953. }
  42954. var cubeInfo = {
  42955. size: size,
  42956. right: right,
  42957. left: left,
  42958. up: up,
  42959. down: down,
  42960. front: front,
  42961. back: back,
  42962. format: format,
  42963. type: type,
  42964. gammaSpace: gammaSpace,
  42965. };
  42966. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  42967. };
  42968. /**
  42969. * Converts a cubemap to the according Spherical Polynomial data.
  42970. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42971. *
  42972. * @param cubeInfo The Cube map to extract the information from.
  42973. * @return The Spherical Polynomial data.
  42974. */
  42975. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42976. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42977. var totalSolidAngle = 0.0;
  42978. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42979. var du = 2.0 / cubeInfo.size;
  42980. var dv = du;
  42981. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42982. var minUV = du * 0.5 - 1.0;
  42983. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42984. var fileFace = this.FileFaces[faceIndex];
  42985. var dataArray = cubeInfo[fileFace.name];
  42986. var v = minUV;
  42987. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42988. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42989. // Because SP is still linear, so summation is fine in that basis.
  42990. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  42991. for (var y = 0; y < cubeInfo.size; y++) {
  42992. var u = minUV;
  42993. for (var x = 0; x < cubeInfo.size; x++) {
  42994. // World direction (not normalised)
  42995. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  42996. worldDirection.normalize();
  42997. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  42998. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  42999. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43000. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43001. // Handle Integer types.
  43002. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43003. r /= 255;
  43004. g /= 255;
  43005. b /= 255;
  43006. }
  43007. // Handle Gamma space textures.
  43008. if (cubeInfo.gammaSpace) {
  43009. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43010. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43011. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43012. }
  43013. var color = new BABYLON.Color3(r, g, b);
  43014. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43015. totalSolidAngle += deltaSolidAngle;
  43016. u += du;
  43017. }
  43018. v += dv;
  43019. }
  43020. }
  43021. // Solid angle for entire sphere is 4*pi
  43022. var sphereSolidAngle = 4.0 * Math.PI;
  43023. // Adjust the solid angle to allow for how many faces we processed.
  43024. var facesProcessed = 6.0;
  43025. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43026. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43027. // This is needed because the numerical integration over the cube uses a
  43028. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43029. // and also to compensate for accumulative error due to float precision in the summation.
  43030. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43031. sphericalHarmonics.scale(correctionFactor);
  43032. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43033. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43034. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43035. };
  43036. CubeMapToSphericalPolynomialTools.FileFaces = [
  43037. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43038. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43039. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43040. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43041. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43042. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43043. ];
  43044. return CubeMapToSphericalPolynomialTools;
  43045. }());
  43046. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43047. })(BABYLON || (BABYLON = {}));
  43048. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43049. var BABYLON;
  43050. (function (BABYLON) {
  43051. /**
  43052. * Manages the defines for the PBR Material.
  43053. * @hiddenChildren
  43054. */
  43055. var PBRMaterialDefines = /** @class */ (function (_super) {
  43056. __extends(PBRMaterialDefines, _super);
  43057. /**
  43058. * Initializes the PBR Material defines.
  43059. */
  43060. function PBRMaterialDefines() {
  43061. var _this = _super.call(this) || this;
  43062. _this.PBR = true;
  43063. _this.MAINUV1 = false;
  43064. _this.MAINUV2 = false;
  43065. _this.UV1 = false;
  43066. _this.UV2 = false;
  43067. _this.ALBEDO = false;
  43068. _this.ALBEDODIRECTUV = 0;
  43069. _this.VERTEXCOLOR = false;
  43070. _this.AMBIENT = false;
  43071. _this.AMBIENTDIRECTUV = 0;
  43072. _this.AMBIENTINGRAYSCALE = false;
  43073. _this.OPACITY = false;
  43074. _this.VERTEXALPHA = false;
  43075. _this.OPACITYDIRECTUV = 0;
  43076. _this.OPACITYRGB = false;
  43077. _this.ALPHATEST = false;
  43078. _this.DEPTHPREPASS = false;
  43079. _this.ALPHABLEND = false;
  43080. _this.ALPHAFROMALBEDO = false;
  43081. _this.ALPHATESTVALUE = "0.5";
  43082. _this.SPECULAROVERALPHA = false;
  43083. _this.RADIANCEOVERALPHA = false;
  43084. _this.ALPHAFRESNEL = false;
  43085. _this.LINEARALPHAFRESNEL = false;
  43086. _this.PREMULTIPLYALPHA = false;
  43087. _this.EMISSIVE = false;
  43088. _this.EMISSIVEDIRECTUV = 0;
  43089. _this.REFLECTIVITY = false;
  43090. _this.REFLECTIVITYDIRECTUV = 0;
  43091. _this.SPECULARTERM = false;
  43092. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43093. _this.MICROSURFACEAUTOMATIC = false;
  43094. _this.LODBASEDMICROSFURACE = false;
  43095. _this.MICROSURFACEMAP = false;
  43096. _this.MICROSURFACEMAPDIRECTUV = 0;
  43097. _this.METALLICWORKFLOW = false;
  43098. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43099. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43100. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43101. _this.AOSTOREINMETALMAPRED = false;
  43102. _this.ENVIRONMENTBRDF = false;
  43103. _this.NORMAL = false;
  43104. _this.TANGENT = false;
  43105. _this.BUMP = false;
  43106. _this.BUMPDIRECTUV = 0;
  43107. _this.OBJECTSPACE_NORMALMAP = false;
  43108. _this.PARALLAX = false;
  43109. _this.PARALLAXOCCLUSION = false;
  43110. _this.NORMALXYSCALE = true;
  43111. _this.LIGHTMAP = false;
  43112. _this.LIGHTMAPDIRECTUV = 0;
  43113. _this.USELIGHTMAPASSHADOWMAP = false;
  43114. _this.GAMMALIGHTMAP = false;
  43115. _this.REFLECTION = false;
  43116. _this.REFLECTIONMAP_3D = false;
  43117. _this.REFLECTIONMAP_SPHERICAL = false;
  43118. _this.REFLECTIONMAP_PLANAR = false;
  43119. _this.REFLECTIONMAP_CUBIC = false;
  43120. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43121. _this.REFLECTIONMAP_PROJECTION = false;
  43122. _this.REFLECTIONMAP_SKYBOX = false;
  43123. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43124. _this.REFLECTIONMAP_EXPLICIT = false;
  43125. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43126. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43127. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43128. _this.INVERTCUBICMAP = false;
  43129. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43130. _this.USESPHERICALINVERTEX = false;
  43131. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43132. _this.LODINREFLECTIONALPHA = false;
  43133. _this.GAMMAREFLECTION = false;
  43134. _this.RGBDREFLECTION = false;
  43135. _this.RADIANCEOCCLUSION = false;
  43136. _this.HORIZONOCCLUSION = false;
  43137. _this.REFRACTION = false;
  43138. _this.REFRACTIONMAP_3D = false;
  43139. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43140. _this.LODINREFRACTIONALPHA = false;
  43141. _this.GAMMAREFRACTION = false;
  43142. _this.RGBDREFRACTION = false;
  43143. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43144. _this.INSTANCES = false;
  43145. _this.NUM_BONE_INFLUENCERS = 0;
  43146. _this.BonesPerMesh = 0;
  43147. _this.NONUNIFORMSCALING = false;
  43148. _this.MORPHTARGETS = false;
  43149. _this.MORPHTARGETS_NORMAL = false;
  43150. _this.MORPHTARGETS_TANGENT = false;
  43151. _this.NUM_MORPH_INFLUENCERS = 0;
  43152. _this.IMAGEPROCESSING = false;
  43153. _this.VIGNETTE = false;
  43154. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43155. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43156. _this.TONEMAPPING = false;
  43157. _this.TONEMAPPING_ACES = false;
  43158. _this.CONTRAST = false;
  43159. _this.COLORCURVES = false;
  43160. _this.COLORGRADING = false;
  43161. _this.COLORGRADING3D = false;
  43162. _this.SAMPLER3DGREENDEPTH = false;
  43163. _this.SAMPLER3DBGRMAP = false;
  43164. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43165. _this.EXPOSURE = false;
  43166. _this.USEPHYSICALLIGHTFALLOFF = false;
  43167. _this.USEGLTFLIGHTFALLOFF = false;
  43168. _this.TWOSIDEDLIGHTING = false;
  43169. _this.SHADOWFLOAT = false;
  43170. _this.CLIPPLANE = false;
  43171. _this.CLIPPLANE2 = false;
  43172. _this.CLIPPLANE3 = false;
  43173. _this.CLIPPLANE4 = false;
  43174. _this.POINTSIZE = false;
  43175. _this.FOG = false;
  43176. _this.LOGARITHMICDEPTH = false;
  43177. _this.FORCENORMALFORWARD = false;
  43178. _this.SPECULARAA = false;
  43179. _this.UNLIT = false;
  43180. _this.rebuild();
  43181. return _this;
  43182. }
  43183. /**
  43184. * Resets the PBR Material defines.
  43185. */
  43186. PBRMaterialDefines.prototype.reset = function () {
  43187. _super.prototype.reset.call(this);
  43188. this.ALPHATESTVALUE = "0.5";
  43189. this.PBR = true;
  43190. };
  43191. return PBRMaterialDefines;
  43192. }(BABYLON.MaterialDefines));
  43193. /**
  43194. * The Physically based material base class of BJS.
  43195. *
  43196. * This offers the main features of a standard PBR material.
  43197. * For more information, please refer to the documentation :
  43198. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43199. */
  43200. var PBRBaseMaterial = /** @class */ (function (_super) {
  43201. __extends(PBRBaseMaterial, _super);
  43202. /**
  43203. * Instantiates a new PBRMaterial instance.
  43204. *
  43205. * @param name The material name
  43206. * @param scene The scene the material will be use in.
  43207. */
  43208. function PBRBaseMaterial(name, scene) {
  43209. var _this = _super.call(this, name, scene) || this;
  43210. /**
  43211. * Intensity of the direct lights e.g. the four lights available in your scene.
  43212. * This impacts both the direct diffuse and specular highlights.
  43213. */
  43214. _this._directIntensity = 1.0;
  43215. /**
  43216. * Intensity of the emissive part of the material.
  43217. * This helps controlling the emissive effect without modifying the emissive color.
  43218. */
  43219. _this._emissiveIntensity = 1.0;
  43220. /**
  43221. * Intensity of the environment e.g. how much the environment will light the object
  43222. * either through harmonics for rough material or through the refelction for shiny ones.
  43223. */
  43224. _this._environmentIntensity = 1.0;
  43225. /**
  43226. * This is a special control allowing the reduction of the specular highlights coming from the
  43227. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43228. */
  43229. _this._specularIntensity = 1.0;
  43230. /**
  43231. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43232. */
  43233. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43234. /**
  43235. * Debug Control allowing disabling the bump map on this material.
  43236. */
  43237. _this._disableBumpMap = false;
  43238. /**
  43239. * AKA Occlusion Texture Intensity in other nomenclature.
  43240. */
  43241. _this._ambientTextureStrength = 1.0;
  43242. /**
  43243. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43244. * 1 means it completely occludes it
  43245. * 0 mean it has no impact
  43246. */
  43247. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43248. /**
  43249. * The color of a material in ambient lighting.
  43250. */
  43251. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43252. /**
  43253. * AKA Diffuse Color in other nomenclature.
  43254. */
  43255. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43256. /**
  43257. * AKA Specular Color in other nomenclature.
  43258. */
  43259. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43260. /**
  43261. * The color applied when light is reflected from a material.
  43262. */
  43263. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43264. /**
  43265. * The color applied when light is emitted from a material.
  43266. */
  43267. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43268. /**
  43269. * AKA Glossiness in other nomenclature.
  43270. */
  43271. _this._microSurface = 0.9;
  43272. /**
  43273. * source material index of refraction (IOR)' / 'destination material IOR.
  43274. */
  43275. _this._indexOfRefraction = 0.66;
  43276. /**
  43277. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43278. */
  43279. _this._invertRefractionY = false;
  43280. /**
  43281. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43282. * Materials half opaque for instance using refraction could benefit from this control.
  43283. */
  43284. _this._linkRefractionWithTransparency = false;
  43285. /**
  43286. * Specifies that the material will use the light map as a show map.
  43287. */
  43288. _this._useLightmapAsShadowmap = false;
  43289. /**
  43290. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43291. * makes the reflect vector face the model (under horizon).
  43292. */
  43293. _this._useHorizonOcclusion = true;
  43294. /**
  43295. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43296. * too much the area relying on ambient texture to define their ambient occlusion.
  43297. */
  43298. _this._useRadianceOcclusion = true;
  43299. /**
  43300. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43301. */
  43302. _this._useAlphaFromAlbedoTexture = false;
  43303. /**
  43304. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43305. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43306. */
  43307. _this._useSpecularOverAlpha = true;
  43308. /**
  43309. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43310. */
  43311. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43312. /**
  43313. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43314. */
  43315. _this._useRoughnessFromMetallicTextureAlpha = true;
  43316. /**
  43317. * Specifies if the metallic texture contains the roughness information in its green channel.
  43318. */
  43319. _this._useRoughnessFromMetallicTextureGreen = false;
  43320. /**
  43321. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43322. */
  43323. _this._useMetallnessFromMetallicTextureBlue = false;
  43324. /**
  43325. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43326. */
  43327. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43328. /**
  43329. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43330. */
  43331. _this._useAmbientInGrayScale = false;
  43332. /**
  43333. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43334. * The material will try to infer what glossiness each pixel should be.
  43335. */
  43336. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43337. /**
  43338. * Defines the falloff type used in this material.
  43339. * It by default is Physical.
  43340. */
  43341. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43342. /**
  43343. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43344. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43345. */
  43346. _this._useRadianceOverAlpha = true;
  43347. /**
  43348. * Allows using an object space normal map (instead of tangent space).
  43349. */
  43350. _this._useObjectSpaceNormalMap = false;
  43351. /**
  43352. * Allows using the bump map in parallax mode.
  43353. */
  43354. _this._useParallax = false;
  43355. /**
  43356. * Allows using the bump map in parallax occlusion mode.
  43357. */
  43358. _this._useParallaxOcclusion = false;
  43359. /**
  43360. * Controls the scale bias of the parallax mode.
  43361. */
  43362. _this._parallaxScaleBias = 0.05;
  43363. /**
  43364. * If sets to true, disables all the lights affecting the material.
  43365. */
  43366. _this._disableLighting = false;
  43367. /**
  43368. * Number of Simultaneous lights allowed on the material.
  43369. */
  43370. _this._maxSimultaneousLights = 4;
  43371. /**
  43372. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43373. */
  43374. _this._invertNormalMapX = false;
  43375. /**
  43376. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43377. */
  43378. _this._invertNormalMapY = false;
  43379. /**
  43380. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43381. */
  43382. _this._twoSidedLighting = false;
  43383. /**
  43384. * Defines the alpha limits in alpha test mode.
  43385. */
  43386. _this._alphaCutOff = 0.4;
  43387. /**
  43388. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43389. */
  43390. _this._forceAlphaTest = false;
  43391. /**
  43392. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43393. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43394. */
  43395. _this._useAlphaFresnel = false;
  43396. /**
  43397. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43398. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43399. */
  43400. _this._useLinearAlphaFresnel = false;
  43401. /**
  43402. * The transparency mode of the material.
  43403. */
  43404. _this._transparencyMode = null;
  43405. /**
  43406. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43407. * from cos thetav and roughness:
  43408. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43409. */
  43410. _this._environmentBRDFTexture = null;
  43411. /**
  43412. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43413. */
  43414. _this._forceIrradianceInFragment = false;
  43415. /**
  43416. * Force normal to face away from face.
  43417. */
  43418. _this._forceNormalForward = false;
  43419. /**
  43420. * Enables specular anti aliasing in the PBR shader.
  43421. * It will both interacts on the Geometry for analytical and IBL lighting.
  43422. * It also prefilter the roughness map based on the bump values.
  43423. */
  43424. _this._enableSpecularAntiAliasing = false;
  43425. /**
  43426. * Stores the available render targets.
  43427. */
  43428. _this._renderTargets = new BABYLON.SmartArray(16);
  43429. /**
  43430. * Sets the global ambient color for the material used in lighting calculations.
  43431. */
  43432. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43433. /**
  43434. * If set to true, no lighting calculations will be applied.
  43435. */
  43436. _this._unlit = false;
  43437. // Setup the default processing configuration to the scene.
  43438. _this._attachImageProcessingConfiguration(null);
  43439. _this.getRenderTargetTextures = function () {
  43440. _this._renderTargets.reset();
  43441. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43442. _this._renderTargets.push(_this._reflectionTexture);
  43443. }
  43444. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43445. _this._renderTargets.push(_this._refractionTexture);
  43446. }
  43447. return _this._renderTargets;
  43448. };
  43449. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43450. return _this;
  43451. }
  43452. /**
  43453. * Attaches a new image processing configuration to the PBR Material.
  43454. * @param configuration
  43455. */
  43456. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43457. var _this = this;
  43458. if (configuration === this._imageProcessingConfiguration) {
  43459. return;
  43460. }
  43461. // Detaches observer.
  43462. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43463. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43464. }
  43465. // Pick the scene configuration if needed.
  43466. if (!configuration) {
  43467. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43468. }
  43469. else {
  43470. this._imageProcessingConfiguration = configuration;
  43471. }
  43472. // Attaches observer.
  43473. if (this._imageProcessingConfiguration) {
  43474. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43475. _this._markAllSubMeshesAsImageProcessingDirty();
  43476. });
  43477. }
  43478. };
  43479. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43480. /**
  43481. * Gets a boolean indicating that current material needs to register RTT
  43482. */
  43483. get: function () {
  43484. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43485. return true;
  43486. }
  43487. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43488. return true;
  43489. }
  43490. return false;
  43491. },
  43492. enumerable: true,
  43493. configurable: true
  43494. });
  43495. /**
  43496. * Gets the name of the material class.
  43497. */
  43498. PBRBaseMaterial.prototype.getClassName = function () {
  43499. return "PBRBaseMaterial";
  43500. };
  43501. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43502. /**
  43503. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43504. */
  43505. get: function () {
  43506. return this._useLogarithmicDepth;
  43507. },
  43508. /**
  43509. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43510. */
  43511. set: function (value) {
  43512. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43513. },
  43514. enumerable: true,
  43515. configurable: true
  43516. });
  43517. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43518. /**
  43519. * Gets the current transparency mode.
  43520. */
  43521. get: function () {
  43522. return this._transparencyMode;
  43523. },
  43524. /**
  43525. * Sets the transparency mode of the material.
  43526. *
  43527. * | Value | Type | Description |
  43528. * | ----- | ----------------------------------- | ----------- |
  43529. * | 0 | OPAQUE | |
  43530. * | 1 | ALPHATEST | |
  43531. * | 2 | ALPHABLEND | |
  43532. * | 3 | ALPHATESTANDBLEND | |
  43533. *
  43534. */
  43535. set: function (value) {
  43536. if (this._transparencyMode === value) {
  43537. return;
  43538. }
  43539. this._transparencyMode = value;
  43540. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43541. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43542. },
  43543. enumerable: true,
  43544. configurable: true
  43545. });
  43546. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43547. /**
  43548. * Returns true if alpha blending should be disabled.
  43549. */
  43550. get: function () {
  43551. return (this._linkRefractionWithTransparency ||
  43552. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43553. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43554. },
  43555. enumerable: true,
  43556. configurable: true
  43557. });
  43558. /**
  43559. * Specifies whether or not this material should be rendered in alpha blend mode.
  43560. */
  43561. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43562. if (this._disableAlphaBlending) {
  43563. return false;
  43564. }
  43565. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43566. };
  43567. /**
  43568. * Specifies if the mesh will require alpha blending.
  43569. * @param mesh - BJS mesh.
  43570. */
  43571. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43572. if (this._disableAlphaBlending) {
  43573. return false;
  43574. }
  43575. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43576. };
  43577. /**
  43578. * Specifies whether or not this material should be rendered in alpha test mode.
  43579. */
  43580. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43581. if (this._forceAlphaTest) {
  43582. return true;
  43583. }
  43584. if (this._linkRefractionWithTransparency) {
  43585. return false;
  43586. }
  43587. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43588. };
  43589. /**
  43590. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43591. */
  43592. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43593. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43594. };
  43595. /**
  43596. * Gets the texture used for the alpha test.
  43597. */
  43598. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43599. return this._albedoTexture;
  43600. };
  43601. /**
  43602. * Specifies that the submesh is ready to be used.
  43603. * @param mesh - BJS mesh.
  43604. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43605. * @param useInstances - Specifies that instances should be used.
  43606. * @returns - boolean indicating that the submesh is ready or not.
  43607. */
  43608. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43609. if (subMesh.effect && this.isFrozen) {
  43610. if (this._wasPreviouslyReady) {
  43611. return true;
  43612. }
  43613. }
  43614. if (!subMesh._materialDefines) {
  43615. subMesh._materialDefines = new PBRMaterialDefines();
  43616. }
  43617. var defines = subMesh._materialDefines;
  43618. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43619. if (defines._renderId === this.getScene().getRenderId()) {
  43620. return true;
  43621. }
  43622. }
  43623. var scene = this.getScene();
  43624. var engine = scene.getEngine();
  43625. if (defines._areTexturesDirty) {
  43626. if (scene.texturesEnabled) {
  43627. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43628. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43629. return false;
  43630. }
  43631. }
  43632. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43633. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43634. return false;
  43635. }
  43636. }
  43637. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43638. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43639. return false;
  43640. }
  43641. }
  43642. var reflectionTexture = this._getReflectionTexture();
  43643. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43644. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43645. return false;
  43646. }
  43647. }
  43648. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43649. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43650. return false;
  43651. }
  43652. }
  43653. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43654. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43655. return false;
  43656. }
  43657. }
  43658. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43659. if (this._metallicTexture) {
  43660. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43661. return false;
  43662. }
  43663. }
  43664. else if (this._reflectivityTexture) {
  43665. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43666. return false;
  43667. }
  43668. }
  43669. if (this._microSurfaceTexture) {
  43670. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43671. return false;
  43672. }
  43673. }
  43674. }
  43675. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43676. // Bump texture cannot be not blocking.
  43677. if (!this._bumpTexture.isReady()) {
  43678. return false;
  43679. }
  43680. }
  43681. var refractionTexture = this._getRefractionTexture();
  43682. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43683. if (!refractionTexture.isReadyOrNotBlocking()) {
  43684. return false;
  43685. }
  43686. }
  43687. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43688. // This is blocking.
  43689. if (!this._environmentBRDFTexture.isReady()) {
  43690. return false;
  43691. }
  43692. }
  43693. }
  43694. }
  43695. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43696. if (!this._imageProcessingConfiguration.isReady()) {
  43697. return false;
  43698. }
  43699. }
  43700. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43701. mesh.createNormals(true);
  43702. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43703. }
  43704. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43705. if (effect) {
  43706. scene.resetCachedMaterial();
  43707. subMesh.setEffect(effect, defines);
  43708. this.buildUniformLayout();
  43709. }
  43710. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43711. return false;
  43712. }
  43713. defines._renderId = scene.getRenderId();
  43714. this._wasPreviouslyReady = true;
  43715. return true;
  43716. };
  43717. /**
  43718. * Specifies if the material uses metallic roughness workflow.
  43719. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43720. */
  43721. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43722. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43723. return true;
  43724. }
  43725. return false;
  43726. };
  43727. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43728. if (onCompiled === void 0) { onCompiled = null; }
  43729. if (onError === void 0) { onError = null; }
  43730. if (useInstances === void 0) { useInstances = null; }
  43731. if (useClipPlane === void 0) { useClipPlane = null; }
  43732. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43733. if (!defines.isDirty) {
  43734. return null;
  43735. }
  43736. defines.markAsProcessed();
  43737. var scene = this.getScene();
  43738. var engine = scene.getEngine();
  43739. // Fallbacks
  43740. var fallbacks = new BABYLON.EffectFallbacks();
  43741. var fallbackRank = 0;
  43742. if (defines.USESPHERICALINVERTEX) {
  43743. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43744. }
  43745. if (defines.FOG) {
  43746. fallbacks.addFallback(fallbackRank, "FOG");
  43747. }
  43748. if (defines.SPECULARAA) {
  43749. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43750. }
  43751. if (defines.POINTSIZE) {
  43752. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43753. }
  43754. if (defines.LOGARITHMICDEPTH) {
  43755. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43756. }
  43757. if (defines.PARALLAX) {
  43758. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43759. }
  43760. if (defines.PARALLAXOCCLUSION) {
  43761. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43762. }
  43763. if (defines.ENVIRONMENTBRDF) {
  43764. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43765. }
  43766. if (defines.TANGENT) {
  43767. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43768. }
  43769. if (defines.BUMP) {
  43770. fallbacks.addFallback(fallbackRank++, "BUMP");
  43771. }
  43772. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43773. if (defines.SPECULARTERM) {
  43774. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43775. }
  43776. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43777. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43778. }
  43779. if (defines.LIGHTMAP) {
  43780. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43781. }
  43782. if (defines.NORMAL) {
  43783. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43784. }
  43785. if (defines.AMBIENT) {
  43786. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43787. }
  43788. if (defines.EMISSIVE) {
  43789. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43790. }
  43791. if (defines.VERTEXCOLOR) {
  43792. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43793. }
  43794. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43795. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43796. }
  43797. if (defines.MORPHTARGETS) {
  43798. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43799. }
  43800. //Attributes
  43801. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43802. if (defines.NORMAL) {
  43803. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43804. }
  43805. if (defines.TANGENT) {
  43806. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43807. }
  43808. if (defines.UV1) {
  43809. attribs.push(BABYLON.VertexBuffer.UVKind);
  43810. }
  43811. if (defines.UV2) {
  43812. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43813. }
  43814. if (defines.VERTEXCOLOR) {
  43815. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43816. }
  43817. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43818. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43819. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43820. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43821. "vFogInfos", "vFogColor", "pointSize",
  43822. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43823. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43824. "mBones",
  43825. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43826. "vLightingIntensity",
  43827. "logarithmicDepthConstant",
  43828. "vSphericalX", "vSphericalY", "vSphericalZ",
  43829. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43830. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43831. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43832. "vTangentSpaceParams"
  43833. ];
  43834. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43835. "bumpSampler", "lightmapSampler", "opacitySampler",
  43836. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43837. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43838. "microSurfaceSampler", "environmentBrdfSampler"];
  43839. var uniformBuffers = ["Material", "Scene"];
  43840. if (BABYLON.ImageProcessingConfiguration) {
  43841. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43842. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43843. }
  43844. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43845. uniformsNames: uniforms,
  43846. uniformBuffersNames: uniformBuffers,
  43847. samplers: samplers,
  43848. defines: defines,
  43849. maxSimultaneousLights: this._maxSimultaneousLights
  43850. });
  43851. var join = defines.toString();
  43852. return engine.createEffect("pbr", {
  43853. attributes: attribs,
  43854. uniformsNames: uniforms,
  43855. uniformBuffersNames: uniformBuffers,
  43856. samplers: samplers,
  43857. defines: join,
  43858. fallbacks: fallbacks,
  43859. onCompiled: onCompiled,
  43860. onError: onError,
  43861. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43862. }, engine);
  43863. };
  43864. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43865. if (useInstances === void 0) { useInstances = null; }
  43866. if (useClipPlane === void 0) { useClipPlane = null; }
  43867. var scene = this.getScene();
  43868. var engine = scene.getEngine();
  43869. // Lights
  43870. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43871. defines._needNormals = true;
  43872. // Textures
  43873. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43874. if (defines._areTexturesDirty) {
  43875. defines._needUVs = false;
  43876. if (scene.texturesEnabled) {
  43877. if (scene.getEngine().getCaps().textureLOD) {
  43878. defines.LODBASEDMICROSFURACE = true;
  43879. }
  43880. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43881. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43882. }
  43883. else {
  43884. defines.ALBEDO = false;
  43885. }
  43886. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43887. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43888. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43889. }
  43890. else {
  43891. defines.AMBIENT = false;
  43892. }
  43893. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43895. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43896. }
  43897. else {
  43898. defines.OPACITY = false;
  43899. }
  43900. var reflectionTexture = this._getReflectionTexture();
  43901. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43902. defines.REFLECTION = true;
  43903. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43904. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43905. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43906. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43907. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43908. defines.INVERTCUBICMAP = true;
  43909. }
  43910. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43911. switch (reflectionTexture.coordinatesMode) {
  43912. case BABYLON.Texture.EXPLICIT_MODE:
  43913. defines.REFLECTIONMAP_EXPLICIT = true;
  43914. break;
  43915. case BABYLON.Texture.PLANAR_MODE:
  43916. defines.REFLECTIONMAP_PLANAR = true;
  43917. break;
  43918. case BABYLON.Texture.PROJECTION_MODE:
  43919. defines.REFLECTIONMAP_PROJECTION = true;
  43920. break;
  43921. case BABYLON.Texture.SKYBOX_MODE:
  43922. defines.REFLECTIONMAP_SKYBOX = true;
  43923. break;
  43924. case BABYLON.Texture.SPHERICAL_MODE:
  43925. defines.REFLECTIONMAP_SPHERICAL = true;
  43926. break;
  43927. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43928. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43929. break;
  43930. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43931. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43932. break;
  43933. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43934. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43935. break;
  43936. case BABYLON.Texture.CUBIC_MODE:
  43937. case BABYLON.Texture.INVCUBIC_MODE:
  43938. default:
  43939. defines.REFLECTIONMAP_CUBIC = true;
  43940. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43941. break;
  43942. }
  43943. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43944. if (reflectionTexture.sphericalPolynomial) {
  43945. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43946. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43947. defines.USESPHERICALINVERTEX = false;
  43948. }
  43949. else {
  43950. defines.USESPHERICALINVERTEX = true;
  43951. }
  43952. }
  43953. }
  43954. else {
  43955. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43956. }
  43957. }
  43958. else {
  43959. defines.REFLECTION = false;
  43960. defines.REFLECTIONMAP_3D = false;
  43961. defines.REFLECTIONMAP_SPHERICAL = false;
  43962. defines.REFLECTIONMAP_PLANAR = false;
  43963. defines.REFLECTIONMAP_CUBIC = false;
  43964. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43965. defines.REFLECTIONMAP_PROJECTION = false;
  43966. defines.REFLECTIONMAP_SKYBOX = false;
  43967. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43968. defines.REFLECTIONMAP_EXPLICIT = false;
  43969. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43970. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43971. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43972. defines.INVERTCUBICMAP = false;
  43973. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43974. defines.USESPHERICALINVERTEX = false;
  43975. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43976. defines.LODINREFLECTIONALPHA = false;
  43977. defines.GAMMAREFLECTION = false;
  43978. defines.RGBDREFLECTION = false;
  43979. }
  43980. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43981. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43982. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43983. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43984. }
  43985. else {
  43986. defines.LIGHTMAP = false;
  43987. }
  43988. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43989. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43990. }
  43991. else {
  43992. defines.EMISSIVE = false;
  43993. }
  43994. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43995. if (this._metallicTexture) {
  43996. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43997. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43998. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43999. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44000. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44001. }
  44002. else if (this._reflectivityTexture) {
  44003. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44004. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44005. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44006. }
  44007. else {
  44008. defines.REFLECTIVITY = false;
  44009. }
  44010. if (this._microSurfaceTexture) {
  44011. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44012. }
  44013. else {
  44014. defines.MICROSURFACEMAP = false;
  44015. }
  44016. }
  44017. else {
  44018. defines.REFLECTIVITY = false;
  44019. defines.MICROSURFACEMAP = false;
  44020. }
  44021. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44022. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44023. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44024. defines.PARALLAX = true;
  44025. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44026. }
  44027. else {
  44028. defines.PARALLAX = false;
  44029. }
  44030. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44031. }
  44032. else {
  44033. defines.BUMP = false;
  44034. }
  44035. var refractionTexture = this._getRefractionTexture();
  44036. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44037. defines.REFRACTION = true;
  44038. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44039. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44040. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44041. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44042. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44043. if (this._linkRefractionWithTransparency) {
  44044. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44045. }
  44046. }
  44047. else {
  44048. defines.REFRACTION = false;
  44049. }
  44050. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44051. defines.ENVIRONMENTBRDF = true;
  44052. }
  44053. else {
  44054. defines.ENVIRONMENTBRDF = false;
  44055. }
  44056. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44057. defines.ALPHAFROMALBEDO = true;
  44058. }
  44059. else {
  44060. defines.ALPHAFROMALBEDO = false;
  44061. }
  44062. }
  44063. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44064. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44065. defines.USEPHYSICALLIGHTFALLOFF = false;
  44066. defines.USEGLTFLIGHTFALLOFF = false;
  44067. }
  44068. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44069. defines.USEPHYSICALLIGHTFALLOFF = false;
  44070. defines.USEGLTFLIGHTFALLOFF = true;
  44071. }
  44072. else {
  44073. defines.USEPHYSICALLIGHTFALLOFF = true;
  44074. defines.USEGLTFLIGHTFALLOFF = false;
  44075. }
  44076. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44077. if (!this.backFaceCulling && this._twoSidedLighting) {
  44078. defines.TWOSIDEDLIGHTING = true;
  44079. }
  44080. else {
  44081. defines.TWOSIDEDLIGHTING = false;
  44082. }
  44083. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44084. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44085. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44086. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44087. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44088. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44089. }
  44090. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44091. this._imageProcessingConfiguration.prepareDefines(defines);
  44092. }
  44093. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44094. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44095. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44096. // Misc.
  44097. if (defines._areMiscDirty) {
  44098. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44099. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44100. }
  44101. // Values that need to be evaluated on every frame
  44102. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44103. // Attribs
  44104. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44105. };
  44106. /**
  44107. * Force shader compilation
  44108. */
  44109. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44110. var _this = this;
  44111. var localOptions = __assign({ clipPlane: false }, options);
  44112. var defines = new PBRMaterialDefines();
  44113. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44114. if (effect.isReady()) {
  44115. if (onCompiled) {
  44116. onCompiled(this);
  44117. }
  44118. }
  44119. else {
  44120. effect.onCompileObservable.add(function () {
  44121. if (onCompiled) {
  44122. onCompiled(_this);
  44123. }
  44124. });
  44125. }
  44126. };
  44127. /**
  44128. * Initializes the uniform buffer layout for the shader.
  44129. */
  44130. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44131. // Order is important !
  44132. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44133. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44134. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44135. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44136. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44137. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44138. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44139. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44140. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44141. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44142. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44143. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44144. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44145. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44146. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44147. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44148. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44149. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44150. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44151. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44152. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44153. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44154. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44155. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44156. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44157. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44158. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44159. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44160. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44161. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44162. this._uniformBuffer.addUniform("pointSize", 1);
  44163. this._uniformBuffer.create();
  44164. };
  44165. /**
  44166. * Unbinds the textures.
  44167. */
  44168. PBRBaseMaterial.prototype.unbind = function () {
  44169. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44170. this._uniformBuffer.setTexture("reflectionSampler", null);
  44171. }
  44172. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44173. this._uniformBuffer.setTexture("refractionSampler", null);
  44174. }
  44175. _super.prototype.unbind.call(this);
  44176. };
  44177. /**
  44178. * Binds the submesh data.
  44179. * @param world - The world matrix.
  44180. * @param mesh - The BJS mesh.
  44181. * @param subMesh - A submesh of the BJS mesh.
  44182. */
  44183. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44184. var scene = this.getScene();
  44185. var defines = subMesh._materialDefines;
  44186. if (!defines) {
  44187. return;
  44188. }
  44189. var effect = subMesh.effect;
  44190. if (!effect) {
  44191. return;
  44192. }
  44193. this._activeEffect = effect;
  44194. // Matrices
  44195. this.bindOnlyWorldMatrix(world);
  44196. // Normal Matrix
  44197. if (defines.OBJECTSPACE_NORMALMAP) {
  44198. world.toNormalMatrix(this._normalMatrix);
  44199. this.bindOnlyNormalMatrix(this._normalMatrix);
  44200. }
  44201. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44202. // Bones
  44203. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44204. var reflectionTexture = null;
  44205. if (mustRebind) {
  44206. this._uniformBuffer.bindToEffect(effect, "Material");
  44207. this.bindViewProjection(effect);
  44208. reflectionTexture = this._getReflectionTexture();
  44209. var refractionTexture = this._getRefractionTexture();
  44210. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44211. // Texture uniforms
  44212. if (scene.texturesEnabled) {
  44213. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44214. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44215. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44216. }
  44217. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44218. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44219. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44220. }
  44221. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44222. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44223. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44224. }
  44225. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44226. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44227. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44228. if (reflectionTexture.boundingBoxSize) {
  44229. var cubeTexture = reflectionTexture;
  44230. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44231. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44232. }
  44233. var polynomials = reflectionTexture.sphericalPolynomial;
  44234. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44235. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44236. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44237. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44238. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44239. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44240. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44241. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44242. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44243. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44244. }
  44245. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44246. }
  44247. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44248. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44249. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44250. }
  44251. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44252. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44253. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44254. }
  44255. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44256. if (this._metallicTexture) {
  44257. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44258. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44259. }
  44260. else if (this._reflectivityTexture) {
  44261. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44262. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44263. }
  44264. if (this._microSurfaceTexture) {
  44265. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44266. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44267. }
  44268. }
  44269. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44270. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44271. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44272. if (scene._mirroredCameraPosition) {
  44273. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44274. }
  44275. else {
  44276. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44277. }
  44278. }
  44279. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44280. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44281. var depth = 1.0;
  44282. if (!refractionTexture.isCube) {
  44283. if (refractionTexture.depth) {
  44284. depth = refractionTexture.depth;
  44285. }
  44286. }
  44287. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44288. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44289. }
  44290. }
  44291. // Point size
  44292. if (this.pointsCloud) {
  44293. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44294. }
  44295. // Colors
  44296. if (defines.METALLICWORKFLOW) {
  44297. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44298. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44299. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44300. }
  44301. else {
  44302. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44303. }
  44304. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44305. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44306. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44307. // Misc
  44308. this._lightingInfos.x = this._directIntensity;
  44309. this._lightingInfos.y = this._emissiveIntensity;
  44310. this._lightingInfos.z = this._environmentIntensity;
  44311. this._lightingInfos.w = this._specularIntensity;
  44312. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44313. }
  44314. // Textures
  44315. if (scene.texturesEnabled) {
  44316. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44317. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44318. }
  44319. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44320. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44321. }
  44322. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44323. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44324. }
  44325. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44326. if (defines.LODBASEDMICROSFURACE) {
  44327. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44328. }
  44329. else {
  44330. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44331. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44332. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44333. }
  44334. }
  44335. if (defines.ENVIRONMENTBRDF) {
  44336. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44337. }
  44338. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44339. if (defines.LODBASEDMICROSFURACE) {
  44340. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44341. }
  44342. else {
  44343. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44344. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44345. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44346. }
  44347. }
  44348. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44349. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44350. }
  44351. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44352. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44353. }
  44354. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44355. if (this._metallicTexture) {
  44356. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44357. }
  44358. else if (this._reflectivityTexture) {
  44359. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44360. }
  44361. if (this._microSurfaceTexture) {
  44362. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44363. }
  44364. }
  44365. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44366. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44367. }
  44368. }
  44369. // Clip plane
  44370. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44371. // Colors
  44372. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44373. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44374. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44375. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44376. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44377. }
  44378. if (mustRebind || !this.isFrozen) {
  44379. // Lights
  44380. if (scene.lightsEnabled && !this._disableLighting) {
  44381. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44382. }
  44383. // View
  44384. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44385. this.bindView(effect);
  44386. }
  44387. // Fog
  44388. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44389. // Morph targets
  44390. if (defines.NUM_MORPH_INFLUENCERS) {
  44391. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44392. }
  44393. // image processing
  44394. this._imageProcessingConfiguration.bind(this._activeEffect);
  44395. // Log. depth
  44396. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44397. }
  44398. this._uniformBuffer.update();
  44399. this._afterBind(mesh, this._activeEffect);
  44400. };
  44401. /**
  44402. * Returns the animatable textures.
  44403. * @returns - Array of animatable textures.
  44404. */
  44405. PBRBaseMaterial.prototype.getAnimatables = function () {
  44406. var results = [];
  44407. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44408. results.push(this._albedoTexture);
  44409. }
  44410. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44411. results.push(this._ambientTexture);
  44412. }
  44413. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44414. results.push(this._opacityTexture);
  44415. }
  44416. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44417. results.push(this._reflectionTexture);
  44418. }
  44419. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44420. results.push(this._emissiveTexture);
  44421. }
  44422. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44423. results.push(this._metallicTexture);
  44424. }
  44425. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44426. results.push(this._reflectivityTexture);
  44427. }
  44428. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44429. results.push(this._bumpTexture);
  44430. }
  44431. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44432. results.push(this._lightmapTexture);
  44433. }
  44434. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44435. results.push(this._refractionTexture);
  44436. }
  44437. return results;
  44438. };
  44439. /**
  44440. * Returns the texture used for reflections.
  44441. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44442. */
  44443. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44444. if (this._reflectionTexture) {
  44445. return this._reflectionTexture;
  44446. }
  44447. return this.getScene().environmentTexture;
  44448. };
  44449. /**
  44450. * Returns the texture used for refraction or null if none is used.
  44451. * @returns - Refection texture if present. If no refraction texture and refraction
  44452. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44453. */
  44454. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44455. if (this._refractionTexture) {
  44456. return this._refractionTexture;
  44457. }
  44458. if (this._linkRefractionWithTransparency) {
  44459. return this.getScene().environmentTexture;
  44460. }
  44461. return null;
  44462. };
  44463. /**
  44464. * Disposes the resources of the material.
  44465. * @param forceDisposeEffect - Forces the disposal of effects.
  44466. * @param forceDisposeTextures - Forces the disposal of all textures.
  44467. */
  44468. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44469. if (forceDisposeTextures) {
  44470. if (this._albedoTexture) {
  44471. this._albedoTexture.dispose();
  44472. }
  44473. if (this._ambientTexture) {
  44474. this._ambientTexture.dispose();
  44475. }
  44476. if (this._opacityTexture) {
  44477. this._opacityTexture.dispose();
  44478. }
  44479. if (this._reflectionTexture) {
  44480. this._reflectionTexture.dispose();
  44481. }
  44482. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44483. this._environmentBRDFTexture.dispose();
  44484. }
  44485. if (this._emissiveTexture) {
  44486. this._emissiveTexture.dispose();
  44487. }
  44488. if (this._metallicTexture) {
  44489. this._metallicTexture.dispose();
  44490. }
  44491. if (this._reflectivityTexture) {
  44492. this._reflectivityTexture.dispose();
  44493. }
  44494. if (this._bumpTexture) {
  44495. this._bumpTexture.dispose();
  44496. }
  44497. if (this._lightmapTexture) {
  44498. this._lightmapTexture.dispose();
  44499. }
  44500. if (this._refractionTexture) {
  44501. this._refractionTexture.dispose();
  44502. }
  44503. }
  44504. this._renderTargets.dispose();
  44505. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44506. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44507. }
  44508. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44509. };
  44510. /**
  44511. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44512. */
  44513. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44514. /**
  44515. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44516. * to enhance interoperability with other engines.
  44517. */
  44518. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44519. /**
  44520. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44521. * to enhance interoperability with other materials.
  44522. */
  44523. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44524. /**
  44525. * Stores the reflectivity values based on metallic roughness workflow.
  44526. */
  44527. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44528. __decorate([
  44529. BABYLON.serializeAsImageProcessingConfiguration()
  44530. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44531. __decorate([
  44532. BABYLON.serialize()
  44533. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44534. __decorate([
  44535. BABYLON.serialize()
  44536. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44537. return PBRBaseMaterial;
  44538. }(BABYLON.PushMaterial));
  44539. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44540. })(BABYLON || (BABYLON = {}));
  44541. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44542. var BABYLON;
  44543. (function (BABYLON) {
  44544. /**
  44545. * The Physically based simple base material of BJS.
  44546. *
  44547. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44548. * It is used as the base class for both the specGloss and metalRough conventions.
  44549. */
  44550. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44551. __extends(PBRBaseSimpleMaterial, _super);
  44552. /**
  44553. * Instantiates a new PBRMaterial instance.
  44554. *
  44555. * @param name The material name
  44556. * @param scene The scene the material will be use in.
  44557. */
  44558. function PBRBaseSimpleMaterial(name, scene) {
  44559. var _this = _super.call(this, name, scene) || this;
  44560. /**
  44561. * Number of Simultaneous lights allowed on the material.
  44562. */
  44563. _this.maxSimultaneousLights = 4;
  44564. /**
  44565. * If sets to true, disables all the lights affecting the material.
  44566. */
  44567. _this.disableLighting = false;
  44568. /**
  44569. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44570. */
  44571. _this.invertNormalMapX = false;
  44572. /**
  44573. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44574. */
  44575. _this.invertNormalMapY = false;
  44576. /**
  44577. * Emissivie color used to self-illuminate the model.
  44578. */
  44579. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44580. /**
  44581. * Occlusion Channel Strenght.
  44582. */
  44583. _this.occlusionStrength = 1.0;
  44584. _this.useLightmapAsShadowmap = false;
  44585. _this._useAlphaFromAlbedoTexture = true;
  44586. _this._useAmbientInGrayScale = true;
  44587. return _this;
  44588. }
  44589. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44590. /**
  44591. * Gets the current double sided mode.
  44592. */
  44593. get: function () {
  44594. return this._twoSidedLighting;
  44595. },
  44596. /**
  44597. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44598. */
  44599. set: function (value) {
  44600. if (this._twoSidedLighting === value) {
  44601. return;
  44602. }
  44603. this._twoSidedLighting = value;
  44604. this.backFaceCulling = !value;
  44605. this._markAllSubMeshesAsTexturesDirty();
  44606. },
  44607. enumerable: true,
  44608. configurable: true
  44609. });
  44610. /**
  44611. * Return the active textures of the material.
  44612. */
  44613. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44614. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44615. if (this.environmentTexture) {
  44616. activeTextures.push(this.environmentTexture);
  44617. }
  44618. if (this.normalTexture) {
  44619. activeTextures.push(this.normalTexture);
  44620. }
  44621. if (this.emissiveTexture) {
  44622. activeTextures.push(this.emissiveTexture);
  44623. }
  44624. if (this.occlusionTexture) {
  44625. activeTextures.push(this.occlusionTexture);
  44626. }
  44627. if (this.lightmapTexture) {
  44628. activeTextures.push(this.lightmapTexture);
  44629. }
  44630. return activeTextures;
  44631. };
  44632. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44633. if (_super.prototype.hasTexture.call(this, texture)) {
  44634. return true;
  44635. }
  44636. if (this.lightmapTexture === texture) {
  44637. return true;
  44638. }
  44639. return false;
  44640. };
  44641. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44642. return "PBRBaseSimpleMaterial";
  44643. };
  44644. __decorate([
  44645. BABYLON.serialize(),
  44646. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44647. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44648. __decorate([
  44649. BABYLON.serialize(),
  44650. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44651. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44652. __decorate([
  44653. BABYLON.serializeAsTexture(),
  44654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44655. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44656. __decorate([
  44657. BABYLON.serialize(),
  44658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44659. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44660. __decorate([
  44661. BABYLON.serialize(),
  44662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44663. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44664. __decorate([
  44665. BABYLON.serializeAsTexture(),
  44666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44667. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44668. __decorate([
  44669. BABYLON.serializeAsColor3("emissive"),
  44670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44671. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44672. __decorate([
  44673. BABYLON.serializeAsTexture(),
  44674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44675. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44676. __decorate([
  44677. BABYLON.serialize(),
  44678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44679. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44680. __decorate([
  44681. BABYLON.serializeAsTexture(),
  44682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44683. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44684. __decorate([
  44685. BABYLON.serialize(),
  44686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44687. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44688. __decorate([
  44689. BABYLON.serialize()
  44690. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44691. __decorate([
  44692. BABYLON.serializeAsTexture(),
  44693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44694. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44695. __decorate([
  44696. BABYLON.serialize(),
  44697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44698. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44699. return PBRBaseSimpleMaterial;
  44700. }(BABYLON.PBRBaseMaterial));
  44701. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44702. })(BABYLON || (BABYLON = {}));
  44703. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44704. var BABYLON;
  44705. (function (BABYLON) {
  44706. /**
  44707. * The Physically based material of BJS.
  44708. *
  44709. * This offers the main features of a standard PBR material.
  44710. * For more information, please refer to the documentation :
  44711. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44712. */
  44713. var PBRMaterial = /** @class */ (function (_super) {
  44714. __extends(PBRMaterial, _super);
  44715. /**
  44716. * Instantiates a new PBRMaterial instance.
  44717. *
  44718. * @param name The material name
  44719. * @param scene The scene the material will be use in.
  44720. */
  44721. function PBRMaterial(name, scene) {
  44722. var _this = _super.call(this, name, scene) || this;
  44723. /**
  44724. * Intensity of the direct lights e.g. the four lights available in your scene.
  44725. * This impacts both the direct diffuse and specular highlights.
  44726. */
  44727. _this.directIntensity = 1.0;
  44728. /**
  44729. * Intensity of the emissive part of the material.
  44730. * This helps controlling the emissive effect without modifying the emissive color.
  44731. */
  44732. _this.emissiveIntensity = 1.0;
  44733. /**
  44734. * Intensity of the environment e.g. how much the environment will light the object
  44735. * either through harmonics for rough material or through the refelction for shiny ones.
  44736. */
  44737. _this.environmentIntensity = 1.0;
  44738. /**
  44739. * This is a special control allowing the reduction of the specular highlights coming from the
  44740. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44741. */
  44742. _this.specularIntensity = 1.0;
  44743. /**
  44744. * Debug Control allowing disabling the bump map on this material.
  44745. */
  44746. _this.disableBumpMap = false;
  44747. /**
  44748. * AKA Occlusion Texture Intensity in other nomenclature.
  44749. */
  44750. _this.ambientTextureStrength = 1.0;
  44751. /**
  44752. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44753. * 1 means it completely occludes it
  44754. * 0 mean it has no impact
  44755. */
  44756. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44757. /**
  44758. * The color of a material in ambient lighting.
  44759. */
  44760. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44761. /**
  44762. * AKA Diffuse Color in other nomenclature.
  44763. */
  44764. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44765. /**
  44766. * AKA Specular Color in other nomenclature.
  44767. */
  44768. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44769. /**
  44770. * The color reflected from the material.
  44771. */
  44772. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44773. /**
  44774. * The color emitted from the material.
  44775. */
  44776. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44777. /**
  44778. * AKA Glossiness in other nomenclature.
  44779. */
  44780. _this.microSurface = 1.0;
  44781. /**
  44782. * source material index of refraction (IOR)' / 'destination material IOR.
  44783. */
  44784. _this.indexOfRefraction = 0.66;
  44785. /**
  44786. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44787. */
  44788. _this.invertRefractionY = false;
  44789. /**
  44790. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44791. * Materials half opaque for instance using refraction could benefit from this control.
  44792. */
  44793. _this.linkRefractionWithTransparency = false;
  44794. _this.useLightmapAsShadowmap = false;
  44795. /**
  44796. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44797. */
  44798. _this.useAlphaFromAlbedoTexture = false;
  44799. /**
  44800. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44801. */
  44802. _this.forceAlphaTest = false;
  44803. /**
  44804. * Defines the alpha limits in alpha test mode.
  44805. */
  44806. _this.alphaCutOff = 0.4;
  44807. /**
  44808. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44809. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44810. */
  44811. _this.useSpecularOverAlpha = true;
  44812. /**
  44813. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44814. */
  44815. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44816. /**
  44817. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44818. */
  44819. _this.useRoughnessFromMetallicTextureAlpha = true;
  44820. /**
  44821. * Specifies if the metallic texture contains the roughness information in its green channel.
  44822. */
  44823. _this.useRoughnessFromMetallicTextureGreen = false;
  44824. /**
  44825. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44826. */
  44827. _this.useMetallnessFromMetallicTextureBlue = false;
  44828. /**
  44829. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44830. */
  44831. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44832. /**
  44833. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44834. */
  44835. _this.useAmbientInGrayScale = false;
  44836. /**
  44837. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44838. * The material will try to infer what glossiness each pixel should be.
  44839. */
  44840. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44841. /**
  44842. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44843. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44844. */
  44845. _this.useRadianceOverAlpha = true;
  44846. /**
  44847. * Allows using an object space normal map (instead of tangent space).
  44848. */
  44849. _this.useObjectSpaceNormalMap = false;
  44850. /**
  44851. * Allows using the bump map in parallax mode.
  44852. */
  44853. _this.useParallax = false;
  44854. /**
  44855. * Allows using the bump map in parallax occlusion mode.
  44856. */
  44857. _this.useParallaxOcclusion = false;
  44858. /**
  44859. * Controls the scale bias of the parallax mode.
  44860. */
  44861. _this.parallaxScaleBias = 0.05;
  44862. /**
  44863. * If sets to true, disables all the lights affecting the material.
  44864. */
  44865. _this.disableLighting = false;
  44866. /**
  44867. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44868. */
  44869. _this.forceIrradianceInFragment = false;
  44870. /**
  44871. * Number of Simultaneous lights allowed on the material.
  44872. */
  44873. _this.maxSimultaneousLights = 4;
  44874. /**
  44875. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44876. */
  44877. _this.invertNormalMapX = false;
  44878. /**
  44879. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44880. */
  44881. _this.invertNormalMapY = false;
  44882. /**
  44883. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44884. */
  44885. _this.twoSidedLighting = false;
  44886. /**
  44887. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44888. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44889. */
  44890. _this.useAlphaFresnel = false;
  44891. /**
  44892. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44893. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44894. */
  44895. _this.useLinearAlphaFresnel = false;
  44896. /**
  44897. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44898. * And/Or occlude the blended part.
  44899. */
  44900. _this.environmentBRDFTexture = null;
  44901. /**
  44902. * Force normal to face away from face.
  44903. */
  44904. _this.forceNormalForward = false;
  44905. /**
  44906. * Enables specular anti aliasing in the PBR shader.
  44907. * It will both interacts on the Geometry for analytical and IBL lighting.
  44908. * It also prefilter the roughness map based on the bump values.
  44909. */
  44910. _this.enableSpecularAntiAliasing = false;
  44911. /**
  44912. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44913. * makes the reflect vector face the model (under horizon).
  44914. */
  44915. _this.useHorizonOcclusion = true;
  44916. /**
  44917. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44918. * too much the area relying on ambient texture to define their ambient occlusion.
  44919. */
  44920. _this.useRadianceOcclusion = true;
  44921. /**
  44922. * If set to true, no lighting calculations will be applied.
  44923. */
  44924. _this.unlit = false;
  44925. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44926. return _this;
  44927. }
  44928. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  44929. /**
  44930. * BJS is using an harcoded light falloff based on a manually sets up range.
  44931. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44932. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44933. */
  44934. get: function () {
  44935. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44936. },
  44937. /**
  44938. * BJS is using an harcoded light falloff based on a manually sets up range.
  44939. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44940. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44941. */
  44942. set: function (value) {
  44943. if (value !== this.usePhysicalLightFalloff) {
  44944. // Ensure the effect will be rebuilt.
  44945. this._markAllSubMeshesAsTexturesDirty();
  44946. if (value) {
  44947. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44948. }
  44949. else {
  44950. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  44951. }
  44952. }
  44953. },
  44954. enumerable: true,
  44955. configurable: true
  44956. });
  44957. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  44958. /**
  44959. * In order to support the falloff compatibility with gltf, a special mode has been added
  44960. * to reproduce the gltf light falloff.
  44961. */
  44962. get: function () {
  44963. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  44964. },
  44965. /**
  44966. * In order to support the falloff compatibility with gltf, a special mode has been added
  44967. * to reproduce the gltf light falloff.
  44968. */
  44969. set: function (value) {
  44970. if (value !== this.useGLTFLightFalloff) {
  44971. // Ensure the effect will be rebuilt.
  44972. this._markAllSubMeshesAsTexturesDirty();
  44973. if (value) {
  44974. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  44975. }
  44976. else {
  44977. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  44978. }
  44979. }
  44980. },
  44981. enumerable: true,
  44982. configurable: true
  44983. });
  44984. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44985. /**
  44986. * Gets the image processing configuration used either in this material.
  44987. */
  44988. get: function () {
  44989. return this._imageProcessingConfiguration;
  44990. },
  44991. /**
  44992. * Sets the Default image processing configuration used either in the this material.
  44993. *
  44994. * If sets to null, the scene one is in use.
  44995. */
  44996. set: function (value) {
  44997. this._attachImageProcessingConfiguration(value);
  44998. // Ensure the effect will be rebuilt.
  44999. this._markAllSubMeshesAsTexturesDirty();
  45000. },
  45001. enumerable: true,
  45002. configurable: true
  45003. });
  45004. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45005. /**
  45006. * Gets wether the color curves effect is enabled.
  45007. */
  45008. get: function () {
  45009. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45010. },
  45011. /**
  45012. * Sets wether the color curves effect is enabled.
  45013. */
  45014. set: function (value) {
  45015. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45016. },
  45017. enumerable: true,
  45018. configurable: true
  45019. });
  45020. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45021. /**
  45022. * Gets wether the color grading effect is enabled.
  45023. */
  45024. get: function () {
  45025. return this.imageProcessingConfiguration.colorGradingEnabled;
  45026. },
  45027. /**
  45028. * Gets wether the color grading effect is enabled.
  45029. */
  45030. set: function (value) {
  45031. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45032. },
  45033. enumerable: true,
  45034. configurable: true
  45035. });
  45036. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45037. /**
  45038. * Gets wether tonemapping is enabled or not.
  45039. */
  45040. get: function () {
  45041. return this._imageProcessingConfiguration.toneMappingEnabled;
  45042. },
  45043. /**
  45044. * Sets wether tonemapping is enabled or not
  45045. */
  45046. set: function (value) {
  45047. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45048. },
  45049. enumerable: true,
  45050. configurable: true
  45051. });
  45052. ;
  45053. ;
  45054. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45055. /**
  45056. * The camera exposure used on this material.
  45057. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45058. * This corresponds to a photographic exposure.
  45059. */
  45060. get: function () {
  45061. return this._imageProcessingConfiguration.exposure;
  45062. },
  45063. /**
  45064. * The camera exposure used on this material.
  45065. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45066. * This corresponds to a photographic exposure.
  45067. */
  45068. set: function (value) {
  45069. this._imageProcessingConfiguration.exposure = value;
  45070. },
  45071. enumerable: true,
  45072. configurable: true
  45073. });
  45074. ;
  45075. ;
  45076. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45077. /**
  45078. * Gets The camera contrast used on this material.
  45079. */
  45080. get: function () {
  45081. return this._imageProcessingConfiguration.contrast;
  45082. },
  45083. /**
  45084. * Sets The camera contrast used on this material.
  45085. */
  45086. set: function (value) {
  45087. this._imageProcessingConfiguration.contrast = value;
  45088. },
  45089. enumerable: true,
  45090. configurable: true
  45091. });
  45092. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45093. /**
  45094. * Gets the Color Grading 2D Lookup Texture.
  45095. */
  45096. get: function () {
  45097. return this._imageProcessingConfiguration.colorGradingTexture;
  45098. },
  45099. /**
  45100. * Sets the Color Grading 2D Lookup Texture.
  45101. */
  45102. set: function (value) {
  45103. this._imageProcessingConfiguration.colorGradingTexture = value;
  45104. },
  45105. enumerable: true,
  45106. configurable: true
  45107. });
  45108. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45109. /**
  45110. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45111. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45112. * 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;
  45113. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45114. */
  45115. get: function () {
  45116. return this._imageProcessingConfiguration.colorCurves;
  45117. },
  45118. /**
  45119. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45120. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45121. * 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;
  45122. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45123. */
  45124. set: function (value) {
  45125. this._imageProcessingConfiguration.colorCurves = value;
  45126. },
  45127. enumerable: true,
  45128. configurable: true
  45129. });
  45130. /**
  45131. * Returns the name of this material class.
  45132. */
  45133. PBRMaterial.prototype.getClassName = function () {
  45134. return "PBRMaterial";
  45135. };
  45136. /**
  45137. * Returns an array of the actively used textures.
  45138. * @returns - Array of BaseTextures
  45139. */
  45140. PBRMaterial.prototype.getActiveTextures = function () {
  45141. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45142. if (this._albedoTexture) {
  45143. activeTextures.push(this._albedoTexture);
  45144. }
  45145. if (this._ambientTexture) {
  45146. activeTextures.push(this._ambientTexture);
  45147. }
  45148. if (this._opacityTexture) {
  45149. activeTextures.push(this._opacityTexture);
  45150. }
  45151. if (this._reflectionTexture) {
  45152. activeTextures.push(this._reflectionTexture);
  45153. }
  45154. if (this._emissiveTexture) {
  45155. activeTextures.push(this._emissiveTexture);
  45156. }
  45157. if (this._reflectivityTexture) {
  45158. activeTextures.push(this._reflectivityTexture);
  45159. }
  45160. if (this._metallicTexture) {
  45161. activeTextures.push(this._metallicTexture);
  45162. }
  45163. if (this._microSurfaceTexture) {
  45164. activeTextures.push(this._microSurfaceTexture);
  45165. }
  45166. if (this._bumpTexture) {
  45167. activeTextures.push(this._bumpTexture);
  45168. }
  45169. if (this._lightmapTexture) {
  45170. activeTextures.push(this._lightmapTexture);
  45171. }
  45172. if (this._refractionTexture) {
  45173. activeTextures.push(this._refractionTexture);
  45174. }
  45175. return activeTextures;
  45176. };
  45177. /**
  45178. * Checks to see if a texture is used in the material.
  45179. * @param texture - Base texture to use.
  45180. * @returns - Boolean specifying if a texture is used in the material.
  45181. */
  45182. PBRMaterial.prototype.hasTexture = function (texture) {
  45183. if (_super.prototype.hasTexture.call(this, texture)) {
  45184. return true;
  45185. }
  45186. if (this._albedoTexture === texture) {
  45187. return true;
  45188. }
  45189. if (this._ambientTexture === texture) {
  45190. return true;
  45191. }
  45192. if (this._opacityTexture === texture) {
  45193. return true;
  45194. }
  45195. if (this._reflectionTexture === texture) {
  45196. return true;
  45197. }
  45198. if (this._reflectivityTexture === texture) {
  45199. return true;
  45200. }
  45201. if (this._metallicTexture === texture) {
  45202. return true;
  45203. }
  45204. if (this._microSurfaceTexture === texture) {
  45205. return true;
  45206. }
  45207. if (this._bumpTexture === texture) {
  45208. return true;
  45209. }
  45210. if (this._lightmapTexture === texture) {
  45211. return true;
  45212. }
  45213. if (this._refractionTexture === texture) {
  45214. return true;
  45215. }
  45216. return false;
  45217. };
  45218. /**
  45219. * Makes a duplicate of the current material.
  45220. * @param name - name to use for the new material.
  45221. */
  45222. PBRMaterial.prototype.clone = function (name) {
  45223. var _this = this;
  45224. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45225. clone.id = name;
  45226. clone.name = name;
  45227. return clone;
  45228. };
  45229. /**
  45230. * Serializes this PBR Material.
  45231. * @returns - An object with the serialized material.
  45232. */
  45233. PBRMaterial.prototype.serialize = function () {
  45234. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45235. serializationObject.customType = "BABYLON.PBRMaterial";
  45236. return serializationObject;
  45237. };
  45238. // Statics
  45239. /**
  45240. * Parses a PBR Material from a serialized object.
  45241. * @param source - Serialized object.
  45242. * @param scene - BJS scene instance.
  45243. * @param rootUrl - url for the scene object
  45244. * @returns - PBRMaterial
  45245. */
  45246. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45247. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45248. };
  45249. /**
  45250. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45251. */
  45252. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45253. /**
  45254. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45255. */
  45256. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45257. /**
  45258. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45259. */
  45260. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45261. /**
  45262. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45263. * They are also discarded below the alpha cutoff threshold to improve performances.
  45264. */
  45265. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45266. /**
  45267. * Defines the default value of how much AO map is occluding the analytical lights
  45268. * (point spot...).
  45269. */
  45270. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45271. __decorate([
  45272. BABYLON.serialize(),
  45273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45274. ], PBRMaterial.prototype, "directIntensity", void 0);
  45275. __decorate([
  45276. BABYLON.serialize(),
  45277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45278. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45279. __decorate([
  45280. BABYLON.serialize(),
  45281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45282. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45283. __decorate([
  45284. BABYLON.serialize(),
  45285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45286. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45287. __decorate([
  45288. BABYLON.serialize(),
  45289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45290. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45291. __decorate([
  45292. BABYLON.serializeAsTexture(),
  45293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45294. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45295. __decorate([
  45296. BABYLON.serializeAsTexture(),
  45297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45298. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45299. __decorate([
  45300. BABYLON.serialize(),
  45301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45302. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45303. __decorate([
  45304. BABYLON.serialize(),
  45305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45306. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45307. __decorate([
  45308. BABYLON.serializeAsTexture(),
  45309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45310. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45311. __decorate([
  45312. BABYLON.serializeAsTexture(),
  45313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45314. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45315. __decorate([
  45316. BABYLON.serializeAsTexture(),
  45317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45318. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45319. __decorate([
  45320. BABYLON.serializeAsTexture(),
  45321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45322. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45323. __decorate([
  45324. BABYLON.serializeAsTexture(),
  45325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45326. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45327. __decorate([
  45328. BABYLON.serialize(),
  45329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45330. ], PBRMaterial.prototype, "metallic", void 0);
  45331. __decorate([
  45332. BABYLON.serialize(),
  45333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45334. ], PBRMaterial.prototype, "roughness", void 0);
  45335. __decorate([
  45336. BABYLON.serializeAsTexture(),
  45337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45338. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45339. __decorate([
  45340. BABYLON.serializeAsTexture(),
  45341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45342. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45343. __decorate([
  45344. BABYLON.serializeAsTexture(),
  45345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45346. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45347. __decorate([
  45348. BABYLON.serializeAsTexture(),
  45349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45350. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45351. __decorate([
  45352. BABYLON.serializeAsColor3("ambient"),
  45353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45354. ], PBRMaterial.prototype, "ambientColor", void 0);
  45355. __decorate([
  45356. BABYLON.serializeAsColor3("albedo"),
  45357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45358. ], PBRMaterial.prototype, "albedoColor", void 0);
  45359. __decorate([
  45360. BABYLON.serializeAsColor3("reflectivity"),
  45361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45362. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45363. __decorate([
  45364. BABYLON.serializeAsColor3("reflection"),
  45365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45366. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45367. __decorate([
  45368. BABYLON.serializeAsColor3("emissive"),
  45369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45370. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45371. __decorate([
  45372. BABYLON.serialize(),
  45373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45374. ], PBRMaterial.prototype, "microSurface", void 0);
  45375. __decorate([
  45376. BABYLON.serialize(),
  45377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45378. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45379. __decorate([
  45380. BABYLON.serialize(),
  45381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45382. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45383. __decorate([
  45384. BABYLON.serialize(),
  45385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45386. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45387. __decorate([
  45388. BABYLON.serialize(),
  45389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45390. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45391. __decorate([
  45392. BABYLON.serialize(),
  45393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45394. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45395. __decorate([
  45396. BABYLON.serialize(),
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45398. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45399. __decorate([
  45400. BABYLON.serialize(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45402. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45403. __decorate([
  45404. BABYLON.serialize(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45406. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45407. __decorate([
  45408. BABYLON.serialize(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45411. __decorate([
  45412. BABYLON.serialize(),
  45413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45414. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45415. __decorate([
  45416. BABYLON.serialize(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45418. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45419. __decorate([
  45420. BABYLON.serialize(),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45422. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45423. __decorate([
  45424. BABYLON.serialize(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45426. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45427. __decorate([
  45428. BABYLON.serialize(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45430. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45431. __decorate([
  45432. BABYLON.serialize(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45434. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45435. __decorate([
  45436. BABYLON.serialize()
  45437. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45438. __decorate([
  45439. BABYLON.serialize()
  45440. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45441. __decorate([
  45442. BABYLON.serialize(),
  45443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45444. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45445. __decorate([
  45446. BABYLON.serialize(),
  45447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45448. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45449. __decorate([
  45450. BABYLON.serialize(),
  45451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45452. ], PBRMaterial.prototype, "useParallax", void 0);
  45453. __decorate([
  45454. BABYLON.serialize(),
  45455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45456. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45457. __decorate([
  45458. BABYLON.serialize(),
  45459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45460. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45461. __decorate([
  45462. BABYLON.serialize(),
  45463. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45464. ], PBRMaterial.prototype, "disableLighting", void 0);
  45465. __decorate([
  45466. BABYLON.serialize(),
  45467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45468. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45469. __decorate([
  45470. BABYLON.serialize(),
  45471. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45472. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45473. __decorate([
  45474. BABYLON.serialize(),
  45475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45476. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45477. __decorate([
  45478. BABYLON.serialize(),
  45479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45480. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45481. __decorate([
  45482. BABYLON.serialize(),
  45483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45484. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45485. __decorate([
  45486. BABYLON.serialize(),
  45487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45488. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45489. __decorate([
  45490. BABYLON.serialize(),
  45491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45492. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45493. __decorate([
  45494. BABYLON.serializeAsTexture(),
  45495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45496. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45497. __decorate([
  45498. BABYLON.serialize(),
  45499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45500. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45501. __decorate([
  45502. BABYLON.serialize(),
  45503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45504. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45505. __decorate([
  45506. BABYLON.serialize(),
  45507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45508. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45509. __decorate([
  45510. BABYLON.serialize(),
  45511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45512. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45513. __decorate([
  45514. BABYLON.serialize(),
  45515. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45516. ], PBRMaterial.prototype, "unlit", void 0);
  45517. return PBRMaterial;
  45518. }(BABYLON.PBRBaseMaterial));
  45519. BABYLON.PBRMaterial = PBRMaterial;
  45520. })(BABYLON || (BABYLON = {}));
  45521. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45522. var BABYLON;
  45523. (function (BABYLON) {
  45524. /**
  45525. * The PBR material of BJS following the metal roughness convention.
  45526. *
  45527. * This fits to the PBR convention in the GLTF definition:
  45528. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45529. */
  45530. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45531. __extends(PBRMetallicRoughnessMaterial, _super);
  45532. /**
  45533. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45534. *
  45535. * @param name The material name
  45536. * @param scene The scene the material will be use in.
  45537. */
  45538. function PBRMetallicRoughnessMaterial(name, scene) {
  45539. var _this = _super.call(this, name, scene) || this;
  45540. _this._useRoughnessFromMetallicTextureAlpha = false;
  45541. _this._useRoughnessFromMetallicTextureGreen = true;
  45542. _this._useMetallnessFromMetallicTextureBlue = true;
  45543. _this.metallic = 1.0;
  45544. _this.roughness = 1.0;
  45545. return _this;
  45546. }
  45547. /**
  45548. * Return the currrent class name of the material.
  45549. */
  45550. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45551. return "PBRMetallicRoughnessMaterial";
  45552. };
  45553. /**
  45554. * Return the active textures of the material.
  45555. */
  45556. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45557. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45558. if (this.baseTexture) {
  45559. activeTextures.push(this.baseTexture);
  45560. }
  45561. if (this.metallicRoughnessTexture) {
  45562. activeTextures.push(this.metallicRoughnessTexture);
  45563. }
  45564. return activeTextures;
  45565. };
  45566. /**
  45567. * Checks to see if a texture is used in the material.
  45568. * @param texture - Base texture to use.
  45569. * @returns - Boolean specifying if a texture is used in the material.
  45570. */
  45571. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45572. if (_super.prototype.hasTexture.call(this, texture)) {
  45573. return true;
  45574. }
  45575. if (this.baseTexture === texture) {
  45576. return true;
  45577. }
  45578. if (this.metallicRoughnessTexture === texture) {
  45579. return true;
  45580. }
  45581. return false;
  45582. };
  45583. /**
  45584. * Makes a duplicate of the current material.
  45585. * @param name - name to use for the new material.
  45586. */
  45587. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45588. var _this = this;
  45589. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45590. clone.id = name;
  45591. clone.name = name;
  45592. return clone;
  45593. };
  45594. /**
  45595. * Serialize the material to a parsable JSON object.
  45596. */
  45597. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45598. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45599. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45600. return serializationObject;
  45601. };
  45602. /**
  45603. * Parses a JSON object correponding to the serialize function.
  45604. */
  45605. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45606. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45607. };
  45608. __decorate([
  45609. BABYLON.serializeAsColor3(),
  45610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45611. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45612. __decorate([
  45613. BABYLON.serializeAsTexture(),
  45614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45615. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45616. __decorate([
  45617. BABYLON.serialize(),
  45618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45619. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45620. __decorate([
  45621. BABYLON.serialize(),
  45622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45623. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45624. __decorate([
  45625. BABYLON.serializeAsTexture(),
  45626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45627. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45628. return PBRMetallicRoughnessMaterial;
  45629. }(BABYLON.PBRBaseSimpleMaterial));
  45630. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45631. })(BABYLON || (BABYLON = {}));
  45632. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45633. var BABYLON;
  45634. (function (BABYLON) {
  45635. /**
  45636. * The PBR material of BJS following the specular glossiness convention.
  45637. *
  45638. * This fits to the PBR convention in the GLTF definition:
  45639. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45640. */
  45641. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45642. __extends(PBRSpecularGlossinessMaterial, _super);
  45643. /**
  45644. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45645. *
  45646. * @param name The material name
  45647. * @param scene The scene the material will be use in.
  45648. */
  45649. function PBRSpecularGlossinessMaterial(name, scene) {
  45650. var _this = _super.call(this, name, scene) || this;
  45651. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45652. return _this;
  45653. }
  45654. /**
  45655. * Return the currrent class name of the material.
  45656. */
  45657. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45658. return "PBRSpecularGlossinessMaterial";
  45659. };
  45660. /**
  45661. * Return the active textures of the material.
  45662. */
  45663. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45664. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45665. if (this.diffuseTexture) {
  45666. activeTextures.push(this.diffuseTexture);
  45667. }
  45668. if (this.specularGlossinessTexture) {
  45669. activeTextures.push(this.specularGlossinessTexture);
  45670. }
  45671. return activeTextures;
  45672. };
  45673. /**
  45674. * Checks to see if a texture is used in the material.
  45675. * @param texture - Base texture to use.
  45676. * @returns - Boolean specifying if a texture is used in the material.
  45677. */
  45678. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45679. if (_super.prototype.hasTexture.call(this, texture)) {
  45680. return true;
  45681. }
  45682. if (this.diffuseTexture === texture) {
  45683. return true;
  45684. }
  45685. if (this.specularGlossinessTexture === texture) {
  45686. return true;
  45687. }
  45688. return false;
  45689. };
  45690. /**
  45691. * Makes a duplicate of the current material.
  45692. * @param name - name to use for the new material.
  45693. */
  45694. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45695. var _this = this;
  45696. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45697. clone.id = name;
  45698. clone.name = name;
  45699. return clone;
  45700. };
  45701. /**
  45702. * Serialize the material to a parsable JSON object.
  45703. */
  45704. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45705. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45706. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45707. return serializationObject;
  45708. };
  45709. /**
  45710. * Parses a JSON object correponding to the serialize function.
  45711. */
  45712. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45713. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45714. };
  45715. __decorate([
  45716. BABYLON.serializeAsColor3("diffuse"),
  45717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45718. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45719. __decorate([
  45720. BABYLON.serializeAsTexture(),
  45721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45722. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45723. __decorate([
  45724. BABYLON.serializeAsColor3("specular"),
  45725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45726. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45727. __decorate([
  45728. BABYLON.serialize(),
  45729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45730. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45731. __decorate([
  45732. BABYLON.serializeAsTexture(),
  45733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45734. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45735. return PBRSpecularGlossinessMaterial;
  45736. }(BABYLON.PBRBaseSimpleMaterial));
  45737. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45738. })(BABYLON || (BABYLON = {}));
  45739. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45740. var BABYLON;
  45741. (function (BABYLON) {
  45742. BABYLON.CameraInputTypes = {};
  45743. var CameraInputsManager = /** @class */ (function () {
  45744. function CameraInputsManager(camera) {
  45745. this.attached = {};
  45746. this.camera = camera;
  45747. this.checkInputs = function () { };
  45748. }
  45749. /**
  45750. * Add an input method to a camera
  45751. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45752. * @param input camera input method
  45753. */
  45754. CameraInputsManager.prototype.add = function (input) {
  45755. var type = input.getSimpleName();
  45756. if (this.attached[type]) {
  45757. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45758. return;
  45759. }
  45760. this.attached[type] = input;
  45761. input.camera = this.camera;
  45762. //for checkInputs, we are dynamically creating a function
  45763. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45764. if (input.checkInputs) {
  45765. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45766. }
  45767. if (this.attachedElement) {
  45768. input.attachControl(this.attachedElement);
  45769. }
  45770. };
  45771. /**
  45772. * Remove a specific input method from a camera
  45773. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45774. * @param inputToRemove camera input method
  45775. */
  45776. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45777. for (var cam in this.attached) {
  45778. var input = this.attached[cam];
  45779. if (input === inputToRemove) {
  45780. input.detachControl(this.attachedElement);
  45781. input.camera = null;
  45782. delete this.attached[cam];
  45783. this.rebuildInputCheck();
  45784. }
  45785. }
  45786. };
  45787. CameraInputsManager.prototype.removeByType = function (inputType) {
  45788. for (var cam in this.attached) {
  45789. var input = this.attached[cam];
  45790. if (input.getClassName() === inputType) {
  45791. input.detachControl(this.attachedElement);
  45792. input.camera = null;
  45793. delete this.attached[cam];
  45794. this.rebuildInputCheck();
  45795. }
  45796. }
  45797. };
  45798. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45799. var current = this.checkInputs;
  45800. return function () {
  45801. current();
  45802. fn();
  45803. };
  45804. };
  45805. CameraInputsManager.prototype.attachInput = function (input) {
  45806. if (this.attachedElement) {
  45807. input.attachControl(this.attachedElement, this.noPreventDefault);
  45808. }
  45809. };
  45810. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45811. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45812. if (this.attachedElement) {
  45813. return;
  45814. }
  45815. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45816. this.attachedElement = element;
  45817. this.noPreventDefault = noPreventDefault;
  45818. for (var cam in this.attached) {
  45819. this.attached[cam].attachControl(element, noPreventDefault);
  45820. }
  45821. };
  45822. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45823. if (disconnect === void 0) { disconnect = false; }
  45824. if (this.attachedElement !== element) {
  45825. return;
  45826. }
  45827. for (var cam in this.attached) {
  45828. this.attached[cam].detachControl(element);
  45829. if (disconnect) {
  45830. this.attached[cam].camera = null;
  45831. }
  45832. }
  45833. this.attachedElement = null;
  45834. };
  45835. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45836. this.checkInputs = function () { };
  45837. for (var cam in this.attached) {
  45838. var input = this.attached[cam];
  45839. if (input.checkInputs) {
  45840. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45841. }
  45842. }
  45843. };
  45844. /**
  45845. * Remove all attached input methods from a camera
  45846. */
  45847. CameraInputsManager.prototype.clear = function () {
  45848. if (this.attachedElement) {
  45849. this.detachElement(this.attachedElement, true);
  45850. }
  45851. this.attached = {};
  45852. this.attachedElement = null;
  45853. this.checkInputs = function () { };
  45854. };
  45855. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45856. var inputs = {};
  45857. for (var cam in this.attached) {
  45858. var input = this.attached[cam];
  45859. var res = BABYLON.SerializationHelper.Serialize(input);
  45860. inputs[input.getClassName()] = res;
  45861. }
  45862. serializedCamera.inputsmgr = inputs;
  45863. };
  45864. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45865. var parsedInputs = parsedCamera.inputsmgr;
  45866. if (parsedInputs) {
  45867. this.clear();
  45868. for (var n in parsedInputs) {
  45869. var construct = BABYLON.CameraInputTypes[n];
  45870. if (construct) {
  45871. var parsedinput = parsedInputs[n];
  45872. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45873. this.add(input);
  45874. }
  45875. }
  45876. }
  45877. else {
  45878. //2016-03-08 this part is for managing backward compatibility
  45879. for (var n in this.attached) {
  45880. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45881. if (construct) {
  45882. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45883. this.remove(this.attached[n]);
  45884. this.add(input);
  45885. }
  45886. }
  45887. }
  45888. };
  45889. return CameraInputsManager;
  45890. }());
  45891. BABYLON.CameraInputsManager = CameraInputsManager;
  45892. })(BABYLON || (BABYLON = {}));
  45893. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45894. var BABYLON;
  45895. (function (BABYLON) {
  45896. var TargetCamera = /** @class */ (function (_super) {
  45897. __extends(TargetCamera, _super);
  45898. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45899. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45900. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45901. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45902. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45903. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45904. _this.speed = 2.0;
  45905. _this.noRotationConstraint = false;
  45906. _this.lockedTarget = null;
  45907. /** @hidden */
  45908. _this._currentTarget = BABYLON.Vector3.Zero();
  45909. /** @hidden */
  45910. _this._viewMatrix = BABYLON.Matrix.Zero();
  45911. /** @hidden */
  45912. _this._camMatrix = BABYLON.Matrix.Zero();
  45913. /** @hidden */
  45914. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45915. /** @hidden */
  45916. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45917. /** @hidden */
  45918. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45919. /** @hidden */
  45920. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45921. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45922. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45923. _this._defaultUp = BABYLON.Vector3.Up();
  45924. _this._cachedRotationZ = 0;
  45925. return _this;
  45926. }
  45927. TargetCamera.prototype.getFrontPosition = function (distance) {
  45928. this.getWorldMatrix();
  45929. var direction = this.getTarget().subtract(this.position);
  45930. direction.normalize();
  45931. direction.scaleInPlace(distance);
  45932. return this.globalPosition.add(direction);
  45933. };
  45934. /** @hidden */
  45935. TargetCamera.prototype._getLockedTargetPosition = function () {
  45936. if (!this.lockedTarget) {
  45937. return null;
  45938. }
  45939. if (this.lockedTarget.absolutePosition) {
  45940. this.lockedTarget.computeWorldMatrix();
  45941. }
  45942. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45943. };
  45944. TargetCamera.prototype.storeState = function () {
  45945. this._storedPosition = this.position.clone();
  45946. this._storedRotation = this.rotation.clone();
  45947. if (this.rotationQuaternion) {
  45948. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45949. }
  45950. return _super.prototype.storeState.call(this);
  45951. };
  45952. /**
  45953. * Restored camera state. You must call storeState() first
  45954. * @returns whether it was successful or not
  45955. * @hidden
  45956. */
  45957. TargetCamera.prototype._restoreStateValues = function () {
  45958. if (!_super.prototype._restoreStateValues.call(this)) {
  45959. return false;
  45960. }
  45961. this.position = this._storedPosition.clone();
  45962. this.rotation = this._storedRotation.clone();
  45963. if (this.rotationQuaternion) {
  45964. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45965. }
  45966. this.cameraDirection.copyFromFloats(0, 0, 0);
  45967. this.cameraRotation.copyFromFloats(0, 0);
  45968. return true;
  45969. };
  45970. // Cache
  45971. /** @hidden */
  45972. TargetCamera.prototype._initCache = function () {
  45973. _super.prototype._initCache.call(this);
  45974. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45975. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45976. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45977. };
  45978. /** @hidden */
  45979. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45980. if (!ignoreParentClass) {
  45981. _super.prototype._updateCache.call(this);
  45982. }
  45983. var lockedTargetPosition = this._getLockedTargetPosition();
  45984. if (!lockedTargetPosition) {
  45985. this._cache.lockedTarget = null;
  45986. }
  45987. else {
  45988. if (!this._cache.lockedTarget) {
  45989. this._cache.lockedTarget = lockedTargetPosition.clone();
  45990. }
  45991. else {
  45992. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45993. }
  45994. }
  45995. this._cache.rotation.copyFrom(this.rotation);
  45996. if (this.rotationQuaternion)
  45997. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45998. };
  45999. // Synchronized
  46000. /** @hidden */
  46001. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46002. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46003. return false;
  46004. }
  46005. var lockedTargetPosition = this._getLockedTargetPosition();
  46006. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46007. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46008. };
  46009. // Methods
  46010. /** @hidden */
  46011. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46012. var engine = this.getEngine();
  46013. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46014. };
  46015. // Target
  46016. /** @hidden */
  46017. TargetCamera.prototype.setTarget = function (target) {
  46018. this.upVector.normalize();
  46019. if (this.position.z === target.z) {
  46020. this.position.z += BABYLON.Epsilon;
  46021. }
  46022. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46023. this._camMatrix.invert();
  46024. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46025. var vDir = target.subtract(this.position);
  46026. if (vDir.x >= 0.0) {
  46027. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46028. }
  46029. else {
  46030. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46031. }
  46032. this.rotation.z = 0;
  46033. if (isNaN(this.rotation.x)) {
  46034. this.rotation.x = 0;
  46035. }
  46036. if (isNaN(this.rotation.y)) {
  46037. this.rotation.y = 0;
  46038. }
  46039. if (isNaN(this.rotation.z)) {
  46040. this.rotation.z = 0;
  46041. }
  46042. if (this.rotationQuaternion) {
  46043. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46044. }
  46045. };
  46046. /**
  46047. * Return the current target position of the camera. This value is expressed in local space.
  46048. */
  46049. TargetCamera.prototype.getTarget = function () {
  46050. return this._currentTarget;
  46051. };
  46052. /** @hidden */
  46053. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46054. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46055. };
  46056. /** @hidden */
  46057. TargetCamera.prototype._updatePosition = function () {
  46058. if (this.parent) {
  46059. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46060. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46061. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46062. return;
  46063. }
  46064. this.position.addInPlace(this.cameraDirection);
  46065. };
  46066. /** @hidden */
  46067. TargetCamera.prototype._checkInputs = function () {
  46068. var needToMove = this._decideIfNeedsToMove();
  46069. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46070. // Move
  46071. if (needToMove) {
  46072. this._updatePosition();
  46073. }
  46074. // Rotate
  46075. if (needToRotate) {
  46076. this.rotation.x += this.cameraRotation.x;
  46077. this.rotation.y += this.cameraRotation.y;
  46078. //rotate, if quaternion is set and rotation was used
  46079. if (this.rotationQuaternion) {
  46080. var len = this.rotation.lengthSquared();
  46081. if (len) {
  46082. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46083. }
  46084. }
  46085. if (!this.noRotationConstraint) {
  46086. var limit = (Math.PI / 2) * 0.95;
  46087. if (this.rotation.x > limit)
  46088. this.rotation.x = limit;
  46089. if (this.rotation.x < -limit)
  46090. this.rotation.x = -limit;
  46091. }
  46092. }
  46093. // Inertia
  46094. if (needToMove) {
  46095. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46096. this.cameraDirection.x = 0;
  46097. }
  46098. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46099. this.cameraDirection.y = 0;
  46100. }
  46101. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46102. this.cameraDirection.z = 0;
  46103. }
  46104. this.cameraDirection.scaleInPlace(this.inertia);
  46105. }
  46106. if (needToRotate) {
  46107. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46108. this.cameraRotation.x = 0;
  46109. }
  46110. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46111. this.cameraRotation.y = 0;
  46112. }
  46113. this.cameraRotation.scaleInPlace(this.inertia);
  46114. }
  46115. _super.prototype._checkInputs.call(this);
  46116. };
  46117. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46118. if (this.rotationQuaternion) {
  46119. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46120. }
  46121. else {
  46122. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46123. }
  46124. };
  46125. /**
  46126. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  46127. * @returns the current camera
  46128. */
  46129. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46130. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46131. return this;
  46132. };
  46133. /** @hidden */
  46134. TargetCamera.prototype._getViewMatrix = function () {
  46135. if (this.lockedTarget) {
  46136. this.setTarget(this._getLockedTargetPosition());
  46137. }
  46138. // Compute
  46139. this._updateCameraRotationMatrix();
  46140. // Apply the changed rotation to the upVector.
  46141. if (this._cachedRotationZ != this.rotation.z) {
  46142. this._rotateUpVectorWithCameraRotationMatrix();
  46143. this._cachedRotationZ = this.rotation.z;
  46144. }
  46145. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46146. // Computing target and final matrix
  46147. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46148. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46149. return this._viewMatrix;
  46150. };
  46151. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46152. if (this.parent) {
  46153. var parentWorldMatrix = this.parent.getWorldMatrix();
  46154. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46155. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46156. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46157. this._markSyncedWithParent();
  46158. }
  46159. else {
  46160. this._globalPosition.copyFrom(position);
  46161. this._globalCurrentTarget.copyFrom(target);
  46162. this._globalCurrentUpVector.copyFrom(up);
  46163. }
  46164. if (this.getScene().useRightHandedSystem) {
  46165. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46166. }
  46167. else {
  46168. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46169. }
  46170. };
  46171. /**
  46172. * @override
  46173. * Override Camera.createRigCamera
  46174. */
  46175. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46176. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46177. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46178. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46179. if (!this.rotationQuaternion) {
  46180. this.rotationQuaternion = new BABYLON.Quaternion();
  46181. }
  46182. rigCamera._cameraRigParams = {};
  46183. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46184. }
  46185. return rigCamera;
  46186. }
  46187. return null;
  46188. };
  46189. /**
  46190. * @hidden
  46191. * @override
  46192. * Override Camera._updateRigCameras
  46193. */
  46194. TargetCamera.prototype._updateRigCameras = function () {
  46195. var camLeft = this._rigCameras[0];
  46196. var camRight = this._rigCameras[1];
  46197. switch (this.cameraRigMode) {
  46198. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46199. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46200. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46201. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46202. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46203. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46204. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46205. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46206. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46207. camLeft.setTarget(this.getTarget());
  46208. camRight.setTarget(this.getTarget());
  46209. break;
  46210. case BABYLON.Camera.RIG_MODE_VR:
  46211. if (camLeft.rotationQuaternion) {
  46212. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46213. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46214. }
  46215. else {
  46216. camLeft.rotation.copyFrom(this.rotation);
  46217. camRight.rotation.copyFrom(this.rotation);
  46218. }
  46219. camLeft.position.copyFrom(this.position);
  46220. camRight.position.copyFrom(this.position);
  46221. break;
  46222. }
  46223. _super.prototype._updateRigCameras.call(this);
  46224. };
  46225. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46226. if (!this._rigCamTransformMatrix) {
  46227. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46228. }
  46229. var target = this.getTarget();
  46230. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46231. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46232. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46233. };
  46234. TargetCamera.prototype.getClassName = function () {
  46235. return "TargetCamera";
  46236. };
  46237. __decorate([
  46238. BABYLON.serializeAsVector3()
  46239. ], TargetCamera.prototype, "rotation", void 0);
  46240. __decorate([
  46241. BABYLON.serialize()
  46242. ], TargetCamera.prototype, "speed", void 0);
  46243. __decorate([
  46244. BABYLON.serializeAsMeshReference("lockedTargetId")
  46245. ], TargetCamera.prototype, "lockedTarget", void 0);
  46246. return TargetCamera;
  46247. }(BABYLON.Camera));
  46248. BABYLON.TargetCamera = TargetCamera;
  46249. })(BABYLON || (BABYLON = {}));
  46250. //# sourceMappingURL=babylon.targetCamera.js.map
  46251. var BABYLON;
  46252. (function (BABYLON) {
  46253. var FreeCameraMouseInput = /** @class */ (function () {
  46254. function FreeCameraMouseInput(touchEnabled) {
  46255. if (touchEnabled === void 0) { touchEnabled = true; }
  46256. this.touchEnabled = touchEnabled;
  46257. this.buttons = [0, 1, 2];
  46258. this.angularSensibility = 2000.0;
  46259. this.previousPosition = null;
  46260. }
  46261. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46262. var _this = this;
  46263. var engine = this.camera.getEngine();
  46264. if (!this._pointerInput) {
  46265. this._pointerInput = function (p, s) {
  46266. var evt = p.event;
  46267. if (engine.isInVRExclusivePointerMode) {
  46268. return;
  46269. }
  46270. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46271. return;
  46272. }
  46273. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46274. return;
  46275. }
  46276. var srcElement = (evt.srcElement || evt.target);
  46277. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46278. try {
  46279. srcElement.setPointerCapture(evt.pointerId);
  46280. }
  46281. catch (e) {
  46282. //Nothing to do with the error. Execution will continue.
  46283. }
  46284. _this.previousPosition = {
  46285. x: evt.clientX,
  46286. y: evt.clientY
  46287. };
  46288. if (!noPreventDefault) {
  46289. evt.preventDefault();
  46290. element.focus();
  46291. }
  46292. }
  46293. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46294. try {
  46295. srcElement.releasePointerCapture(evt.pointerId);
  46296. }
  46297. catch (e) {
  46298. //Nothing to do with the error.
  46299. }
  46300. _this.previousPosition = null;
  46301. if (!noPreventDefault) {
  46302. evt.preventDefault();
  46303. }
  46304. }
  46305. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46306. if (!_this.previousPosition || engine.isPointerLock) {
  46307. return;
  46308. }
  46309. var offsetX = evt.clientX - _this.previousPosition.x;
  46310. if (_this.camera.getScene().useRightHandedSystem)
  46311. offsetX *= -1;
  46312. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46313. offsetX *= -1;
  46314. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46315. var offsetY = evt.clientY - _this.previousPosition.y;
  46316. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46317. _this.previousPosition = {
  46318. x: evt.clientX,
  46319. y: evt.clientY
  46320. };
  46321. if (!noPreventDefault) {
  46322. evt.preventDefault();
  46323. }
  46324. }
  46325. };
  46326. }
  46327. this._onMouseMove = function (evt) {
  46328. if (!engine.isPointerLock) {
  46329. return;
  46330. }
  46331. if (engine.isInVRExclusivePointerMode) {
  46332. return;
  46333. }
  46334. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46335. if (_this.camera.getScene().useRightHandedSystem)
  46336. offsetX *= -1;
  46337. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46338. offsetX *= -1;
  46339. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46340. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46341. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46342. _this.previousPosition = null;
  46343. if (!noPreventDefault) {
  46344. evt.preventDefault();
  46345. }
  46346. };
  46347. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46348. element.addEventListener("mousemove", this._onMouseMove, false);
  46349. };
  46350. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46351. if (this._observer && element) {
  46352. this.camera.getScene().onPointerObservable.remove(this._observer);
  46353. if (this._onMouseMove) {
  46354. element.removeEventListener("mousemove", this._onMouseMove);
  46355. }
  46356. this._observer = null;
  46357. this._onMouseMove = null;
  46358. this.previousPosition = null;
  46359. }
  46360. };
  46361. FreeCameraMouseInput.prototype.getClassName = function () {
  46362. return "FreeCameraMouseInput";
  46363. };
  46364. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46365. return "mouse";
  46366. };
  46367. __decorate([
  46368. BABYLON.serialize()
  46369. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46370. __decorate([
  46371. BABYLON.serialize()
  46372. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46373. return FreeCameraMouseInput;
  46374. }());
  46375. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46376. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46377. })(BABYLON || (BABYLON = {}));
  46378. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46379. var BABYLON;
  46380. (function (BABYLON) {
  46381. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46382. function FreeCameraKeyboardMoveInput() {
  46383. this._keys = new Array();
  46384. this.keysUp = [38];
  46385. this.keysDown = [40];
  46386. this.keysLeft = [37];
  46387. this.keysRight = [39];
  46388. }
  46389. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46390. var _this = this;
  46391. if (this._onCanvasBlurObserver) {
  46392. return;
  46393. }
  46394. this._scene = this.camera.getScene();
  46395. this._engine = this._scene.getEngine();
  46396. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46397. _this._keys = [];
  46398. });
  46399. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46400. var evt = info.event;
  46401. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46402. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46403. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46404. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46405. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46406. var index = _this._keys.indexOf(evt.keyCode);
  46407. if (index === -1) {
  46408. _this._keys.push(evt.keyCode);
  46409. }
  46410. if (!noPreventDefault) {
  46411. evt.preventDefault();
  46412. }
  46413. }
  46414. }
  46415. else {
  46416. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46417. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46418. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46419. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46420. var index = _this._keys.indexOf(evt.keyCode);
  46421. if (index >= 0) {
  46422. _this._keys.splice(index, 1);
  46423. }
  46424. if (!noPreventDefault) {
  46425. evt.preventDefault();
  46426. }
  46427. }
  46428. }
  46429. });
  46430. };
  46431. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46432. if (this._scene) {
  46433. if (this._onKeyboardObserver) {
  46434. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46435. }
  46436. if (this._onCanvasBlurObserver) {
  46437. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46438. }
  46439. this._onKeyboardObserver = null;
  46440. this._onCanvasBlurObserver = null;
  46441. }
  46442. this._keys = [];
  46443. };
  46444. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46445. if (this._onKeyboardObserver) {
  46446. var camera = this.camera;
  46447. // Keyboard
  46448. for (var index = 0; index < this._keys.length; index++) {
  46449. var keyCode = this._keys[index];
  46450. var speed = camera._computeLocalCameraSpeed();
  46451. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46452. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46453. }
  46454. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46455. camera._localDirection.copyFromFloats(0, 0, speed);
  46456. }
  46457. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46458. camera._localDirection.copyFromFloats(speed, 0, 0);
  46459. }
  46460. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46461. camera._localDirection.copyFromFloats(0, 0, -speed);
  46462. }
  46463. if (camera.getScene().useRightHandedSystem) {
  46464. camera._localDirection.z *= -1;
  46465. }
  46466. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46467. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46468. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46469. }
  46470. }
  46471. };
  46472. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46473. return "FreeCameraKeyboardMoveInput";
  46474. };
  46475. /** @hidden */
  46476. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46477. this._keys = [];
  46478. };
  46479. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46480. return "keyboard";
  46481. };
  46482. __decorate([
  46483. BABYLON.serialize()
  46484. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46485. __decorate([
  46486. BABYLON.serialize()
  46487. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46488. __decorate([
  46489. BABYLON.serialize()
  46490. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46491. __decorate([
  46492. BABYLON.serialize()
  46493. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46494. return FreeCameraKeyboardMoveInput;
  46495. }());
  46496. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46497. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46498. })(BABYLON || (BABYLON = {}));
  46499. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46500. var BABYLON;
  46501. (function (BABYLON) {
  46502. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46503. __extends(FreeCameraInputsManager, _super);
  46504. function FreeCameraInputsManager(camera) {
  46505. return _super.call(this, camera) || this;
  46506. }
  46507. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46508. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46509. return this;
  46510. };
  46511. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46512. if (touchEnabled === void 0) { touchEnabled = true; }
  46513. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46514. return this;
  46515. };
  46516. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46517. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46518. return this;
  46519. };
  46520. FreeCameraInputsManager.prototype.addTouch = function () {
  46521. this.add(new BABYLON.FreeCameraTouchInput());
  46522. return this;
  46523. };
  46524. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46525. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46526. return this;
  46527. };
  46528. return FreeCameraInputsManager;
  46529. }(BABYLON.CameraInputsManager));
  46530. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46531. })(BABYLON || (BABYLON = {}));
  46532. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46533. var BABYLON;
  46534. (function (BABYLON) {
  46535. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46536. // Forcing to use the Universal camera
  46537. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46538. });
  46539. var FreeCamera = /** @class */ (function (_super) {
  46540. __extends(FreeCamera, _super);
  46541. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46542. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46543. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46544. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46545. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46546. _this.checkCollisions = false;
  46547. _this.applyGravity = false;
  46548. _this._needMoveForGravity = false;
  46549. _this._oldPosition = BABYLON.Vector3.Zero();
  46550. _this._diffPosition = BABYLON.Vector3.Zero();
  46551. _this._newPosition = BABYLON.Vector3.Zero();
  46552. // Collisions
  46553. _this._collisionMask = -1;
  46554. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46555. if (collidedMesh === void 0) { collidedMesh = null; }
  46556. //TODO move this to the collision coordinator!
  46557. if (_this.getScene().workerCollisions)
  46558. newPosition.multiplyInPlace(_this._collider._radius);
  46559. var updatePosition = function (newPos) {
  46560. _this._newPosition.copyFrom(newPos);
  46561. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46562. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46563. _this.position.addInPlace(_this._diffPosition);
  46564. if (_this.onCollide && collidedMesh) {
  46565. _this.onCollide(collidedMesh);
  46566. }
  46567. }
  46568. };
  46569. updatePosition(newPosition);
  46570. };
  46571. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46572. _this.inputs.addKeyboard().addMouse();
  46573. return _this;
  46574. }
  46575. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46576. //-- begin properties for backward compatibility for inputs
  46577. /**
  46578. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46579. * Higher values reduce sensitivity.
  46580. */
  46581. get: function () {
  46582. var mouse = this.inputs.attached["mouse"];
  46583. if (mouse)
  46584. return mouse.angularSensibility;
  46585. return 0;
  46586. },
  46587. /**
  46588. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46589. * Higher values reduce sensitivity.
  46590. */
  46591. set: function (value) {
  46592. var mouse = this.inputs.attached["mouse"];
  46593. if (mouse)
  46594. mouse.angularSensibility = value;
  46595. },
  46596. enumerable: true,
  46597. configurable: true
  46598. });
  46599. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46600. get: function () {
  46601. var keyboard = this.inputs.attached["keyboard"];
  46602. if (keyboard)
  46603. return keyboard.keysUp;
  46604. return [];
  46605. },
  46606. set: function (value) {
  46607. var keyboard = this.inputs.attached["keyboard"];
  46608. if (keyboard)
  46609. keyboard.keysUp = value;
  46610. },
  46611. enumerable: true,
  46612. configurable: true
  46613. });
  46614. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46615. get: function () {
  46616. var keyboard = this.inputs.attached["keyboard"];
  46617. if (keyboard)
  46618. return keyboard.keysDown;
  46619. return [];
  46620. },
  46621. set: function (value) {
  46622. var keyboard = this.inputs.attached["keyboard"];
  46623. if (keyboard)
  46624. keyboard.keysDown = value;
  46625. },
  46626. enumerable: true,
  46627. configurable: true
  46628. });
  46629. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46630. get: function () {
  46631. var keyboard = this.inputs.attached["keyboard"];
  46632. if (keyboard)
  46633. return keyboard.keysLeft;
  46634. return [];
  46635. },
  46636. set: function (value) {
  46637. var keyboard = this.inputs.attached["keyboard"];
  46638. if (keyboard)
  46639. keyboard.keysLeft = value;
  46640. },
  46641. enumerable: true,
  46642. configurable: true
  46643. });
  46644. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46645. get: function () {
  46646. var keyboard = this.inputs.attached["keyboard"];
  46647. if (keyboard)
  46648. return keyboard.keysRight;
  46649. return [];
  46650. },
  46651. set: function (value) {
  46652. var keyboard = this.inputs.attached["keyboard"];
  46653. if (keyboard)
  46654. keyboard.keysRight = value;
  46655. },
  46656. enumerable: true,
  46657. configurable: true
  46658. });
  46659. // Controls
  46660. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46661. this.inputs.attachElement(element, noPreventDefault);
  46662. };
  46663. FreeCamera.prototype.detachControl = function (element) {
  46664. this.inputs.detachElement(element);
  46665. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46666. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46667. };
  46668. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46669. get: function () {
  46670. return this._collisionMask;
  46671. },
  46672. set: function (mask) {
  46673. this._collisionMask = !isNaN(mask) ? mask : -1;
  46674. },
  46675. enumerable: true,
  46676. configurable: true
  46677. });
  46678. /** @hidden */
  46679. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46680. var globalPosition;
  46681. if (this.parent) {
  46682. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46683. }
  46684. else {
  46685. globalPosition = this.position;
  46686. }
  46687. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46688. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46689. if (!this._collider) {
  46690. this._collider = new BABYLON.Collider();
  46691. }
  46692. this._collider._radius = this.ellipsoid;
  46693. this._collider.collisionMask = this._collisionMask;
  46694. //no need for clone, as long as gravity is not on.
  46695. var actualDisplacement = displacement;
  46696. //add gravity to the direction to prevent the dual-collision checking
  46697. if (this.applyGravity) {
  46698. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46699. actualDisplacement = displacement.add(this.getScene().gravity);
  46700. }
  46701. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46702. };
  46703. /** @hidden */
  46704. FreeCamera.prototype._checkInputs = function () {
  46705. if (!this._localDirection) {
  46706. this._localDirection = BABYLON.Vector3.Zero();
  46707. this._transformedDirection = BABYLON.Vector3.Zero();
  46708. }
  46709. this.inputs.checkInputs();
  46710. _super.prototype._checkInputs.call(this);
  46711. };
  46712. /** @hidden */
  46713. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46714. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46715. };
  46716. /** @hidden */
  46717. FreeCamera.prototype._updatePosition = function () {
  46718. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46719. this._collideWithWorld(this.cameraDirection);
  46720. }
  46721. else {
  46722. _super.prototype._updatePosition.call(this);
  46723. }
  46724. };
  46725. FreeCamera.prototype.dispose = function () {
  46726. this.inputs.clear();
  46727. _super.prototype.dispose.call(this);
  46728. };
  46729. FreeCamera.prototype.getClassName = function () {
  46730. return "FreeCamera";
  46731. };
  46732. __decorate([
  46733. BABYLON.serializeAsVector3()
  46734. ], FreeCamera.prototype, "ellipsoid", void 0);
  46735. __decorate([
  46736. BABYLON.serializeAsVector3()
  46737. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46738. __decorate([
  46739. BABYLON.serialize()
  46740. ], FreeCamera.prototype, "checkCollisions", void 0);
  46741. __decorate([
  46742. BABYLON.serialize()
  46743. ], FreeCamera.prototype, "applyGravity", void 0);
  46744. return FreeCamera;
  46745. }(BABYLON.TargetCamera));
  46746. BABYLON.FreeCamera = FreeCamera;
  46747. })(BABYLON || (BABYLON = {}));
  46748. //# sourceMappingURL=babylon.freeCamera.js.map
  46749. var BABYLON;
  46750. (function (BABYLON) {
  46751. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46752. function ArcRotateCameraKeyboardMoveInput() {
  46753. this._keys = new Array();
  46754. this.keysUp = [38];
  46755. this.keysDown = [40];
  46756. this.keysLeft = [37];
  46757. this.keysRight = [39];
  46758. this.keysReset = [220];
  46759. this.panningSensibility = 50.0;
  46760. this.zoomingSensibility = 25.0;
  46761. this.useAltToZoom = true;
  46762. }
  46763. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46764. var _this = this;
  46765. if (this._onCanvasBlurObserver) {
  46766. return;
  46767. }
  46768. this._scene = this.camera.getScene();
  46769. this._engine = this._scene.getEngine();
  46770. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46771. _this._keys = [];
  46772. });
  46773. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46774. var evt = info.event;
  46775. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46776. _this._ctrlPressed = evt.ctrlKey;
  46777. _this._altPressed = evt.altKey;
  46778. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46779. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46780. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46781. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46782. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46783. var index = _this._keys.indexOf(evt.keyCode);
  46784. if (index === -1) {
  46785. _this._keys.push(evt.keyCode);
  46786. }
  46787. if (evt.preventDefault) {
  46788. if (!noPreventDefault) {
  46789. evt.preventDefault();
  46790. }
  46791. }
  46792. }
  46793. }
  46794. else {
  46795. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46796. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46797. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46798. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46799. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46800. var index = _this._keys.indexOf(evt.keyCode);
  46801. if (index >= 0) {
  46802. _this._keys.splice(index, 1);
  46803. }
  46804. if (evt.preventDefault) {
  46805. if (!noPreventDefault) {
  46806. evt.preventDefault();
  46807. }
  46808. }
  46809. }
  46810. }
  46811. });
  46812. };
  46813. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46814. if (this._scene) {
  46815. if (this._onKeyboardObserver) {
  46816. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46817. }
  46818. if (this._onCanvasBlurObserver) {
  46819. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46820. }
  46821. this._onKeyboardObserver = null;
  46822. this._onCanvasBlurObserver = null;
  46823. }
  46824. this._keys = [];
  46825. };
  46826. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46827. if (this._onKeyboardObserver) {
  46828. var camera = this.camera;
  46829. for (var index = 0; index < this._keys.length; index++) {
  46830. var keyCode = this._keys[index];
  46831. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46832. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46833. camera.inertialPanningX -= 1 / this.panningSensibility;
  46834. }
  46835. else {
  46836. camera.inertialAlphaOffset -= 0.01;
  46837. }
  46838. }
  46839. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46840. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46841. camera.inertialPanningY += 1 / this.panningSensibility;
  46842. }
  46843. else if (this._altPressed && this.useAltToZoom) {
  46844. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46845. }
  46846. else {
  46847. camera.inertialBetaOffset -= 0.01;
  46848. }
  46849. }
  46850. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46851. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46852. camera.inertialPanningX += 1 / this.panningSensibility;
  46853. }
  46854. else {
  46855. camera.inertialAlphaOffset += 0.01;
  46856. }
  46857. }
  46858. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46859. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46860. camera.inertialPanningY -= 1 / this.panningSensibility;
  46861. }
  46862. else if (this._altPressed && this.useAltToZoom) {
  46863. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46864. }
  46865. else {
  46866. camera.inertialBetaOffset += 0.01;
  46867. }
  46868. }
  46869. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46870. camera.restoreState();
  46871. }
  46872. }
  46873. }
  46874. };
  46875. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46876. return "ArcRotateCameraKeyboardMoveInput";
  46877. };
  46878. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46879. return "keyboard";
  46880. };
  46881. __decorate([
  46882. BABYLON.serialize()
  46883. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46884. __decorate([
  46885. BABYLON.serialize()
  46886. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46887. __decorate([
  46888. BABYLON.serialize()
  46889. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46890. __decorate([
  46891. BABYLON.serialize()
  46892. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46893. __decorate([
  46894. BABYLON.serialize()
  46895. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46896. __decorate([
  46897. BABYLON.serialize()
  46898. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46899. __decorate([
  46900. BABYLON.serialize()
  46901. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46902. __decorate([
  46903. BABYLON.serialize()
  46904. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46905. return ArcRotateCameraKeyboardMoveInput;
  46906. }());
  46907. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46908. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46909. })(BABYLON || (BABYLON = {}));
  46910. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46911. var BABYLON;
  46912. (function (BABYLON) {
  46913. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46914. function ArcRotateCameraMouseWheelInput() {
  46915. this.wheelPrecision = 3.0;
  46916. /**
  46917. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46918. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46919. */
  46920. this.wheelDeltaPercentage = 0;
  46921. }
  46922. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46923. var _this = this;
  46924. this._wheel = function (p, s) {
  46925. //sanity check - this should be a PointerWheel event.
  46926. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46927. return;
  46928. var event = p.event;
  46929. var delta = 0;
  46930. if (event.wheelDelta) {
  46931. if (_this.wheelDeltaPercentage) {
  46932. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46933. if (event.wheelDelta > 0) {
  46934. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46935. }
  46936. else {
  46937. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46938. }
  46939. }
  46940. else {
  46941. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46942. }
  46943. }
  46944. else if (event.detail) {
  46945. delta = -event.detail / _this.wheelPrecision;
  46946. }
  46947. if (delta)
  46948. _this.camera.inertialRadiusOffset += delta;
  46949. if (event.preventDefault) {
  46950. if (!noPreventDefault) {
  46951. event.preventDefault();
  46952. }
  46953. }
  46954. };
  46955. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46956. };
  46957. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46958. if (this._observer && element) {
  46959. this.camera.getScene().onPointerObservable.remove(this._observer);
  46960. this._observer = null;
  46961. this._wheel = null;
  46962. }
  46963. };
  46964. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46965. return "ArcRotateCameraMouseWheelInput";
  46966. };
  46967. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46968. return "mousewheel";
  46969. };
  46970. __decorate([
  46971. BABYLON.serialize()
  46972. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46973. __decorate([
  46974. BABYLON.serialize()
  46975. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46976. return ArcRotateCameraMouseWheelInput;
  46977. }());
  46978. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46979. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46980. })(BABYLON || (BABYLON = {}));
  46981. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46982. var BABYLON;
  46983. (function (BABYLON) {
  46984. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46985. function ArcRotateCameraPointersInput() {
  46986. this.buttons = [0, 1, 2];
  46987. this.angularSensibilityX = 1000.0;
  46988. this.angularSensibilityY = 1000.0;
  46989. this.pinchPrecision = 12.0;
  46990. /**
  46991. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46992. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46993. */
  46994. this.pinchDeltaPercentage = 0;
  46995. this.panningSensibility = 1000.0;
  46996. this.multiTouchPanning = true;
  46997. this.multiTouchPanAndZoom = true;
  46998. this._isPanClick = false;
  46999. this.pinchInwards = true;
  47000. }
  47001. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47002. var _this = this;
  47003. var engine = this.camera.getEngine();
  47004. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47005. var pointA = null;
  47006. var pointB = null;
  47007. var previousPinchSquaredDistance = 0;
  47008. var initialDistance = 0;
  47009. var twoFingerActivityCount = 0;
  47010. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47011. this._pointerInput = function (p, s) {
  47012. var evt = p.event;
  47013. var isTouch = p.event.pointerType === "touch";
  47014. if (engine.isInVRExclusivePointerMode) {
  47015. return;
  47016. }
  47017. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47018. return;
  47019. }
  47020. var srcElement = (evt.srcElement || evt.target);
  47021. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47022. try {
  47023. srcElement.setPointerCapture(evt.pointerId);
  47024. }
  47025. catch (e) {
  47026. //Nothing to do with the error. Execution will continue.
  47027. }
  47028. // Manage panning with pan button click
  47029. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47030. // manage pointers
  47031. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47032. if (pointA === null) {
  47033. pointA = cacheSoloPointer;
  47034. }
  47035. else if (pointB === null) {
  47036. pointB = cacheSoloPointer;
  47037. }
  47038. if (!noPreventDefault) {
  47039. evt.preventDefault();
  47040. element.focus();
  47041. }
  47042. }
  47043. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47044. _this.camera.restoreState();
  47045. }
  47046. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47047. try {
  47048. srcElement.releasePointerCapture(evt.pointerId);
  47049. }
  47050. catch (e) {
  47051. //Nothing to do with the error.
  47052. }
  47053. cacheSoloPointer = null;
  47054. previousPinchSquaredDistance = 0;
  47055. previousMultiTouchPanPosition.isPaning = false;
  47056. previousMultiTouchPanPosition.isPinching = false;
  47057. twoFingerActivityCount = 0;
  47058. initialDistance = 0;
  47059. if (!isTouch) {
  47060. pointB = null; // Mouse and pen are mono pointer
  47061. }
  47062. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47063. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47064. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47065. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47066. if (engine._badOS) {
  47067. pointA = pointB = null;
  47068. }
  47069. else {
  47070. //only remove the impacted pointer in case of multitouch allowing on most
  47071. //platforms switching from rotate to zoom and pan seamlessly.
  47072. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47073. pointA = pointB;
  47074. pointB = null;
  47075. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47076. }
  47077. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47078. pointB = null;
  47079. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47080. }
  47081. else {
  47082. pointA = pointB = null;
  47083. }
  47084. }
  47085. if (!noPreventDefault) {
  47086. evt.preventDefault();
  47087. }
  47088. }
  47089. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47090. if (!noPreventDefault) {
  47091. evt.preventDefault();
  47092. }
  47093. // One button down
  47094. if (pointA && pointB === null && cacheSoloPointer) {
  47095. if (_this.panningSensibility !== 0 &&
  47096. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47097. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47098. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47099. }
  47100. else {
  47101. var offsetX = evt.clientX - cacheSoloPointer.x;
  47102. var offsetY = evt.clientY - cacheSoloPointer.y;
  47103. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47104. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47105. }
  47106. cacheSoloPointer.x = evt.clientX;
  47107. cacheSoloPointer.y = evt.clientY;
  47108. }
  47109. // Two buttons down: pinch/pan
  47110. else if (pointA && pointB) {
  47111. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47112. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47113. ed.x = evt.clientX;
  47114. ed.y = evt.clientY;
  47115. var direction = _this.pinchInwards ? 1 : -1;
  47116. var distX = pointA.x - pointB.x;
  47117. var distY = pointA.y - pointB.y;
  47118. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47119. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47120. if (previousPinchSquaredDistance === 0) {
  47121. initialDistance = pinchDistance;
  47122. previousPinchSquaredDistance = pinchSquaredDistance;
  47123. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47124. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47125. return;
  47126. }
  47127. if (_this.multiTouchPanAndZoom) {
  47128. if (_this.pinchDeltaPercentage) {
  47129. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47130. }
  47131. else {
  47132. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47133. (_this.pinchPrecision *
  47134. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47135. direction);
  47136. }
  47137. if (_this.panningSensibility !== 0) {
  47138. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47139. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47140. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47141. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47142. previousMultiTouchPanPosition.x = pointersCenterX;
  47143. previousMultiTouchPanPosition.y = pointersCenterY;
  47144. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47145. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47146. }
  47147. }
  47148. else {
  47149. twoFingerActivityCount++;
  47150. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47151. if (_this.pinchDeltaPercentage) {
  47152. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47153. }
  47154. else {
  47155. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47156. (_this.pinchPrecision *
  47157. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47158. direction);
  47159. }
  47160. previousMultiTouchPanPosition.isPaning = false;
  47161. previousMultiTouchPanPosition.isPinching = true;
  47162. }
  47163. else {
  47164. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47165. if (!previousMultiTouchPanPosition.isPaning) {
  47166. previousMultiTouchPanPosition.isPaning = true;
  47167. previousMultiTouchPanPosition.isPinching = false;
  47168. previousMultiTouchPanPosition.x = ed.x;
  47169. previousMultiTouchPanPosition.y = ed.y;
  47170. return;
  47171. }
  47172. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47173. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47174. }
  47175. }
  47176. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47177. previousMultiTouchPanPosition.x = ed.x;
  47178. previousMultiTouchPanPosition.y = ed.y;
  47179. }
  47180. }
  47181. previousPinchSquaredDistance = pinchSquaredDistance;
  47182. }
  47183. }
  47184. };
  47185. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47186. this._onContextMenu = function (evt) {
  47187. evt.preventDefault();
  47188. };
  47189. if (!this.camera._useCtrlForPanning) {
  47190. element.addEventListener("contextmenu", this._onContextMenu, false);
  47191. }
  47192. this._onLostFocus = function () {
  47193. //this._keys = [];
  47194. pointA = pointB = null;
  47195. previousPinchSquaredDistance = 0;
  47196. previousMultiTouchPanPosition.isPaning = false;
  47197. previousMultiTouchPanPosition.isPinching = false;
  47198. twoFingerActivityCount = 0;
  47199. cacheSoloPointer = null;
  47200. initialDistance = 0;
  47201. };
  47202. this._onMouseMove = function (evt) {
  47203. if (!engine.isPointerLock) {
  47204. return;
  47205. }
  47206. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47207. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47208. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47209. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47210. if (!noPreventDefault) {
  47211. evt.preventDefault();
  47212. }
  47213. };
  47214. this._onGestureStart = function (e) {
  47215. if (window.MSGesture === undefined) {
  47216. return;
  47217. }
  47218. if (!_this._MSGestureHandler) {
  47219. _this._MSGestureHandler = new MSGesture();
  47220. _this._MSGestureHandler.target = element;
  47221. }
  47222. _this._MSGestureHandler.addPointer(e.pointerId);
  47223. };
  47224. this._onGesture = function (e) {
  47225. _this.camera.radius *= e.scale;
  47226. if (e.preventDefault) {
  47227. if (!noPreventDefault) {
  47228. e.stopPropagation();
  47229. e.preventDefault();
  47230. }
  47231. }
  47232. };
  47233. element.addEventListener("mousemove", this._onMouseMove, false);
  47234. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47235. element.addEventListener("MSGestureChange", this._onGesture, false);
  47236. BABYLON.Tools.RegisterTopRootEvents([
  47237. { name: "blur", handler: this._onLostFocus }
  47238. ]);
  47239. };
  47240. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47241. if (this._onLostFocus) {
  47242. BABYLON.Tools.UnregisterTopRootEvents([
  47243. { name: "blur", handler: this._onLostFocus }
  47244. ]);
  47245. }
  47246. if (element && this._observer) {
  47247. this.camera.getScene().onPointerObservable.remove(this._observer);
  47248. this._observer = null;
  47249. if (this._onContextMenu) {
  47250. element.removeEventListener("contextmenu", this._onContextMenu);
  47251. }
  47252. if (this._onMouseMove) {
  47253. element.removeEventListener("mousemove", this._onMouseMove);
  47254. }
  47255. if (this._onGestureStart) {
  47256. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47257. }
  47258. if (this._onGesture) {
  47259. element.removeEventListener("MSGestureChange", this._onGesture);
  47260. }
  47261. this._isPanClick = false;
  47262. this.pinchInwards = true;
  47263. this._onMouseMove = null;
  47264. this._onGestureStart = null;
  47265. this._onGesture = null;
  47266. this._MSGestureHandler = null;
  47267. this._onLostFocus = null;
  47268. this._onContextMenu = null;
  47269. }
  47270. };
  47271. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47272. return "ArcRotateCameraPointersInput";
  47273. };
  47274. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47275. return "pointers";
  47276. };
  47277. __decorate([
  47278. BABYLON.serialize()
  47279. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47280. __decorate([
  47281. BABYLON.serialize()
  47282. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47283. __decorate([
  47284. BABYLON.serialize()
  47285. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47286. __decorate([
  47287. BABYLON.serialize()
  47288. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47289. __decorate([
  47290. BABYLON.serialize()
  47291. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47292. __decorate([
  47293. BABYLON.serialize()
  47294. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47295. __decorate([
  47296. BABYLON.serialize()
  47297. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47298. __decorate([
  47299. BABYLON.serialize()
  47300. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47301. return ArcRotateCameraPointersInput;
  47302. }());
  47303. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47304. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47305. })(BABYLON || (BABYLON = {}));
  47306. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47307. var BABYLON;
  47308. (function (BABYLON) {
  47309. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47310. __extends(ArcRotateCameraInputsManager, _super);
  47311. function ArcRotateCameraInputsManager(camera) {
  47312. return _super.call(this, camera) || this;
  47313. }
  47314. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47315. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47316. return this;
  47317. };
  47318. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47319. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47320. return this;
  47321. };
  47322. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47323. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47324. return this;
  47325. };
  47326. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47327. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47328. return this;
  47329. };
  47330. return ArcRotateCameraInputsManager;
  47331. }(BABYLON.CameraInputsManager));
  47332. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47333. })(BABYLON || (BABYLON = {}));
  47334. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47335. var BABYLON;
  47336. (function (BABYLON) {
  47337. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47338. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47339. });
  47340. var ArcRotateCamera = /** @class */ (function (_super) {
  47341. __extends(ArcRotateCamera, _super);
  47342. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47343. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47344. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47345. _this.inertialAlphaOffset = 0;
  47346. _this.inertialBetaOffset = 0;
  47347. _this.inertialRadiusOffset = 0;
  47348. _this.lowerAlphaLimit = null;
  47349. _this.upperAlphaLimit = null;
  47350. _this.lowerBetaLimit = 0.01;
  47351. _this.upperBetaLimit = Math.PI;
  47352. _this.lowerRadiusLimit = null;
  47353. _this.upperRadiusLimit = null;
  47354. _this.inertialPanningX = 0;
  47355. _this.inertialPanningY = 0;
  47356. _this.pinchToPanMaxDistance = 20;
  47357. _this.panningDistanceLimit = null;
  47358. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47359. _this.panningInertia = 0.9;
  47360. //-- end properties for backward compatibility for inputs
  47361. _this.zoomOnFactor = 1;
  47362. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47363. _this.allowUpsideDown = true;
  47364. /** @hidden */
  47365. _this._viewMatrix = new BABYLON.Matrix();
  47366. // Panning
  47367. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47368. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47369. _this.checkCollisions = false;
  47370. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47371. _this._previousPosition = BABYLON.Vector3.Zero();
  47372. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47373. _this._newPosition = BABYLON.Vector3.Zero();
  47374. _this._computationVector = BABYLON.Vector3.Zero();
  47375. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47376. if (collidedMesh === void 0) { collidedMesh = null; }
  47377. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47378. newPosition.multiplyInPlace(_this._collider._radius);
  47379. }
  47380. if (!collidedMesh) {
  47381. _this._previousPosition.copyFrom(_this.position);
  47382. }
  47383. else {
  47384. _this.setPosition(newPosition);
  47385. if (_this.onCollide) {
  47386. _this.onCollide(collidedMesh);
  47387. }
  47388. }
  47389. // Recompute because of constraints
  47390. var cosa = Math.cos(_this.alpha);
  47391. var sina = Math.sin(_this.alpha);
  47392. var cosb = Math.cos(_this.beta);
  47393. var sinb = Math.sin(_this.beta);
  47394. if (sinb === 0) {
  47395. sinb = 0.0001;
  47396. }
  47397. var target = _this._getTargetPosition();
  47398. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47399. target.addToRef(_this._computationVector, _this._newPosition);
  47400. _this.position.copyFrom(_this._newPosition);
  47401. var up = _this.upVector;
  47402. if (_this.allowUpsideDown && _this.beta < 0) {
  47403. up = up.clone();
  47404. up = up.negate();
  47405. }
  47406. _this._computeViewMatrix(_this.position, target, up);
  47407. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47408. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47409. _this._collisionTriggered = false;
  47410. };
  47411. _this._target = BABYLON.Vector3.Zero();
  47412. if (target) {
  47413. _this.setTarget(target);
  47414. }
  47415. _this.alpha = alpha;
  47416. _this.beta = beta;
  47417. _this.radius = radius;
  47418. _this.getViewMatrix();
  47419. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47420. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47421. return _this;
  47422. }
  47423. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47424. get: function () {
  47425. return this._target;
  47426. },
  47427. set: function (value) {
  47428. this.setTarget(value);
  47429. },
  47430. enumerable: true,
  47431. configurable: true
  47432. });
  47433. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47434. //-- begin properties for backward compatibility for inputs
  47435. get: function () {
  47436. var pointers = this.inputs.attached["pointers"];
  47437. if (pointers)
  47438. return pointers.angularSensibilityX;
  47439. return 0;
  47440. },
  47441. set: function (value) {
  47442. var pointers = this.inputs.attached["pointers"];
  47443. if (pointers) {
  47444. pointers.angularSensibilityX = value;
  47445. }
  47446. },
  47447. enumerable: true,
  47448. configurable: true
  47449. });
  47450. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47451. get: function () {
  47452. var pointers = this.inputs.attached["pointers"];
  47453. if (pointers)
  47454. return pointers.angularSensibilityY;
  47455. return 0;
  47456. },
  47457. set: function (value) {
  47458. var pointers = this.inputs.attached["pointers"];
  47459. if (pointers) {
  47460. pointers.angularSensibilityY = value;
  47461. }
  47462. },
  47463. enumerable: true,
  47464. configurable: true
  47465. });
  47466. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47467. get: function () {
  47468. var pointers = this.inputs.attached["pointers"];
  47469. if (pointers)
  47470. return pointers.pinchPrecision;
  47471. return 0;
  47472. },
  47473. set: function (value) {
  47474. var pointers = this.inputs.attached["pointers"];
  47475. if (pointers) {
  47476. pointers.pinchPrecision = value;
  47477. }
  47478. },
  47479. enumerable: true,
  47480. configurable: true
  47481. });
  47482. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47483. get: function () {
  47484. var pointers = this.inputs.attached["pointers"];
  47485. if (pointers)
  47486. return pointers.pinchDeltaPercentage;
  47487. return 0;
  47488. },
  47489. set: function (value) {
  47490. var pointers = this.inputs.attached["pointers"];
  47491. if (pointers) {
  47492. pointers.pinchDeltaPercentage = value;
  47493. }
  47494. },
  47495. enumerable: true,
  47496. configurable: true
  47497. });
  47498. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47499. get: function () {
  47500. var pointers = this.inputs.attached["pointers"];
  47501. if (pointers)
  47502. return pointers.panningSensibility;
  47503. return 0;
  47504. },
  47505. set: function (value) {
  47506. var pointers = this.inputs.attached["pointers"];
  47507. if (pointers) {
  47508. pointers.panningSensibility = value;
  47509. }
  47510. },
  47511. enumerable: true,
  47512. configurable: true
  47513. });
  47514. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47515. get: function () {
  47516. var keyboard = this.inputs.attached["keyboard"];
  47517. if (keyboard)
  47518. return keyboard.keysUp;
  47519. return [];
  47520. },
  47521. set: function (value) {
  47522. var keyboard = this.inputs.attached["keyboard"];
  47523. if (keyboard)
  47524. keyboard.keysUp = value;
  47525. },
  47526. enumerable: true,
  47527. configurable: true
  47528. });
  47529. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47530. get: function () {
  47531. var keyboard = this.inputs.attached["keyboard"];
  47532. if (keyboard)
  47533. return keyboard.keysDown;
  47534. return [];
  47535. },
  47536. set: function (value) {
  47537. var keyboard = this.inputs.attached["keyboard"];
  47538. if (keyboard)
  47539. keyboard.keysDown = value;
  47540. },
  47541. enumerable: true,
  47542. configurable: true
  47543. });
  47544. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47545. get: function () {
  47546. var keyboard = this.inputs.attached["keyboard"];
  47547. if (keyboard)
  47548. return keyboard.keysLeft;
  47549. return [];
  47550. },
  47551. set: function (value) {
  47552. var keyboard = this.inputs.attached["keyboard"];
  47553. if (keyboard)
  47554. keyboard.keysLeft = value;
  47555. },
  47556. enumerable: true,
  47557. configurable: true
  47558. });
  47559. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47560. get: function () {
  47561. var keyboard = this.inputs.attached["keyboard"];
  47562. if (keyboard)
  47563. return keyboard.keysRight;
  47564. return [];
  47565. },
  47566. set: function (value) {
  47567. var keyboard = this.inputs.attached["keyboard"];
  47568. if (keyboard)
  47569. keyboard.keysRight = value;
  47570. },
  47571. enumerable: true,
  47572. configurable: true
  47573. });
  47574. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47575. get: function () {
  47576. var mousewheel = this.inputs.attached["mousewheel"];
  47577. if (mousewheel)
  47578. return mousewheel.wheelPrecision;
  47579. return 0;
  47580. },
  47581. set: function (value) {
  47582. var mousewheel = this.inputs.attached["mousewheel"];
  47583. if (mousewheel)
  47584. mousewheel.wheelPrecision = value;
  47585. },
  47586. enumerable: true,
  47587. configurable: true
  47588. });
  47589. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47590. get: function () {
  47591. var mousewheel = this.inputs.attached["mousewheel"];
  47592. if (mousewheel)
  47593. return mousewheel.wheelDeltaPercentage;
  47594. return 0;
  47595. },
  47596. set: function (value) {
  47597. var mousewheel = this.inputs.attached["mousewheel"];
  47598. if (mousewheel)
  47599. mousewheel.wheelDeltaPercentage = value;
  47600. },
  47601. enumerable: true,
  47602. configurable: true
  47603. });
  47604. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47605. get: function () {
  47606. return this._bouncingBehavior;
  47607. },
  47608. enumerable: true,
  47609. configurable: true
  47610. });
  47611. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47612. get: function () {
  47613. return this._bouncingBehavior != null;
  47614. },
  47615. set: function (value) {
  47616. if (value === this.useBouncingBehavior) {
  47617. return;
  47618. }
  47619. if (value) {
  47620. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47621. this.addBehavior(this._bouncingBehavior);
  47622. }
  47623. else if (this._bouncingBehavior) {
  47624. this.removeBehavior(this._bouncingBehavior);
  47625. this._bouncingBehavior = null;
  47626. }
  47627. },
  47628. enumerable: true,
  47629. configurable: true
  47630. });
  47631. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47632. get: function () {
  47633. return this._framingBehavior;
  47634. },
  47635. enumerable: true,
  47636. configurable: true
  47637. });
  47638. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47639. get: function () {
  47640. return this._framingBehavior != null;
  47641. },
  47642. set: function (value) {
  47643. if (value === this.useFramingBehavior) {
  47644. return;
  47645. }
  47646. if (value) {
  47647. this._framingBehavior = new BABYLON.FramingBehavior();
  47648. this.addBehavior(this._framingBehavior);
  47649. }
  47650. else if (this._framingBehavior) {
  47651. this.removeBehavior(this._framingBehavior);
  47652. this._framingBehavior = null;
  47653. }
  47654. },
  47655. enumerable: true,
  47656. configurable: true
  47657. });
  47658. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47659. get: function () {
  47660. return this._autoRotationBehavior;
  47661. },
  47662. enumerable: true,
  47663. configurable: true
  47664. });
  47665. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47666. get: function () {
  47667. return this._autoRotationBehavior != null;
  47668. },
  47669. set: function (value) {
  47670. if (value === this.useAutoRotationBehavior) {
  47671. return;
  47672. }
  47673. if (value) {
  47674. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47675. this.addBehavior(this._autoRotationBehavior);
  47676. }
  47677. else if (this._autoRotationBehavior) {
  47678. this.removeBehavior(this._autoRotationBehavior);
  47679. this._autoRotationBehavior = null;
  47680. }
  47681. },
  47682. enumerable: true,
  47683. configurable: true
  47684. });
  47685. // Cache
  47686. /** @hidden */
  47687. ArcRotateCamera.prototype._initCache = function () {
  47688. _super.prototype._initCache.call(this);
  47689. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47690. this._cache.alpha = undefined;
  47691. this._cache.beta = undefined;
  47692. this._cache.radius = undefined;
  47693. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47694. };
  47695. /** @hidden */
  47696. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47697. if (!ignoreParentClass) {
  47698. _super.prototype._updateCache.call(this);
  47699. }
  47700. this._cache._target.copyFrom(this._getTargetPosition());
  47701. this._cache.alpha = this.alpha;
  47702. this._cache.beta = this.beta;
  47703. this._cache.radius = this.radius;
  47704. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47705. };
  47706. ArcRotateCamera.prototype._getTargetPosition = function () {
  47707. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47708. var pos = this._targetHost.getAbsolutePosition();
  47709. if (this._targetBoundingCenter) {
  47710. pos.addToRef(this._targetBoundingCenter, this._target);
  47711. }
  47712. else {
  47713. this._target.copyFrom(pos);
  47714. }
  47715. }
  47716. var lockedTargetPosition = this._getLockedTargetPosition();
  47717. if (lockedTargetPosition) {
  47718. return lockedTargetPosition;
  47719. }
  47720. return this._target;
  47721. };
  47722. ArcRotateCamera.prototype.storeState = function () {
  47723. this._storedAlpha = this.alpha;
  47724. this._storedBeta = this.beta;
  47725. this._storedRadius = this.radius;
  47726. this._storedTarget = this._getTargetPosition().clone();
  47727. return _super.prototype.storeState.call(this);
  47728. };
  47729. /**
  47730. * @hidden
  47731. * Restored camera state. You must call storeState() first
  47732. */
  47733. ArcRotateCamera.prototype._restoreStateValues = function () {
  47734. if (!_super.prototype._restoreStateValues.call(this)) {
  47735. return false;
  47736. }
  47737. this.alpha = this._storedAlpha;
  47738. this.beta = this._storedBeta;
  47739. this.radius = this._storedRadius;
  47740. this.setTarget(this._storedTarget.clone());
  47741. this.inertialAlphaOffset = 0;
  47742. this.inertialBetaOffset = 0;
  47743. this.inertialRadiusOffset = 0;
  47744. this.inertialPanningX = 0;
  47745. this.inertialPanningY = 0;
  47746. return true;
  47747. };
  47748. // Synchronized
  47749. /** @hidden */
  47750. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47751. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47752. return false;
  47753. return this._cache._target.equals(this._getTargetPosition())
  47754. && this._cache.alpha === this.alpha
  47755. && this._cache.beta === this.beta
  47756. && this._cache.radius === this.radius
  47757. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47758. };
  47759. // Methods
  47760. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47761. var _this = this;
  47762. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47763. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47764. this._useCtrlForPanning = useCtrlForPanning;
  47765. this._panningMouseButton = panningMouseButton;
  47766. this.inputs.attachElement(element, noPreventDefault);
  47767. this._reset = function () {
  47768. _this.inertialAlphaOffset = 0;
  47769. _this.inertialBetaOffset = 0;
  47770. _this.inertialRadiusOffset = 0;
  47771. _this.inertialPanningX = 0;
  47772. _this.inertialPanningY = 0;
  47773. };
  47774. };
  47775. ArcRotateCamera.prototype.detachControl = function (element) {
  47776. this.inputs.detachElement(element);
  47777. if (this._reset) {
  47778. this._reset();
  47779. }
  47780. };
  47781. /** @hidden */
  47782. ArcRotateCamera.prototype._checkInputs = function () {
  47783. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47784. if (this._collisionTriggered) {
  47785. return;
  47786. }
  47787. this.inputs.checkInputs();
  47788. // Inertia
  47789. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47790. var inertialAlphaOffset = this.inertialAlphaOffset;
  47791. if (this.beta <= 0)
  47792. inertialAlphaOffset *= -1;
  47793. if (this.getScene().useRightHandedSystem)
  47794. inertialAlphaOffset *= -1;
  47795. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47796. inertialAlphaOffset *= -1;
  47797. this.alpha += inertialAlphaOffset;
  47798. this.beta += this.inertialBetaOffset;
  47799. this.radius -= this.inertialRadiusOffset;
  47800. this.inertialAlphaOffset *= this.inertia;
  47801. this.inertialBetaOffset *= this.inertia;
  47802. this.inertialRadiusOffset *= this.inertia;
  47803. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47804. this.inertialAlphaOffset = 0;
  47805. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47806. this.inertialBetaOffset = 0;
  47807. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47808. this.inertialRadiusOffset = 0;
  47809. }
  47810. // Panning inertia
  47811. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47812. if (!this._localDirection) {
  47813. this._localDirection = BABYLON.Vector3.Zero();
  47814. this._transformedDirection = BABYLON.Vector3.Zero();
  47815. }
  47816. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47817. this._localDirection.multiplyInPlace(this.panningAxis);
  47818. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47819. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47820. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47821. if (!this.panningAxis.y) {
  47822. this._transformedDirection.y = 0;
  47823. }
  47824. if (!this._targetHost) {
  47825. if (this.panningDistanceLimit) {
  47826. this._transformedDirection.addInPlace(this._target);
  47827. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47828. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47829. this._target.copyFrom(this._transformedDirection);
  47830. }
  47831. }
  47832. else {
  47833. this._target.addInPlace(this._transformedDirection);
  47834. }
  47835. }
  47836. this.inertialPanningX *= this.panningInertia;
  47837. this.inertialPanningY *= this.panningInertia;
  47838. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47839. this.inertialPanningX = 0;
  47840. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47841. this.inertialPanningY = 0;
  47842. }
  47843. // Limits
  47844. this._checkLimits();
  47845. _super.prototype._checkInputs.call(this);
  47846. };
  47847. ArcRotateCamera.prototype._checkLimits = function () {
  47848. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47849. if (this.allowUpsideDown && this.beta > Math.PI) {
  47850. this.beta = this.beta - (2 * Math.PI);
  47851. }
  47852. }
  47853. else {
  47854. if (this.beta < this.lowerBetaLimit) {
  47855. this.beta = this.lowerBetaLimit;
  47856. }
  47857. }
  47858. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47859. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47860. this.beta = this.beta + (2 * Math.PI);
  47861. }
  47862. }
  47863. else {
  47864. if (this.beta > this.upperBetaLimit) {
  47865. this.beta = this.upperBetaLimit;
  47866. }
  47867. }
  47868. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47869. this.alpha = this.lowerAlphaLimit;
  47870. }
  47871. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47872. this.alpha = this.upperAlphaLimit;
  47873. }
  47874. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47875. this.radius = this.lowerRadiusLimit;
  47876. }
  47877. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47878. this.radius = this.upperRadiusLimit;
  47879. }
  47880. };
  47881. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47882. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47883. this.radius = this._computationVector.length();
  47884. if (this.radius === 0) {
  47885. this.radius = 0.0001; // Just to avoid division by zero
  47886. }
  47887. // Alpha
  47888. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47889. if (this._computationVector.z < 0) {
  47890. this.alpha = 2 * Math.PI - this.alpha;
  47891. }
  47892. // Beta
  47893. this.beta = Math.acos(this._computationVector.y / this.radius);
  47894. this._checkLimits();
  47895. };
  47896. ArcRotateCamera.prototype.setPosition = function (position) {
  47897. if (this.position.equals(position)) {
  47898. return;
  47899. }
  47900. this.position.copyFrom(position);
  47901. this.rebuildAnglesAndRadius();
  47902. };
  47903. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47904. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47905. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47906. if (target.getBoundingInfo) {
  47907. if (toBoundingCenter) {
  47908. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47909. }
  47910. else {
  47911. this._targetBoundingCenter = null;
  47912. }
  47913. this._targetHost = target;
  47914. this._target = this._getTargetPosition();
  47915. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47916. }
  47917. else {
  47918. var newTarget = target;
  47919. var currentTarget = this._getTargetPosition();
  47920. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47921. return;
  47922. }
  47923. this._targetHost = null;
  47924. this._target = newTarget;
  47925. this._targetBoundingCenter = null;
  47926. this.onMeshTargetChangedObservable.notifyObservers(null);
  47927. }
  47928. this.rebuildAnglesAndRadius();
  47929. };
  47930. /** @hidden */
  47931. ArcRotateCamera.prototype._getViewMatrix = function () {
  47932. // Compute
  47933. var cosa = Math.cos(this.alpha);
  47934. var sina = Math.sin(this.alpha);
  47935. var cosb = Math.cos(this.beta);
  47936. var sinb = Math.sin(this.beta);
  47937. if (sinb === 0) {
  47938. sinb = 0.0001;
  47939. }
  47940. var target = this._getTargetPosition();
  47941. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47942. target.addToRef(this._computationVector, this._newPosition);
  47943. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47944. if (!this._collider) {
  47945. this._collider = new BABYLON.Collider();
  47946. }
  47947. this._collider._radius = this.collisionRadius;
  47948. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47949. this._collisionTriggered = true;
  47950. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47951. }
  47952. else {
  47953. this.position.copyFrom(this._newPosition);
  47954. var up = this.upVector;
  47955. if (this.allowUpsideDown && sinb < 0) {
  47956. up = up.clone();
  47957. up = up.negate();
  47958. }
  47959. this._computeViewMatrix(this.position, target, up);
  47960. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47961. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47962. }
  47963. this._currentTarget = target;
  47964. return this._viewMatrix;
  47965. };
  47966. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47967. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47968. meshes = meshes || this.getScene().meshes;
  47969. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47970. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47971. this.radius = distance * this.zoomOnFactor;
  47972. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47973. };
  47974. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47975. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47976. var meshesOrMinMaxVector;
  47977. var distance;
  47978. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47979. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47980. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47981. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47982. }
  47983. else { //minMaxVector and distance
  47984. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47985. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47986. distance = minMaxVectorAndDistance.distance;
  47987. }
  47988. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47989. if (!doNotUpdateMaxZ) {
  47990. this.maxZ = distance * 2;
  47991. }
  47992. };
  47993. /**
  47994. * @override
  47995. * Override Camera.createRigCamera
  47996. */
  47997. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47998. var alphaShift = 0;
  47999. switch (this.cameraRigMode) {
  48000. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48001. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48002. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48003. case BABYLON.Camera.RIG_MODE_VR:
  48004. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48005. break;
  48006. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48007. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48008. break;
  48009. }
  48010. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48011. rigCam._cameraRigParams = {};
  48012. return rigCam;
  48013. };
  48014. /**
  48015. * @hidden
  48016. * @override
  48017. * Override Camera._updateRigCameras
  48018. */
  48019. ArcRotateCamera.prototype._updateRigCameras = function () {
  48020. var camLeft = this._rigCameras[0];
  48021. var camRight = this._rigCameras[1];
  48022. camLeft.beta = camRight.beta = this.beta;
  48023. camLeft.radius = camRight.radius = this.radius;
  48024. switch (this.cameraRigMode) {
  48025. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48026. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48027. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48028. case BABYLON.Camera.RIG_MODE_VR:
  48029. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48030. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48031. break;
  48032. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48033. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48034. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48035. break;
  48036. }
  48037. _super.prototype._updateRigCameras.call(this);
  48038. };
  48039. ArcRotateCamera.prototype.dispose = function () {
  48040. this.inputs.clear();
  48041. _super.prototype.dispose.call(this);
  48042. };
  48043. ArcRotateCamera.prototype.getClassName = function () {
  48044. return "ArcRotateCamera";
  48045. };
  48046. __decorate([
  48047. BABYLON.serialize()
  48048. ], ArcRotateCamera.prototype, "alpha", void 0);
  48049. __decorate([
  48050. BABYLON.serialize()
  48051. ], ArcRotateCamera.prototype, "beta", void 0);
  48052. __decorate([
  48053. BABYLON.serialize()
  48054. ], ArcRotateCamera.prototype, "radius", void 0);
  48055. __decorate([
  48056. BABYLON.serializeAsVector3("target")
  48057. ], ArcRotateCamera.prototype, "_target", void 0);
  48058. __decorate([
  48059. BABYLON.serialize()
  48060. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48061. __decorate([
  48062. BABYLON.serialize()
  48063. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48064. __decorate([
  48065. BABYLON.serialize()
  48066. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48067. __decorate([
  48068. BABYLON.serialize()
  48069. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48070. __decorate([
  48071. BABYLON.serialize()
  48072. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48073. __decorate([
  48074. BABYLON.serialize()
  48075. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48076. __decorate([
  48077. BABYLON.serialize()
  48078. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48079. __decorate([
  48080. BABYLON.serialize()
  48081. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48082. __decorate([
  48083. BABYLON.serialize()
  48084. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48085. __decorate([
  48086. BABYLON.serialize()
  48087. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48088. __decorate([
  48089. BABYLON.serialize()
  48090. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48091. __decorate([
  48092. BABYLON.serialize()
  48093. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48094. __decorate([
  48095. BABYLON.serialize()
  48096. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48097. __decorate([
  48098. BABYLON.serializeAsVector3()
  48099. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48100. __decorate([
  48101. BABYLON.serialize()
  48102. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48103. __decorate([
  48104. BABYLON.serialize()
  48105. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48106. __decorate([
  48107. BABYLON.serialize()
  48108. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48109. return ArcRotateCamera;
  48110. }(BABYLON.TargetCamera));
  48111. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48112. })(BABYLON || (BABYLON = {}));
  48113. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48114. var BABYLON;
  48115. (function (BABYLON) {
  48116. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48117. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48118. });
  48119. /**
  48120. * The HemisphericLight simulates the ambient environment light,
  48121. * so the passed direction is the light reflection direction, not the incoming direction.
  48122. */
  48123. var HemisphericLight = /** @class */ (function (_super) {
  48124. __extends(HemisphericLight, _super);
  48125. /**
  48126. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48127. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48128. * The HemisphericLight can't cast shadows.
  48129. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48130. * @param name The friendly name of the light
  48131. * @param direction The direction of the light reflection
  48132. * @param scene The scene the light belongs to
  48133. */
  48134. function HemisphericLight(name, direction, scene) {
  48135. var _this = _super.call(this, name, scene) || this;
  48136. /**
  48137. * The groundColor is the light in the opposite direction to the one specified during creation.
  48138. * 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.
  48139. */
  48140. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48141. _this.direction = direction || BABYLON.Vector3.Up();
  48142. return _this;
  48143. }
  48144. HemisphericLight.prototype._buildUniformLayout = function () {
  48145. this._uniformBuffer.addUniform("vLightData", 4);
  48146. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48147. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48148. this._uniformBuffer.addUniform("vLightGround", 3);
  48149. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48150. this._uniformBuffer.addUniform("depthValues", 2);
  48151. this._uniformBuffer.create();
  48152. };
  48153. /**
  48154. * Returns the string "HemisphericLight".
  48155. * @return The class name
  48156. */
  48157. HemisphericLight.prototype.getClassName = function () {
  48158. return "HemisphericLight";
  48159. };
  48160. /**
  48161. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48162. * Returns the updated direction.
  48163. * @param target The target the direction should point to
  48164. * @return The computed direction
  48165. */
  48166. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48167. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48168. return this.direction;
  48169. };
  48170. /**
  48171. * Returns the shadow generator associated to the light.
  48172. * @returns Always null for hemispheric lights because it does not support shadows.
  48173. */
  48174. HemisphericLight.prototype.getShadowGenerator = function () {
  48175. return null;
  48176. };
  48177. /**
  48178. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48179. * @param effect The effect to update
  48180. * @param lightIndex The index of the light in the effect to update
  48181. * @returns The hemispheric light
  48182. */
  48183. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48184. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48185. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48186. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48187. return this;
  48188. };
  48189. /**
  48190. * Computes the world matrix of the node
  48191. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48192. * @param useWasUpdatedFlag defines a reserved property
  48193. * @returns the world matrix
  48194. */
  48195. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  48196. if (!this._worldMatrix) {
  48197. this._worldMatrix = BABYLON.Matrix.Identity();
  48198. }
  48199. return this._worldMatrix;
  48200. };
  48201. /**
  48202. * Returns the integer 3.
  48203. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48204. */
  48205. HemisphericLight.prototype.getTypeID = function () {
  48206. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48207. };
  48208. /**
  48209. * Prepares the list of defines specific to the light type.
  48210. * @param defines the list of defines
  48211. * @param lightIndex defines the index of the light for the effect
  48212. */
  48213. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48214. defines["HEMILIGHT" + lightIndex] = true;
  48215. };
  48216. __decorate([
  48217. BABYLON.serializeAsColor3()
  48218. ], HemisphericLight.prototype, "groundColor", void 0);
  48219. __decorate([
  48220. BABYLON.serializeAsVector3()
  48221. ], HemisphericLight.prototype, "direction", void 0);
  48222. return HemisphericLight;
  48223. }(BABYLON.Light));
  48224. BABYLON.HemisphericLight = HemisphericLight;
  48225. })(BABYLON || (BABYLON = {}));
  48226. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48227. var BABYLON;
  48228. (function (BABYLON) {
  48229. /**
  48230. * Base implementation IShadowLight
  48231. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48232. */
  48233. var ShadowLight = /** @class */ (function (_super) {
  48234. __extends(ShadowLight, _super);
  48235. function ShadowLight() {
  48236. var _this = _super !== null && _super.apply(this, arguments) || this;
  48237. _this._needProjectionMatrixCompute = true;
  48238. return _this;
  48239. }
  48240. ShadowLight.prototype._setPosition = function (value) {
  48241. this._position = value;
  48242. };
  48243. Object.defineProperty(ShadowLight.prototype, "position", {
  48244. /**
  48245. * Sets the position the shadow will be casted from. Also use as the light position for both
  48246. * point and spot lights.
  48247. */
  48248. get: function () {
  48249. return this._position;
  48250. },
  48251. /**
  48252. * Sets the position the shadow will be casted from. Also use as the light position for both
  48253. * point and spot lights.
  48254. */
  48255. set: function (value) {
  48256. this._setPosition(value);
  48257. },
  48258. enumerable: true,
  48259. configurable: true
  48260. });
  48261. ShadowLight.prototype._setDirection = function (value) {
  48262. this._direction = value;
  48263. };
  48264. Object.defineProperty(ShadowLight.prototype, "direction", {
  48265. /**
  48266. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48267. * Also use as the light direction on spot and directional lights.
  48268. */
  48269. get: function () {
  48270. return this._direction;
  48271. },
  48272. /**
  48273. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48274. * Also use as the light direction on spot and directional lights.
  48275. */
  48276. set: function (value) {
  48277. this._setDirection(value);
  48278. },
  48279. enumerable: true,
  48280. configurable: true
  48281. });
  48282. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48283. /**
  48284. * Gets the shadow projection clipping minimum z value.
  48285. */
  48286. get: function () {
  48287. return this._shadowMinZ;
  48288. },
  48289. /**
  48290. * Sets the shadow projection clipping minimum z value.
  48291. */
  48292. set: function (value) {
  48293. this._shadowMinZ = value;
  48294. this.forceProjectionMatrixCompute();
  48295. },
  48296. enumerable: true,
  48297. configurable: true
  48298. });
  48299. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48300. /**
  48301. * Sets the shadow projection clipping maximum z value.
  48302. */
  48303. get: function () {
  48304. return this._shadowMaxZ;
  48305. },
  48306. /**
  48307. * Gets the shadow projection clipping maximum z value.
  48308. */
  48309. set: function (value) {
  48310. this._shadowMaxZ = value;
  48311. this.forceProjectionMatrixCompute();
  48312. },
  48313. enumerable: true,
  48314. configurable: true
  48315. });
  48316. /**
  48317. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48318. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48319. */
  48320. ShadowLight.prototype.computeTransformedInformation = function () {
  48321. if (this.parent && this.parent.getWorldMatrix) {
  48322. if (!this.transformedPosition) {
  48323. this.transformedPosition = BABYLON.Vector3.Zero();
  48324. }
  48325. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48326. // In case the direction is present.
  48327. if (this.direction) {
  48328. if (!this.transformedDirection) {
  48329. this.transformedDirection = BABYLON.Vector3.Zero();
  48330. }
  48331. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48332. }
  48333. return true;
  48334. }
  48335. return false;
  48336. };
  48337. /**
  48338. * Return the depth scale used for the shadow map.
  48339. * @returns the depth scale.
  48340. */
  48341. ShadowLight.prototype.getDepthScale = function () {
  48342. return 50.0;
  48343. };
  48344. /**
  48345. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48346. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48347. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48348. */
  48349. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48350. return this.transformedDirection ? this.transformedDirection : this.direction;
  48351. };
  48352. /**
  48353. * Returns the ShadowLight absolute position in the World.
  48354. * @returns the position vector in world space
  48355. */
  48356. ShadowLight.prototype.getAbsolutePosition = function () {
  48357. return this.transformedPosition ? this.transformedPosition : this.position;
  48358. };
  48359. /**
  48360. * Sets the ShadowLight direction toward the passed target.
  48361. * @param target The point tot target in local space
  48362. * @returns the updated ShadowLight direction
  48363. */
  48364. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48365. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48366. return this.direction;
  48367. };
  48368. /**
  48369. * Returns the light rotation in euler definition.
  48370. * @returns the x y z rotation in local space.
  48371. */
  48372. ShadowLight.prototype.getRotation = function () {
  48373. this.direction.normalize();
  48374. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48375. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48376. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48377. };
  48378. /**
  48379. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48380. * @returns true if a cube texture needs to be use
  48381. */
  48382. ShadowLight.prototype.needCube = function () {
  48383. return false;
  48384. };
  48385. /**
  48386. * Detects if the projection matrix requires to be recomputed this frame.
  48387. * @returns true if it requires to be recomputed otherwise, false.
  48388. */
  48389. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48390. return this._needProjectionMatrixCompute;
  48391. };
  48392. /**
  48393. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48394. */
  48395. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48396. this._needProjectionMatrixCompute = true;
  48397. };
  48398. /** @hidden */
  48399. ShadowLight.prototype._initCache = function () {
  48400. _super.prototype._initCache.call(this);
  48401. this._cache.position = BABYLON.Vector3.Zero();
  48402. };
  48403. /** @hidden */
  48404. ShadowLight.prototype._isSynchronized = function () {
  48405. if (!this._cache.position.equals(this.position))
  48406. return false;
  48407. return true;
  48408. };
  48409. /**
  48410. * Computes the world matrix of the node
  48411. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48412. * @returns the world matrix
  48413. */
  48414. ShadowLight.prototype.computeWorldMatrix = function (force) {
  48415. if (!force && this.isSynchronized()) {
  48416. this._currentRenderId = this.getScene().getRenderId();
  48417. return this._worldMatrix;
  48418. }
  48419. this._updateCache();
  48420. this._cache.position.copyFrom(this.position);
  48421. if (!this._worldMatrix) {
  48422. this._worldMatrix = BABYLON.Matrix.Identity();
  48423. }
  48424. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48425. if (this.parent && this.parent.getWorldMatrix) {
  48426. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  48427. this._markSyncedWithParent();
  48428. }
  48429. // Cache the determinant
  48430. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  48431. return this._worldMatrix;
  48432. };
  48433. /**
  48434. * Gets the minZ used for shadow according to both the scene and the light.
  48435. * @param activeCamera The camera we are returning the min for
  48436. * @returns the depth min z
  48437. */
  48438. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48439. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48440. };
  48441. /**
  48442. * Gets the maxZ used for shadow according to both the scene and the light.
  48443. * @param activeCamera The camera we are returning the max for
  48444. * @returns the depth max z
  48445. */
  48446. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48447. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48448. };
  48449. /**
  48450. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48451. * @param matrix The materix to updated with the projection information
  48452. * @param viewMatrix The transform matrix of the light
  48453. * @param renderList The list of mesh to render in the map
  48454. * @returns The current light
  48455. */
  48456. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48457. if (this.customProjectionMatrixBuilder) {
  48458. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48459. }
  48460. else {
  48461. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48462. }
  48463. return this;
  48464. };
  48465. __decorate([
  48466. BABYLON.serializeAsVector3()
  48467. ], ShadowLight.prototype, "position", null);
  48468. __decorate([
  48469. BABYLON.serializeAsVector3()
  48470. ], ShadowLight.prototype, "direction", null);
  48471. __decorate([
  48472. BABYLON.serialize()
  48473. ], ShadowLight.prototype, "shadowMinZ", null);
  48474. __decorate([
  48475. BABYLON.serialize()
  48476. ], ShadowLight.prototype, "shadowMaxZ", null);
  48477. return ShadowLight;
  48478. }(BABYLON.Light));
  48479. BABYLON.ShadowLight = ShadowLight;
  48480. })(BABYLON || (BABYLON = {}));
  48481. //# sourceMappingURL=babylon.shadowLight.js.map
  48482. var BABYLON;
  48483. (function (BABYLON) {
  48484. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48485. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48486. });
  48487. /**
  48488. * A point light is a light defined by an unique point in world space.
  48489. * The light is emitted in every direction from this point.
  48490. * A good example of a point light is a standard light bulb.
  48491. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48492. */
  48493. var PointLight = /** @class */ (function (_super) {
  48494. __extends(PointLight, _super);
  48495. /**
  48496. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48497. * A PointLight emits the light in every direction.
  48498. * It can cast shadows.
  48499. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48500. * ```javascript
  48501. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48502. * ```
  48503. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48504. * @param name The light friendly name
  48505. * @param position The position of the point light in the scene
  48506. * @param scene The scene the lights belongs to
  48507. */
  48508. function PointLight(name, position, scene) {
  48509. var _this = _super.call(this, name, scene) || this;
  48510. _this._shadowAngle = Math.PI / 2;
  48511. _this.position = position;
  48512. return _this;
  48513. }
  48514. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48515. /**
  48516. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48517. * This specifies what angle the shadow will use to be created.
  48518. *
  48519. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48520. */
  48521. get: function () {
  48522. return this._shadowAngle;
  48523. },
  48524. /**
  48525. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48526. * This specifies what angle the shadow will use to be created.
  48527. *
  48528. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48529. */
  48530. set: function (value) {
  48531. this._shadowAngle = value;
  48532. this.forceProjectionMatrixCompute();
  48533. },
  48534. enumerable: true,
  48535. configurable: true
  48536. });
  48537. Object.defineProperty(PointLight.prototype, "direction", {
  48538. /**
  48539. * Gets the direction if it has been set.
  48540. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48541. */
  48542. get: function () {
  48543. return this._direction;
  48544. },
  48545. /**
  48546. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48547. */
  48548. set: function (value) {
  48549. var previousNeedCube = this.needCube();
  48550. this._direction = value;
  48551. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48552. this._shadowGenerator.recreateShadowMap();
  48553. }
  48554. },
  48555. enumerable: true,
  48556. configurable: true
  48557. });
  48558. /**
  48559. * Returns the string "PointLight"
  48560. * @returns the class name
  48561. */
  48562. PointLight.prototype.getClassName = function () {
  48563. return "PointLight";
  48564. };
  48565. /**
  48566. * Returns the integer 0.
  48567. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48568. */
  48569. PointLight.prototype.getTypeID = function () {
  48570. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48571. };
  48572. /**
  48573. * Specifies wether or not the shadowmap should be a cube texture.
  48574. * @returns true if the shadowmap needs to be a cube texture.
  48575. */
  48576. PointLight.prototype.needCube = function () {
  48577. return !this.direction;
  48578. };
  48579. /**
  48580. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48581. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48582. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48583. */
  48584. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48585. if (this.direction) {
  48586. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48587. }
  48588. else {
  48589. switch (faceIndex) {
  48590. case 0:
  48591. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48592. case 1:
  48593. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48594. case 2:
  48595. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48596. case 3:
  48597. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48598. case 4:
  48599. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48600. case 5:
  48601. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48602. }
  48603. }
  48604. return BABYLON.Vector3.Zero();
  48605. };
  48606. /**
  48607. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48608. * - fov = PI / 2
  48609. * - aspect ratio : 1.0
  48610. * - z-near and far equal to the active camera minZ and maxZ.
  48611. * Returns the PointLight.
  48612. */
  48613. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48614. var activeCamera = this.getScene().activeCamera;
  48615. if (!activeCamera) {
  48616. return;
  48617. }
  48618. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48619. };
  48620. PointLight.prototype._buildUniformLayout = function () {
  48621. this._uniformBuffer.addUniform("vLightData", 4);
  48622. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48623. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48624. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48625. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48626. this._uniformBuffer.addUniform("depthValues", 2);
  48627. this._uniformBuffer.create();
  48628. };
  48629. /**
  48630. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48631. * @param effect The effect to update
  48632. * @param lightIndex The index of the light in the effect to update
  48633. * @returns The point light
  48634. */
  48635. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48636. if (this.computeTransformedInformation()) {
  48637. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48638. }
  48639. else {
  48640. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48641. }
  48642. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48643. return this;
  48644. };
  48645. /**
  48646. * Prepares the list of defines specific to the light type.
  48647. * @param defines the list of defines
  48648. * @param lightIndex defines the index of the light for the effect
  48649. */
  48650. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48651. defines["POINTLIGHT" + lightIndex] = true;
  48652. };
  48653. __decorate([
  48654. BABYLON.serialize()
  48655. ], PointLight.prototype, "shadowAngle", null);
  48656. return PointLight;
  48657. }(BABYLON.ShadowLight));
  48658. BABYLON.PointLight = PointLight;
  48659. })(BABYLON || (BABYLON = {}));
  48660. //# sourceMappingURL=babylon.pointLight.js.map
  48661. var BABYLON;
  48662. (function (BABYLON) {
  48663. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48664. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48665. });
  48666. /**
  48667. * A directional light is defined by a direction (what a surprise!).
  48668. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48669. * 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.
  48670. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48671. */
  48672. var DirectionalLight = /** @class */ (function (_super) {
  48673. __extends(DirectionalLight, _super);
  48674. /**
  48675. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48676. * The directional light is emitted from everywhere in the given direction.
  48677. * It can cast shawdows.
  48678. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48679. * @param name The friendly name of the light
  48680. * @param direction The direction of the light
  48681. * @param scene The scene the light belongs to
  48682. */
  48683. function DirectionalLight(name, direction, scene) {
  48684. var _this = _super.call(this, name, scene) || this;
  48685. _this._shadowFrustumSize = 0;
  48686. _this._shadowOrthoScale = 0.1;
  48687. /**
  48688. * Automatically compute the projection matrix to best fit (including all the casters)
  48689. * on each frame.
  48690. */
  48691. _this.autoUpdateExtends = true;
  48692. // Cache
  48693. _this._orthoLeft = Number.MAX_VALUE;
  48694. _this._orthoRight = Number.MIN_VALUE;
  48695. _this._orthoTop = Number.MIN_VALUE;
  48696. _this._orthoBottom = Number.MAX_VALUE;
  48697. _this.position = direction.scale(-1.0);
  48698. _this.direction = direction;
  48699. return _this;
  48700. }
  48701. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48702. /**
  48703. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48704. */
  48705. get: function () {
  48706. return this._shadowFrustumSize;
  48707. },
  48708. /**
  48709. * Specifies a fix frustum size for the shadow generation.
  48710. */
  48711. set: function (value) {
  48712. this._shadowFrustumSize = value;
  48713. this.forceProjectionMatrixCompute();
  48714. },
  48715. enumerable: true,
  48716. configurable: true
  48717. });
  48718. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48719. /**
  48720. * Gets the shadow projection scale against the optimal computed one.
  48721. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48722. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48723. */
  48724. get: function () {
  48725. return this._shadowOrthoScale;
  48726. },
  48727. /**
  48728. * Sets the shadow projection scale against the optimal computed one.
  48729. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48730. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48731. */
  48732. set: function (value) {
  48733. this._shadowOrthoScale = value;
  48734. this.forceProjectionMatrixCompute();
  48735. },
  48736. enumerable: true,
  48737. configurable: true
  48738. });
  48739. /**
  48740. * Returns the string "DirectionalLight".
  48741. * @return The class name
  48742. */
  48743. DirectionalLight.prototype.getClassName = function () {
  48744. return "DirectionalLight";
  48745. };
  48746. /**
  48747. * Returns the integer 1.
  48748. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48749. */
  48750. DirectionalLight.prototype.getTypeID = function () {
  48751. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48752. };
  48753. /**
  48754. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48755. * Returns the DirectionalLight Shadow projection matrix.
  48756. */
  48757. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48758. if (this.shadowFrustumSize > 0) {
  48759. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48760. }
  48761. else {
  48762. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48763. }
  48764. };
  48765. /**
  48766. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48767. * Returns the DirectionalLight Shadow projection matrix.
  48768. */
  48769. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48770. var activeCamera = this.getScene().activeCamera;
  48771. if (!activeCamera) {
  48772. return;
  48773. }
  48774. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48775. };
  48776. /**
  48777. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48778. * Returns the DirectionalLight Shadow projection matrix.
  48779. */
  48780. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48781. var activeCamera = this.getScene().activeCamera;
  48782. if (!activeCamera) {
  48783. return;
  48784. }
  48785. // Check extends
  48786. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48787. var tempVector3 = BABYLON.Vector3.Zero();
  48788. this._orthoLeft = Number.MAX_VALUE;
  48789. this._orthoRight = Number.MIN_VALUE;
  48790. this._orthoTop = Number.MIN_VALUE;
  48791. this._orthoBottom = Number.MAX_VALUE;
  48792. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48793. var mesh = renderList[meshIndex];
  48794. if (!mesh) {
  48795. continue;
  48796. }
  48797. var boundingInfo = mesh.getBoundingInfo();
  48798. var boundingBox = boundingInfo.boundingBox;
  48799. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48800. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48801. if (tempVector3.x < this._orthoLeft)
  48802. this._orthoLeft = tempVector3.x;
  48803. if (tempVector3.y < this._orthoBottom)
  48804. this._orthoBottom = tempVector3.y;
  48805. if (tempVector3.x > this._orthoRight)
  48806. this._orthoRight = tempVector3.x;
  48807. if (tempVector3.y > this._orthoTop)
  48808. this._orthoTop = tempVector3.y;
  48809. }
  48810. }
  48811. }
  48812. var xOffset = this._orthoRight - this._orthoLeft;
  48813. var yOffset = this._orthoTop - this._orthoBottom;
  48814. 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);
  48815. };
  48816. DirectionalLight.prototype._buildUniformLayout = function () {
  48817. this._uniformBuffer.addUniform("vLightData", 4);
  48818. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48819. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48820. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48821. this._uniformBuffer.addUniform("depthValues", 2);
  48822. this._uniformBuffer.create();
  48823. };
  48824. /**
  48825. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48826. * @param effect The effect to update
  48827. * @param lightIndex The index of the light in the effect to update
  48828. * @returns The directional light
  48829. */
  48830. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48831. if (this.computeTransformedInformation()) {
  48832. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48833. return this;
  48834. }
  48835. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48836. return this;
  48837. };
  48838. /**
  48839. * Gets the minZ used for shadow according to both the scene and the light.
  48840. *
  48841. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48842. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48843. * @param activeCamera The camera we are returning the min for
  48844. * @returns the depth min z
  48845. */
  48846. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48847. return 1;
  48848. };
  48849. /**
  48850. * Gets the maxZ used for shadow according to both the scene and the light.
  48851. *
  48852. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48853. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48854. * @param activeCamera The camera we are returning the max for
  48855. * @returns the depth max z
  48856. */
  48857. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48858. return 1;
  48859. };
  48860. /**
  48861. * Prepares the list of defines specific to the light type.
  48862. * @param defines the list of defines
  48863. * @param lightIndex defines the index of the light for the effect
  48864. */
  48865. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48866. defines["DIRLIGHT" + lightIndex] = true;
  48867. };
  48868. __decorate([
  48869. BABYLON.serialize()
  48870. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48871. __decorate([
  48872. BABYLON.serialize()
  48873. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48874. __decorate([
  48875. BABYLON.serialize()
  48876. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48877. return DirectionalLight;
  48878. }(BABYLON.ShadowLight));
  48879. BABYLON.DirectionalLight = DirectionalLight;
  48880. })(BABYLON || (BABYLON = {}));
  48881. //# sourceMappingURL=babylon.directionalLight.js.map
  48882. var BABYLON;
  48883. (function (BABYLON) {
  48884. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48885. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48886. });
  48887. /**
  48888. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48889. * These values define a cone of light starting from the position, emitting toward the direction.
  48890. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48891. * and the exponent defines the speed of the decay of the light with distance (reach).
  48892. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48893. */
  48894. var SpotLight = /** @class */ (function (_super) {
  48895. __extends(SpotLight, _super);
  48896. /**
  48897. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48898. * It can cast shadows.
  48899. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48900. * @param name The light friendly name
  48901. * @param position The position of the spot light in the scene
  48902. * @param direction The direction of the light in the scene
  48903. * @param angle The cone angle of the light in Radians
  48904. * @param exponent The light decay speed with the distance from the emission spot
  48905. * @param scene The scene the lights belongs to
  48906. */
  48907. function SpotLight(name, position, direction, angle, exponent, scene) {
  48908. var _this = _super.call(this, name, scene) || this;
  48909. _this._innerAngle = 0;
  48910. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48911. _this._projectionTextureLightNear = 1e-6;
  48912. _this._projectionTextureLightFar = 1000.0;
  48913. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48914. _this._projectionTextureViewLightDirty = true;
  48915. _this._projectionTextureProjectionLightDirty = true;
  48916. _this._projectionTextureDirty = true;
  48917. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48918. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48919. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48920. _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);
  48921. _this.position = position;
  48922. _this.direction = direction;
  48923. _this.angle = angle;
  48924. _this.exponent = exponent;
  48925. return _this;
  48926. }
  48927. Object.defineProperty(SpotLight.prototype, "angle", {
  48928. /**
  48929. * Gets the cone angle of the spot light in Radians.
  48930. */
  48931. get: function () {
  48932. return this._angle;
  48933. },
  48934. /**
  48935. * Sets the cone angle of the spot light in Radians.
  48936. */
  48937. set: function (value) {
  48938. this._angle = value;
  48939. this._cosHalfAngle = Math.cos(value * 0.5);
  48940. this._projectionTextureProjectionLightDirty = true;
  48941. this.forceProjectionMatrixCompute();
  48942. this._computeAngleValues();
  48943. },
  48944. enumerable: true,
  48945. configurable: true
  48946. });
  48947. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  48948. /**
  48949. * Only used in gltf falloff mode, this defines the angle where
  48950. * the directional falloff will start before cutting at angle which could be seen
  48951. * as outer angle.
  48952. */
  48953. get: function () {
  48954. return this._angle;
  48955. },
  48956. /**
  48957. * Only used in gltf falloff mode, this defines the angle where
  48958. * the directional falloff will start before cutting at angle which could be seen
  48959. * as outer angle.
  48960. */
  48961. set: function (value) {
  48962. this._innerAngle = value;
  48963. this._computeAngleValues();
  48964. },
  48965. enumerable: true,
  48966. configurable: true
  48967. });
  48968. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48969. /**
  48970. * Allows scaling the angle of the light for shadow generation only.
  48971. */
  48972. get: function () {
  48973. return this._shadowAngleScale;
  48974. },
  48975. /**
  48976. * Allows scaling the angle of the light for shadow generation only.
  48977. */
  48978. set: function (value) {
  48979. this._shadowAngleScale = value;
  48980. this.forceProjectionMatrixCompute();
  48981. },
  48982. enumerable: true,
  48983. configurable: true
  48984. });
  48985. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48986. /**
  48987. * Allows reading the projecton texture
  48988. */
  48989. get: function () {
  48990. return this._projectionTextureMatrix;
  48991. },
  48992. enumerable: true,
  48993. configurable: true
  48994. });
  48995. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48996. /**
  48997. * Gets the near clip of the Spotlight for texture projection.
  48998. */
  48999. get: function () {
  49000. return this._projectionTextureLightNear;
  49001. },
  49002. /**
  49003. * Sets the near clip of the Spotlight for texture projection.
  49004. */
  49005. set: function (value) {
  49006. this._projectionTextureLightNear = value;
  49007. this._projectionTextureProjectionLightDirty = true;
  49008. },
  49009. enumerable: true,
  49010. configurable: true
  49011. });
  49012. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49013. /**
  49014. * Gets the far clip of the Spotlight for texture projection.
  49015. */
  49016. get: function () {
  49017. return this._projectionTextureLightFar;
  49018. },
  49019. /**
  49020. * Sets the far clip of the Spotlight for texture projection.
  49021. */
  49022. set: function (value) {
  49023. this._projectionTextureLightFar = value;
  49024. this._projectionTextureProjectionLightDirty = true;
  49025. },
  49026. enumerable: true,
  49027. configurable: true
  49028. });
  49029. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49030. /**
  49031. * Gets the Up vector of the Spotlight for texture projection.
  49032. */
  49033. get: function () {
  49034. return this._projectionTextureUpDirection;
  49035. },
  49036. /**
  49037. * Sets the Up vector of the Spotlight for texture projection.
  49038. */
  49039. set: function (value) {
  49040. this._projectionTextureUpDirection = value;
  49041. this._projectionTextureProjectionLightDirty = true;
  49042. },
  49043. enumerable: true,
  49044. configurable: true
  49045. });
  49046. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49047. /**
  49048. * Gets the projection texture of the light.
  49049. */
  49050. get: function () {
  49051. return this._projectionTexture;
  49052. },
  49053. /**
  49054. * Sets the projection texture of the light.
  49055. */
  49056. set: function (value) {
  49057. this._projectionTexture = value;
  49058. this._projectionTextureDirty = true;
  49059. },
  49060. enumerable: true,
  49061. configurable: true
  49062. });
  49063. /**
  49064. * Returns the string "SpotLight".
  49065. * @returns the class name
  49066. */
  49067. SpotLight.prototype.getClassName = function () {
  49068. return "SpotLight";
  49069. };
  49070. /**
  49071. * Returns the integer 2.
  49072. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49073. */
  49074. SpotLight.prototype.getTypeID = function () {
  49075. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49076. };
  49077. /**
  49078. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49079. */
  49080. SpotLight.prototype._setDirection = function (value) {
  49081. _super.prototype._setDirection.call(this, value);
  49082. this._projectionTextureViewLightDirty = true;
  49083. };
  49084. /**
  49085. * Overrides the position setter to recompute the projection texture view light Matrix.
  49086. */
  49087. SpotLight.prototype._setPosition = function (value) {
  49088. _super.prototype._setPosition.call(this, value);
  49089. this._projectionTextureViewLightDirty = true;
  49090. };
  49091. /**
  49092. * 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.
  49093. * Returns the SpotLight.
  49094. */
  49095. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49096. var activeCamera = this.getScene().activeCamera;
  49097. if (!activeCamera) {
  49098. return;
  49099. }
  49100. this._shadowAngleScale = this._shadowAngleScale || 1;
  49101. var angle = this._shadowAngleScale * this._angle;
  49102. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49103. };
  49104. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49105. this._projectionTextureViewLightDirty = false;
  49106. this._projectionTextureDirty = true;
  49107. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49108. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49109. };
  49110. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49111. this._projectionTextureProjectionLightDirty = false;
  49112. this._projectionTextureDirty = true;
  49113. var light_far = this.projectionTextureLightFar;
  49114. var light_near = this.projectionTextureLightNear;
  49115. var P = light_far / (light_far - light_near);
  49116. var Q = -P * light_near;
  49117. var S = 1.0 / Math.tan(this._angle / 2.0);
  49118. var A = 1.0;
  49119. 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);
  49120. };
  49121. /**
  49122. * Main function for light texture projection matrix computing.
  49123. */
  49124. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49125. this._projectionTextureDirty = false;
  49126. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49127. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49128. };
  49129. SpotLight.prototype._buildUniformLayout = function () {
  49130. this._uniformBuffer.addUniform("vLightData", 4);
  49131. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49132. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49133. this._uniformBuffer.addUniform("vLightDirection", 3);
  49134. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49135. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49136. this._uniformBuffer.addUniform("depthValues", 2);
  49137. this._uniformBuffer.create();
  49138. };
  49139. SpotLight.prototype._computeAngleValues = function () {
  49140. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49141. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49142. };
  49143. /**
  49144. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49145. * @param effect The effect to update
  49146. * @param lightIndex The index of the light in the effect to update
  49147. * @returns The spot light
  49148. */
  49149. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49150. var normalizeDirection;
  49151. if (this.computeTransformedInformation()) {
  49152. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49153. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49154. }
  49155. else {
  49156. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49157. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49158. }
  49159. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49160. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49161. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49162. if (this._projectionTextureViewLightDirty) {
  49163. this._computeProjectionTextureViewLightMatrix();
  49164. }
  49165. if (this._projectionTextureProjectionLightDirty) {
  49166. this._computeProjectionTextureProjectionLightMatrix();
  49167. }
  49168. if (this._projectionTextureDirty) {
  49169. this._computeProjectionTextureMatrix();
  49170. }
  49171. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49172. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49173. }
  49174. return this;
  49175. };
  49176. /**
  49177. * Disposes the light and the associated resources.
  49178. */
  49179. SpotLight.prototype.dispose = function () {
  49180. _super.prototype.dispose.call(this);
  49181. if (this._projectionTexture) {
  49182. this._projectionTexture.dispose();
  49183. }
  49184. };
  49185. /**
  49186. * Prepares the list of defines specific to the light type.
  49187. * @param defines the list of defines
  49188. * @param lightIndex defines the index of the light for the effect
  49189. */
  49190. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49191. defines["SPOTLIGHT" + lightIndex] = true;
  49192. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49193. };
  49194. __decorate([
  49195. BABYLON.serialize()
  49196. ], SpotLight.prototype, "angle", null);
  49197. __decorate([
  49198. BABYLON.serialize()
  49199. ], SpotLight.prototype, "innerAngle", null);
  49200. __decorate([
  49201. BABYLON.serialize()
  49202. ], SpotLight.prototype, "shadowAngleScale", null);
  49203. __decorate([
  49204. BABYLON.serialize()
  49205. ], SpotLight.prototype, "exponent", void 0);
  49206. __decorate([
  49207. BABYLON.serialize()
  49208. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49209. __decorate([
  49210. BABYLON.serialize()
  49211. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49212. __decorate([
  49213. BABYLON.serialize()
  49214. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49215. __decorate([
  49216. BABYLON.serializeAsTexture("projectedLightTexture")
  49217. ], SpotLight.prototype, "_projectionTexture", void 0);
  49218. return SpotLight;
  49219. }(BABYLON.ShadowLight));
  49220. BABYLON.SpotLight = SpotLight;
  49221. })(BABYLON || (BABYLON = {}));
  49222. //# sourceMappingURL=babylon.spotLight.js.map
  49223. var BABYLON;
  49224. (function (BABYLON) {
  49225. /**
  49226. * Class used to override all child animations of a given target
  49227. */
  49228. var AnimationPropertiesOverride = /** @class */ (function () {
  49229. function AnimationPropertiesOverride() {
  49230. /**
  49231. * Gets or sets a value indicating if animation blending must be used
  49232. */
  49233. this.enableBlending = false;
  49234. /**
  49235. * Gets or sets the blending speed to use when enableBlending is true
  49236. */
  49237. this.blendingSpeed = 0.01;
  49238. /**
  49239. * Gets or sets the default loop mode to use
  49240. */
  49241. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49242. }
  49243. return AnimationPropertiesOverride;
  49244. }());
  49245. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49246. })(BABYLON || (BABYLON = {}));
  49247. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49248. var BABYLON;
  49249. (function (BABYLON) {
  49250. /**
  49251. * Represents the range of an animation
  49252. */
  49253. var AnimationRange = /** @class */ (function () {
  49254. /**
  49255. * Initializes the range of an animation
  49256. * @param name The name of the animation range
  49257. * @param from The starting frame of the animation
  49258. * @param to The ending frame of the animation
  49259. */
  49260. function AnimationRange(
  49261. /**The name of the animation range**/
  49262. name,
  49263. /**The starting frame of the animation */
  49264. from,
  49265. /**The ending frame of the animation*/
  49266. to) {
  49267. this.name = name;
  49268. this.from = from;
  49269. this.to = to;
  49270. }
  49271. /**
  49272. * Makes a copy of the animation range
  49273. * @returns A copy of the animation range
  49274. */
  49275. AnimationRange.prototype.clone = function () {
  49276. return new AnimationRange(this.name, this.from, this.to);
  49277. };
  49278. return AnimationRange;
  49279. }());
  49280. BABYLON.AnimationRange = AnimationRange;
  49281. /**
  49282. * Composed of a frame, and an action function
  49283. */
  49284. var AnimationEvent = /** @class */ (function () {
  49285. /**
  49286. * Initializes the animation event
  49287. * @param frame The frame for which the event is triggered
  49288. * @param action The event to perform when triggered
  49289. * @param onlyOnce Specifies if the event should be triggered only once
  49290. */
  49291. function AnimationEvent(
  49292. /** The frame for which the event is triggered **/
  49293. frame,
  49294. /** The event to perform when triggered **/
  49295. action,
  49296. /** Specifies if the event should be triggered only once**/
  49297. onlyOnce) {
  49298. this.frame = frame;
  49299. this.action = action;
  49300. this.onlyOnce = onlyOnce;
  49301. /**
  49302. * Specifies if the animation event is done
  49303. */
  49304. this.isDone = false;
  49305. }
  49306. /** @hidden */
  49307. AnimationEvent.prototype._clone = function () {
  49308. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49309. };
  49310. return AnimationEvent;
  49311. }());
  49312. BABYLON.AnimationEvent = AnimationEvent;
  49313. /**
  49314. * A cursor which tracks a point on a path
  49315. */
  49316. var PathCursor = /** @class */ (function () {
  49317. /**
  49318. * Initializes the path cursor
  49319. * @param path The path to track
  49320. */
  49321. function PathCursor(path) {
  49322. this.path = path;
  49323. /**
  49324. * Stores path cursor callbacks for when an onchange event is triggered
  49325. */
  49326. this._onchange = new Array();
  49327. /**
  49328. * The value of the path cursor
  49329. */
  49330. this.value = 0;
  49331. /**
  49332. * The animation array of the path cursor
  49333. */
  49334. this.animations = new Array();
  49335. }
  49336. /**
  49337. * Gets the cursor point on the path
  49338. * @returns A point on the path cursor at the cursor location
  49339. */
  49340. PathCursor.prototype.getPoint = function () {
  49341. var point = this.path.getPointAtLengthPosition(this.value);
  49342. return new BABYLON.Vector3(point.x, 0, point.y);
  49343. };
  49344. /**
  49345. * Moves the cursor ahead by the step amount
  49346. * @param step The amount to move the cursor forward
  49347. * @returns This path cursor
  49348. */
  49349. PathCursor.prototype.moveAhead = function (step) {
  49350. if (step === void 0) { step = 0.002; }
  49351. this.move(step);
  49352. return this;
  49353. };
  49354. /**
  49355. * Moves the cursor behind by the step amount
  49356. * @param step The amount to move the cursor back
  49357. * @returns This path cursor
  49358. */
  49359. PathCursor.prototype.moveBack = function (step) {
  49360. if (step === void 0) { step = 0.002; }
  49361. this.move(-step);
  49362. return this;
  49363. };
  49364. /**
  49365. * Moves the cursor by the step amount
  49366. * If the step amount is greater than one, an exception is thrown
  49367. * @param step The amount to move the cursor
  49368. * @returns This path cursor
  49369. */
  49370. PathCursor.prototype.move = function (step) {
  49371. if (Math.abs(step) > 1) {
  49372. throw "step size should be less than 1.";
  49373. }
  49374. this.value += step;
  49375. this.ensureLimits();
  49376. this.raiseOnChange();
  49377. return this;
  49378. };
  49379. /**
  49380. * Ensures that the value is limited between zero and one
  49381. * @returns This path cursor
  49382. */
  49383. PathCursor.prototype.ensureLimits = function () {
  49384. while (this.value > 1) {
  49385. this.value -= 1;
  49386. }
  49387. while (this.value < 0) {
  49388. this.value += 1;
  49389. }
  49390. return this;
  49391. };
  49392. /**
  49393. * Runs onchange callbacks on change (used by the animation engine)
  49394. * @returns This path cursor
  49395. */
  49396. PathCursor.prototype.raiseOnChange = function () {
  49397. var _this = this;
  49398. this._onchange.forEach(function (f) { return f(_this); });
  49399. return this;
  49400. };
  49401. /**
  49402. * Executes a function on change
  49403. * @param f A path cursor onchange callback
  49404. * @returns This path cursor
  49405. */
  49406. PathCursor.prototype.onchange = function (f) {
  49407. this._onchange.push(f);
  49408. return this;
  49409. };
  49410. return PathCursor;
  49411. }());
  49412. BABYLON.PathCursor = PathCursor;
  49413. /**
  49414. * Enum for the animation key frame interpolation type
  49415. */
  49416. var AnimationKeyInterpolation;
  49417. (function (AnimationKeyInterpolation) {
  49418. /**
  49419. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49420. */
  49421. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49422. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49423. /**
  49424. * Class used to store any kind of animation
  49425. */
  49426. var Animation = /** @class */ (function () {
  49427. /**
  49428. * Initializes the animation
  49429. * @param name Name of the animation
  49430. * @param targetProperty Property to animate
  49431. * @param framePerSecond The frames per second of the animation
  49432. * @param dataType The data type of the animation
  49433. * @param loopMode The loop mode of the animation
  49434. * @param enableBlendings Specifies if blending should be enabled
  49435. */
  49436. function Animation(
  49437. /**Name of the animation */
  49438. name,
  49439. /**Property to animate */
  49440. targetProperty,
  49441. /**The frames per second of the animation */
  49442. framePerSecond,
  49443. /**The data type of the animation */
  49444. dataType,
  49445. /**The loop mode of the animation */
  49446. loopMode,
  49447. /**Specifies if blending should be enabled */
  49448. enableBlending) {
  49449. this.name = name;
  49450. this.targetProperty = targetProperty;
  49451. this.framePerSecond = framePerSecond;
  49452. this.dataType = dataType;
  49453. this.loopMode = loopMode;
  49454. this.enableBlending = enableBlending;
  49455. /**
  49456. * @hidden Internal use only
  49457. */
  49458. this._runtimeAnimations = new Array();
  49459. /**
  49460. * The set of event that will be linked to this animation
  49461. */
  49462. this._events = new Array();
  49463. /**
  49464. * Stores the blending speed of the animation
  49465. */
  49466. this.blendingSpeed = 0.01;
  49467. /**
  49468. * Stores the animation ranges for the animation
  49469. */
  49470. this._ranges = {};
  49471. this.targetPropertyPath = targetProperty.split(".");
  49472. this.dataType = dataType;
  49473. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49474. }
  49475. /**
  49476. * @hidden Internal use
  49477. */
  49478. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49479. var dataType = undefined;
  49480. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49481. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49482. }
  49483. else if (from instanceof BABYLON.Quaternion) {
  49484. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49485. }
  49486. else if (from instanceof BABYLON.Vector3) {
  49487. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49488. }
  49489. else if (from instanceof BABYLON.Vector2) {
  49490. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49491. }
  49492. else if (from instanceof BABYLON.Color3) {
  49493. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49494. }
  49495. else if (from instanceof BABYLON.Size) {
  49496. dataType = Animation.ANIMATIONTYPE_SIZE;
  49497. }
  49498. if (dataType == undefined) {
  49499. return null;
  49500. }
  49501. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49502. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49503. animation.setKeys(keys);
  49504. if (easingFunction !== undefined) {
  49505. animation.setEasingFunction(easingFunction);
  49506. }
  49507. return animation;
  49508. };
  49509. /**
  49510. * Sets up an animation
  49511. * @param property The property to animate
  49512. * @param animationType The animation type to apply
  49513. * @param framePerSecond The frames per second of the animation
  49514. * @param easingFunction The easing function used in the animation
  49515. * @returns The created animation
  49516. */
  49517. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49518. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49519. animation.setEasingFunction(easingFunction);
  49520. return animation;
  49521. };
  49522. /**
  49523. * Create and start an animation on a node
  49524. * @param name defines the name of the global animation that will be run on all nodes
  49525. * @param node defines the root node where the animation will take place
  49526. * @param targetProperty defines property to animate
  49527. * @param framePerSecond defines the number of frame per second yo use
  49528. * @param totalFrame defines the number of frames in total
  49529. * @param from defines the initial value
  49530. * @param to defines the final value
  49531. * @param loopMode defines which loop mode you want to use (off by default)
  49532. * @param easingFunction defines the easing function to use (linear by default)
  49533. * @param onAnimationEnd defines the callback to call when animation end
  49534. * @returns the animatable created for this animation
  49535. */
  49536. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49537. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49538. if (!animation) {
  49539. return null;
  49540. }
  49541. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49542. };
  49543. /**
  49544. * Create and start an animation on a node and its descendants
  49545. * @param name defines the name of the global animation that will be run on all nodes
  49546. * @param node defines the root node where the animation will take place
  49547. * @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
  49548. * @param targetProperty defines property to animate
  49549. * @param framePerSecond defines the number of frame per second to use
  49550. * @param totalFrame defines the number of frames in total
  49551. * @param from defines the initial value
  49552. * @param to defines the final value
  49553. * @param loopMode defines which loop mode you want to use (off by default)
  49554. * @param easingFunction defines the easing function to use (linear by default)
  49555. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49556. * @returns the list of animatables created for all nodes
  49557. * @example https://www.babylonjs-playground.com/#MH0VLI
  49558. */
  49559. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49560. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49561. if (!animation) {
  49562. return null;
  49563. }
  49564. var scene = node.getScene();
  49565. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49566. };
  49567. /**
  49568. * Creates a new animation, merges it with the existing animations and starts it
  49569. * @param name Name of the animation
  49570. * @param node Node which contains the scene that begins the animations
  49571. * @param targetProperty Specifies which property to animate
  49572. * @param framePerSecond The frames per second of the animation
  49573. * @param totalFrame The total number of frames
  49574. * @param from The frame at the beginning of the animation
  49575. * @param to The frame at the end of the animation
  49576. * @param loopMode Specifies the loop mode of the animation
  49577. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49578. * @param onAnimationEnd Callback to run once the animation is complete
  49579. * @returns Nullable animation
  49580. */
  49581. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49582. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49583. if (!animation) {
  49584. return null;
  49585. }
  49586. node.animations.push(animation);
  49587. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49588. };
  49589. /**
  49590. * Transition property of an host to the target Value
  49591. * @param property The property to transition
  49592. * @param targetValue The target Value of the property
  49593. * @param host The object where the property to animate belongs
  49594. * @param scene Scene used to run the animation
  49595. * @param frameRate Framerate (in frame/s) to use
  49596. * @param transition The transition type we want to use
  49597. * @param duration The duration of the animation, in milliseconds
  49598. * @param onAnimationEnd Callback trigger at the end of the animation
  49599. * @returns Nullable animation
  49600. */
  49601. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49602. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49603. if (duration <= 0) {
  49604. host[property] = targetValue;
  49605. if (onAnimationEnd) {
  49606. onAnimationEnd();
  49607. }
  49608. return null;
  49609. }
  49610. var endFrame = frameRate * (duration / 1000);
  49611. transition.setKeys([{
  49612. frame: 0,
  49613. value: host[property].clone ? host[property].clone() : host[property]
  49614. },
  49615. {
  49616. frame: endFrame,
  49617. value: targetValue
  49618. }]);
  49619. if (!host.animations) {
  49620. host.animations = [];
  49621. }
  49622. host.animations.push(transition);
  49623. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49624. animation.onAnimationEnd = onAnimationEnd;
  49625. return animation;
  49626. };
  49627. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49628. /**
  49629. * Return the array of runtime animations currently using this animation
  49630. */
  49631. get: function () {
  49632. return this._runtimeAnimations;
  49633. },
  49634. enumerable: true,
  49635. configurable: true
  49636. });
  49637. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49638. /**
  49639. * Specifies if any of the runtime animations are currently running
  49640. */
  49641. get: function () {
  49642. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49643. var runtimeAnimation = _a[_i];
  49644. if (!runtimeAnimation.isStopped) {
  49645. return true;
  49646. }
  49647. }
  49648. return false;
  49649. },
  49650. enumerable: true,
  49651. configurable: true
  49652. });
  49653. // Methods
  49654. /**
  49655. * Converts the animation to a string
  49656. * @param fullDetails support for multiple levels of logging within scene loading
  49657. * @returns String form of the animation
  49658. */
  49659. Animation.prototype.toString = function (fullDetails) {
  49660. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49661. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49662. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49663. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49664. if (fullDetails) {
  49665. ret += ", Ranges: {";
  49666. var first = true;
  49667. for (var name in this._ranges) {
  49668. if (first) {
  49669. ret += ", ";
  49670. first = false;
  49671. }
  49672. ret += name;
  49673. }
  49674. ret += "}";
  49675. }
  49676. return ret;
  49677. };
  49678. /**
  49679. * Add an event to this animation
  49680. * @param event Event to add
  49681. */
  49682. Animation.prototype.addEvent = function (event) {
  49683. this._events.push(event);
  49684. };
  49685. /**
  49686. * Remove all events found at the given frame
  49687. * @param frame The frame to remove events from
  49688. */
  49689. Animation.prototype.removeEvents = function (frame) {
  49690. for (var index = 0; index < this._events.length; index++) {
  49691. if (this._events[index].frame === frame) {
  49692. this._events.splice(index, 1);
  49693. index--;
  49694. }
  49695. }
  49696. };
  49697. /**
  49698. * Retrieves all the events from the animation
  49699. * @returns Events from the animation
  49700. */
  49701. Animation.prototype.getEvents = function () {
  49702. return this._events;
  49703. };
  49704. /**
  49705. * Creates an animation range
  49706. * @param name Name of the animation range
  49707. * @param from Starting frame of the animation range
  49708. * @param to Ending frame of the animation
  49709. */
  49710. Animation.prototype.createRange = function (name, from, to) {
  49711. // check name not already in use; could happen for bones after serialized
  49712. if (!this._ranges[name]) {
  49713. this._ranges[name] = new AnimationRange(name, from, to);
  49714. }
  49715. };
  49716. /**
  49717. * Deletes an animation range by name
  49718. * @param name Name of the animation range to delete
  49719. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49720. */
  49721. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49722. if (deleteFrames === void 0) { deleteFrames = true; }
  49723. var range = this._ranges[name];
  49724. if (!range) {
  49725. return;
  49726. }
  49727. if (deleteFrames) {
  49728. var from = range.from;
  49729. var to = range.to;
  49730. // this loop MUST go high to low for multiple splices to work
  49731. for (var key = this._keys.length - 1; key >= 0; key--) {
  49732. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49733. this._keys.splice(key, 1);
  49734. }
  49735. }
  49736. }
  49737. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49738. };
  49739. /**
  49740. * Gets the animation range by name, or null if not defined
  49741. * @param name Name of the animation range
  49742. * @returns Nullable animation range
  49743. */
  49744. Animation.prototype.getRange = function (name) {
  49745. return this._ranges[name];
  49746. };
  49747. /**
  49748. * Gets the key frames from the animation
  49749. * @returns The key frames of the animation
  49750. */
  49751. Animation.prototype.getKeys = function () {
  49752. return this._keys;
  49753. };
  49754. /**
  49755. * Gets the highest frame rate of the animation
  49756. * @returns Highest frame rate of the animation
  49757. */
  49758. Animation.prototype.getHighestFrame = function () {
  49759. var ret = 0;
  49760. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49761. if (ret < this._keys[key].frame) {
  49762. ret = this._keys[key].frame;
  49763. }
  49764. }
  49765. return ret;
  49766. };
  49767. /**
  49768. * Gets the easing function of the animation
  49769. * @returns Easing function of the animation
  49770. */
  49771. Animation.prototype.getEasingFunction = function () {
  49772. return this._easingFunction;
  49773. };
  49774. /**
  49775. * Sets the easing function of the animation
  49776. * @param easingFunction A custom mathematical formula for animation
  49777. */
  49778. Animation.prototype.setEasingFunction = function (easingFunction) {
  49779. this._easingFunction = easingFunction;
  49780. };
  49781. /**
  49782. * Interpolates a scalar linearly
  49783. * @param startValue Start value of the animation curve
  49784. * @param endValue End value of the animation curve
  49785. * @param gradient Scalar amount to interpolate
  49786. * @returns Interpolated scalar value
  49787. */
  49788. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49789. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49790. };
  49791. /**
  49792. * Interpolates a scalar cubically
  49793. * @param startValue Start value of the animation curve
  49794. * @param outTangent End tangent of the animation
  49795. * @param endValue End value of the animation curve
  49796. * @param inTangent Start tangent of the animation curve
  49797. * @param gradient Scalar amount to interpolate
  49798. * @returns Interpolated scalar value
  49799. */
  49800. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49801. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49802. };
  49803. /**
  49804. * Interpolates a quaternion using a spherical linear interpolation
  49805. * @param startValue Start value of the animation curve
  49806. * @param endValue End value of the animation curve
  49807. * @param gradient Scalar amount to interpolate
  49808. * @returns Interpolated quaternion value
  49809. */
  49810. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49811. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49812. };
  49813. /**
  49814. * Interpolates a quaternion cubically
  49815. * @param startValue Start value of the animation curve
  49816. * @param outTangent End tangent of the animation curve
  49817. * @param endValue End value of the animation curve
  49818. * @param inTangent Start tangent of the animation curve
  49819. * @param gradient Scalar amount to interpolate
  49820. * @returns Interpolated quaternion value
  49821. */
  49822. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49823. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49824. };
  49825. /**
  49826. * Interpolates a Vector3 linearl
  49827. * @param startValue Start value of the animation curve
  49828. * @param endValue End value of the animation curve
  49829. * @param gradient Scalar amount to interpolate
  49830. * @returns Interpolated scalar value
  49831. */
  49832. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49833. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49834. };
  49835. /**
  49836. * Interpolates a Vector3 cubically
  49837. * @param startValue Start value of the animation curve
  49838. * @param outTangent End tangent of the animation
  49839. * @param endValue End value of the animation curve
  49840. * @param inTangent Start tangent of the animation curve
  49841. * @param gradient Scalar amount to interpolate
  49842. * @returns InterpolatedVector3 value
  49843. */
  49844. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49845. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49846. };
  49847. /**
  49848. * Interpolates a Vector2 linearly
  49849. * @param startValue Start value of the animation curve
  49850. * @param endValue End value of the animation curve
  49851. * @param gradient Scalar amount to interpolate
  49852. * @returns Interpolated Vector2 value
  49853. */
  49854. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49855. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49856. };
  49857. /**
  49858. * Interpolates a Vector2 cubically
  49859. * @param startValue Start value of the animation curve
  49860. * @param outTangent End tangent of the animation
  49861. * @param endValue End value of the animation curve
  49862. * @param inTangent Start tangent of the animation curve
  49863. * @param gradient Scalar amount to interpolate
  49864. * @returns Interpolated Vector2 value
  49865. */
  49866. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49867. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49868. };
  49869. /**
  49870. * Interpolates a size linearly
  49871. * @param startValue Start value of the animation curve
  49872. * @param endValue End value of the animation curve
  49873. * @param gradient Scalar amount to interpolate
  49874. * @returns Interpolated Size value
  49875. */
  49876. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49877. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49878. };
  49879. /**
  49880. * Interpolates a Color3 linearly
  49881. * @param startValue Start value of the animation curve
  49882. * @param endValue End value of the animation curve
  49883. * @param gradient Scalar amount to interpolate
  49884. * @returns Interpolated Color3 value
  49885. */
  49886. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49887. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49888. };
  49889. /**
  49890. * @hidden Internal use only
  49891. */
  49892. Animation.prototype._getKeyValue = function (value) {
  49893. if (typeof value === "function") {
  49894. return value();
  49895. }
  49896. return value;
  49897. };
  49898. /**
  49899. * @hidden Internal use only
  49900. */
  49901. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49902. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49903. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49904. }
  49905. var keys = this.getKeys();
  49906. // Try to get a hash to find the right key
  49907. 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));
  49908. if (keys[startKeyIndex].frame >= currentFrame) {
  49909. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49910. startKeyIndex--;
  49911. }
  49912. }
  49913. for (var key = startKeyIndex; key < keys.length; key++) {
  49914. var endKey = keys[key + 1];
  49915. if (endKey.frame >= currentFrame) {
  49916. var startKey = keys[key];
  49917. var startValue = this._getKeyValue(startKey.value);
  49918. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49919. return startValue;
  49920. }
  49921. var endValue = this._getKeyValue(endKey.value);
  49922. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49923. var frameDelta = endKey.frame - startKey.frame;
  49924. // gradient : percent of currentFrame between the frame inf and the frame sup
  49925. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49926. // check for easingFunction and correction of gradient
  49927. var easingFunction = this.getEasingFunction();
  49928. if (easingFunction != null) {
  49929. gradient = easingFunction.ease(gradient);
  49930. }
  49931. switch (this.dataType) {
  49932. // Float
  49933. case Animation.ANIMATIONTYPE_FLOAT:
  49934. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49935. switch (loopMode) {
  49936. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49937. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49938. return floatValue;
  49939. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49940. return offsetValue * repeatCount + floatValue;
  49941. }
  49942. break;
  49943. // Quaternion
  49944. case Animation.ANIMATIONTYPE_QUATERNION:
  49945. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49946. switch (loopMode) {
  49947. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49948. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49949. return quatValue;
  49950. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49951. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49952. }
  49953. return quatValue;
  49954. // Vector3
  49955. case Animation.ANIMATIONTYPE_VECTOR3:
  49956. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49957. switch (loopMode) {
  49958. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49959. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49960. return vec3Value;
  49961. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49962. return vec3Value.add(offsetValue.scale(repeatCount));
  49963. }
  49964. // Vector2
  49965. case Animation.ANIMATIONTYPE_VECTOR2:
  49966. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49967. switch (loopMode) {
  49968. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49969. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49970. return vec2Value;
  49971. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49972. return vec2Value.add(offsetValue.scale(repeatCount));
  49973. }
  49974. // Size
  49975. case Animation.ANIMATIONTYPE_SIZE:
  49976. switch (loopMode) {
  49977. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49978. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49979. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49980. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49981. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49982. }
  49983. // Color3
  49984. case Animation.ANIMATIONTYPE_COLOR3:
  49985. switch (loopMode) {
  49986. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49987. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49988. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49989. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49990. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49991. }
  49992. // Matrix
  49993. case Animation.ANIMATIONTYPE_MATRIX:
  49994. switch (loopMode) {
  49995. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49996. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49997. if (Animation.AllowMatricesInterpolation) {
  49998. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49999. }
  50000. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50001. return startValue;
  50002. }
  50003. default:
  50004. break;
  50005. }
  50006. break;
  50007. }
  50008. }
  50009. return this._getKeyValue(keys[keys.length - 1].value);
  50010. };
  50011. /**
  50012. * Defines the function to use to interpolate matrices
  50013. * @param startValue defines the start matrix
  50014. * @param endValue defines the end matrix
  50015. * @param gradient defines the gradient between both matrices
  50016. * @param result defines an optional target matrix where to store the interpolation
  50017. * @returns the interpolated matrix
  50018. */
  50019. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50020. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50021. if (result) {
  50022. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50023. return result;
  50024. }
  50025. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50026. }
  50027. if (result) {
  50028. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50029. return result;
  50030. }
  50031. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50032. };
  50033. /**
  50034. * Makes a copy of the animation
  50035. * @returns Cloned animation
  50036. */
  50037. Animation.prototype.clone = function () {
  50038. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50039. clone.enableBlending = this.enableBlending;
  50040. clone.blendingSpeed = this.blendingSpeed;
  50041. if (this._keys) {
  50042. clone.setKeys(this._keys);
  50043. }
  50044. if (this._ranges) {
  50045. clone._ranges = {};
  50046. for (var name in this._ranges) {
  50047. var range = this._ranges[name];
  50048. if (!range) {
  50049. continue;
  50050. }
  50051. clone._ranges[name] = range.clone();
  50052. }
  50053. }
  50054. return clone;
  50055. };
  50056. /**
  50057. * Sets the key frames of the animation
  50058. * @param values The animation key frames to set
  50059. */
  50060. Animation.prototype.setKeys = function (values) {
  50061. this._keys = values.slice(0);
  50062. };
  50063. /**
  50064. * Serializes the animation to an object
  50065. * @returns Serialized object
  50066. */
  50067. Animation.prototype.serialize = function () {
  50068. var serializationObject = {};
  50069. serializationObject.name = this.name;
  50070. serializationObject.property = this.targetProperty;
  50071. serializationObject.framePerSecond = this.framePerSecond;
  50072. serializationObject.dataType = this.dataType;
  50073. serializationObject.loopBehavior = this.loopMode;
  50074. serializationObject.enableBlending = this.enableBlending;
  50075. serializationObject.blendingSpeed = this.blendingSpeed;
  50076. var dataType = this.dataType;
  50077. serializationObject.keys = [];
  50078. var keys = this.getKeys();
  50079. for (var index = 0; index < keys.length; index++) {
  50080. var animationKey = keys[index];
  50081. var key = {};
  50082. key.frame = animationKey.frame;
  50083. switch (dataType) {
  50084. case Animation.ANIMATIONTYPE_FLOAT:
  50085. key.values = [animationKey.value];
  50086. break;
  50087. case Animation.ANIMATIONTYPE_QUATERNION:
  50088. case Animation.ANIMATIONTYPE_MATRIX:
  50089. case Animation.ANIMATIONTYPE_VECTOR3:
  50090. case Animation.ANIMATIONTYPE_COLOR3:
  50091. key.values = animationKey.value.asArray();
  50092. break;
  50093. }
  50094. serializationObject.keys.push(key);
  50095. }
  50096. serializationObject.ranges = [];
  50097. for (var name in this._ranges) {
  50098. var source = this._ranges[name];
  50099. if (!source) {
  50100. continue;
  50101. }
  50102. var range = {};
  50103. range.name = name;
  50104. range.from = source.from;
  50105. range.to = source.to;
  50106. serializationObject.ranges.push(range);
  50107. }
  50108. return serializationObject;
  50109. };
  50110. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50111. /**
  50112. * Get the float animation type
  50113. */
  50114. get: function () {
  50115. return Animation._ANIMATIONTYPE_FLOAT;
  50116. },
  50117. enumerable: true,
  50118. configurable: true
  50119. });
  50120. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50121. /**
  50122. * Get the Vector3 animation type
  50123. */
  50124. get: function () {
  50125. return Animation._ANIMATIONTYPE_VECTOR3;
  50126. },
  50127. enumerable: true,
  50128. configurable: true
  50129. });
  50130. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50131. /**
  50132. * Get the Vector2 animation type
  50133. */
  50134. get: function () {
  50135. return Animation._ANIMATIONTYPE_VECTOR2;
  50136. },
  50137. enumerable: true,
  50138. configurable: true
  50139. });
  50140. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50141. /**
  50142. * Get the Size animation type
  50143. */
  50144. get: function () {
  50145. return Animation._ANIMATIONTYPE_SIZE;
  50146. },
  50147. enumerable: true,
  50148. configurable: true
  50149. });
  50150. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50151. /**
  50152. * Get the Quaternion animation type
  50153. */
  50154. get: function () {
  50155. return Animation._ANIMATIONTYPE_QUATERNION;
  50156. },
  50157. enumerable: true,
  50158. configurable: true
  50159. });
  50160. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50161. /**
  50162. * Get the Matrix animation type
  50163. */
  50164. get: function () {
  50165. return Animation._ANIMATIONTYPE_MATRIX;
  50166. },
  50167. enumerable: true,
  50168. configurable: true
  50169. });
  50170. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50171. /**
  50172. * Get the Color3 animation type
  50173. */
  50174. get: function () {
  50175. return Animation._ANIMATIONTYPE_COLOR3;
  50176. },
  50177. enumerable: true,
  50178. configurable: true
  50179. });
  50180. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50181. /**
  50182. * Get the Relative Loop Mode
  50183. */
  50184. get: function () {
  50185. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50186. },
  50187. enumerable: true,
  50188. configurable: true
  50189. });
  50190. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50191. /**
  50192. * Get the Cycle Loop Mode
  50193. */
  50194. get: function () {
  50195. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50196. },
  50197. enumerable: true,
  50198. configurable: true
  50199. });
  50200. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50201. /**
  50202. * Get the Constant Loop Mode
  50203. */
  50204. get: function () {
  50205. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50206. },
  50207. enumerable: true,
  50208. configurable: true
  50209. });
  50210. /** @hidden */
  50211. Animation._UniversalLerp = function (left, right, amount) {
  50212. var constructor = left.constructor;
  50213. if (constructor.Lerp) { // Lerp supported
  50214. return constructor.Lerp(left, right, amount);
  50215. }
  50216. else if (constructor.Slerp) { // Slerp supported
  50217. return constructor.Slerp(left, right, amount);
  50218. }
  50219. else if (left.toFixed) { // Number
  50220. return left * (1.0 - amount) + amount * right;
  50221. }
  50222. else { // Blending not supported
  50223. return right;
  50224. }
  50225. };
  50226. /**
  50227. * Parses an animation object and creates an animation
  50228. * @param parsedAnimation Parsed animation object
  50229. * @returns Animation object
  50230. */
  50231. Animation.Parse = function (parsedAnimation) {
  50232. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50233. var dataType = parsedAnimation.dataType;
  50234. var keys = [];
  50235. var data;
  50236. var index;
  50237. if (parsedAnimation.enableBlending) {
  50238. animation.enableBlending = parsedAnimation.enableBlending;
  50239. }
  50240. if (parsedAnimation.blendingSpeed) {
  50241. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50242. }
  50243. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50244. var key = parsedAnimation.keys[index];
  50245. var inTangent;
  50246. var outTangent;
  50247. switch (dataType) {
  50248. case Animation.ANIMATIONTYPE_FLOAT:
  50249. data = key.values[0];
  50250. if (key.values.length >= 1) {
  50251. inTangent = key.values[1];
  50252. }
  50253. if (key.values.length >= 2) {
  50254. outTangent = key.values[2];
  50255. }
  50256. break;
  50257. case Animation.ANIMATIONTYPE_QUATERNION:
  50258. data = BABYLON.Quaternion.FromArray(key.values);
  50259. if (key.values.length >= 8) {
  50260. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50261. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50262. inTangent = _inTangent;
  50263. }
  50264. }
  50265. if (key.values.length >= 12) {
  50266. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50267. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50268. outTangent = _outTangent;
  50269. }
  50270. }
  50271. break;
  50272. case Animation.ANIMATIONTYPE_MATRIX:
  50273. data = BABYLON.Matrix.FromArray(key.values);
  50274. break;
  50275. case Animation.ANIMATIONTYPE_COLOR3:
  50276. data = BABYLON.Color3.FromArray(key.values);
  50277. break;
  50278. case Animation.ANIMATIONTYPE_VECTOR3:
  50279. default:
  50280. data = BABYLON.Vector3.FromArray(key.values);
  50281. break;
  50282. }
  50283. var keyData = {};
  50284. keyData.frame = key.frame;
  50285. keyData.value = data;
  50286. if (inTangent != undefined) {
  50287. keyData.inTangent = inTangent;
  50288. }
  50289. if (outTangent != undefined) {
  50290. keyData.outTangent = outTangent;
  50291. }
  50292. keys.push(keyData);
  50293. }
  50294. animation.setKeys(keys);
  50295. if (parsedAnimation.ranges) {
  50296. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50297. data = parsedAnimation.ranges[index];
  50298. animation.createRange(data.name, data.from, data.to);
  50299. }
  50300. }
  50301. return animation;
  50302. };
  50303. /**
  50304. * Appends the serialized animations from the source animations
  50305. * @param source Source containing the animations
  50306. * @param destination Target to store the animations
  50307. */
  50308. Animation.AppendSerializedAnimations = function (source, destination) {
  50309. if (source.animations) {
  50310. destination.animations = [];
  50311. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50312. var animation = source.animations[animationIndex];
  50313. destination.animations.push(animation.serialize());
  50314. }
  50315. }
  50316. };
  50317. /**
  50318. * Use matrix interpolation instead of using direct key value when animating matrices
  50319. */
  50320. Animation.AllowMatricesInterpolation = false;
  50321. /**
  50322. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50323. */
  50324. Animation.AllowMatrixDecomposeForInterpolation = true;
  50325. // Statics
  50326. /**
  50327. * Float animation type
  50328. */
  50329. Animation._ANIMATIONTYPE_FLOAT = 0;
  50330. /**
  50331. * Vector3 animation type
  50332. */
  50333. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50334. /**
  50335. * Quaternion animation type
  50336. */
  50337. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50338. /**
  50339. * Matrix animation type
  50340. */
  50341. Animation._ANIMATIONTYPE_MATRIX = 3;
  50342. /**
  50343. * Color3 animation type
  50344. */
  50345. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50346. /**
  50347. * Vector2 animation type
  50348. */
  50349. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50350. /**
  50351. * Size animation type
  50352. */
  50353. Animation._ANIMATIONTYPE_SIZE = 6;
  50354. /**
  50355. * Relative Loop Mode
  50356. */
  50357. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50358. /**
  50359. * Cycle Loop Mode
  50360. */
  50361. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50362. /**
  50363. * Constant Loop Mode
  50364. */
  50365. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50366. return Animation;
  50367. }());
  50368. BABYLON.Animation = Animation;
  50369. })(BABYLON || (BABYLON = {}));
  50370. //# sourceMappingURL=babylon.animation.js.map
  50371. var BABYLON;
  50372. (function (BABYLON) {
  50373. /**
  50374. * This class defines the direct association between an animation and a target
  50375. */
  50376. var TargetedAnimation = /** @class */ (function () {
  50377. function TargetedAnimation() {
  50378. }
  50379. return TargetedAnimation;
  50380. }());
  50381. BABYLON.TargetedAnimation = TargetedAnimation;
  50382. /**
  50383. * Use this class to create coordinated animations on multiple targets
  50384. */
  50385. var AnimationGroup = /** @class */ (function () {
  50386. function AnimationGroup(name, scene) {
  50387. if (scene === void 0) { scene = null; }
  50388. this.name = name;
  50389. this._targetedAnimations = new Array();
  50390. this._animatables = new Array();
  50391. this._from = Number.MAX_VALUE;
  50392. this._to = -Number.MAX_VALUE;
  50393. this._speedRatio = 1;
  50394. this.onAnimationEndObservable = new BABYLON.Observable();
  50395. /**
  50396. * This observable will notify when all animations have ended.
  50397. */
  50398. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50399. /**
  50400. * This observable will notify when all animations have paused.
  50401. */
  50402. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50403. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50404. this._scene.animationGroups.push(this);
  50405. }
  50406. Object.defineProperty(AnimationGroup.prototype, "from", {
  50407. /**
  50408. * Gets the first frame
  50409. */
  50410. get: function () {
  50411. return this._from;
  50412. },
  50413. enumerable: true,
  50414. configurable: true
  50415. });
  50416. Object.defineProperty(AnimationGroup.prototype, "to", {
  50417. /**
  50418. * Gets the last frame
  50419. */
  50420. get: function () {
  50421. return this._to;
  50422. },
  50423. enumerable: true,
  50424. configurable: true
  50425. });
  50426. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50427. /**
  50428. * Define if the animations are started
  50429. */
  50430. get: function () {
  50431. return this._isStarted;
  50432. },
  50433. enumerable: true,
  50434. configurable: true
  50435. });
  50436. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50437. /**
  50438. * Gets or sets the speed ratio to use for all animations
  50439. */
  50440. get: function () {
  50441. return this._speedRatio;
  50442. },
  50443. /**
  50444. * Gets or sets the speed ratio to use for all animations
  50445. */
  50446. set: function (value) {
  50447. if (this._speedRatio === value) {
  50448. return;
  50449. }
  50450. this._speedRatio = value;
  50451. for (var index = 0; index < this._animatables.length; index++) {
  50452. var animatable = this._animatables[index];
  50453. animatable.speedRatio = this._speedRatio;
  50454. }
  50455. },
  50456. enumerable: true,
  50457. configurable: true
  50458. });
  50459. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50460. /**
  50461. * Gets the targeted animations for this animation group
  50462. */
  50463. get: function () {
  50464. return this._targetedAnimations;
  50465. },
  50466. enumerable: true,
  50467. configurable: true
  50468. });
  50469. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50470. /**
  50471. * returning the list of animatables controlled by this animation group.
  50472. */
  50473. get: function () {
  50474. return this._animatables;
  50475. },
  50476. enumerable: true,
  50477. configurable: true
  50478. });
  50479. /**
  50480. * Add an animation (with its target) in the group
  50481. * @param animation defines the animation we want to add
  50482. * @param target defines the target of the animation
  50483. * @returns the {BABYLON.TargetedAnimation} object
  50484. */
  50485. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50486. var targetedAnimation = {
  50487. animation: animation,
  50488. target: target
  50489. };
  50490. var keys = animation.getKeys();
  50491. if (this._from > keys[0].frame) {
  50492. this._from = keys[0].frame;
  50493. }
  50494. if (this._to < keys[keys.length - 1].frame) {
  50495. this._to = keys[keys.length - 1].frame;
  50496. }
  50497. this._targetedAnimations.push(targetedAnimation);
  50498. return targetedAnimation;
  50499. };
  50500. /**
  50501. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50502. * It can add constant keys at begin or end
  50503. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50504. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50505. */
  50506. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50507. if (beginFrame === void 0) { beginFrame = null; }
  50508. if (endFrame === void 0) { endFrame = null; }
  50509. if (beginFrame == null)
  50510. beginFrame = this._from;
  50511. if (endFrame == null)
  50512. endFrame = this._to;
  50513. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50514. var targetedAnimation = this._targetedAnimations[index];
  50515. var keys = targetedAnimation.animation.getKeys();
  50516. var startKey = keys[0];
  50517. var endKey = keys[keys.length - 1];
  50518. if (startKey.frame > beginFrame) {
  50519. var newKey = {
  50520. frame: beginFrame,
  50521. value: startKey.value,
  50522. inTangent: startKey.inTangent,
  50523. outTangent: startKey.outTangent,
  50524. interpolation: startKey.interpolation
  50525. };
  50526. keys.splice(0, 0, newKey);
  50527. }
  50528. if (endKey.frame < endFrame) {
  50529. var newKey = {
  50530. frame: endFrame,
  50531. value: endKey.value,
  50532. inTangent: endKey.outTangent,
  50533. outTangent: endKey.outTangent,
  50534. interpolation: endKey.interpolation
  50535. };
  50536. keys.push(newKey);
  50537. }
  50538. }
  50539. this._from = beginFrame;
  50540. this._to = endFrame;
  50541. return this;
  50542. };
  50543. /**
  50544. * Start all animations on given targets
  50545. * @param loop defines if animations must loop
  50546. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50547. * @param from defines the from key (optional)
  50548. * @param to defines the to key (optional)
  50549. * @returns the current animation group
  50550. */
  50551. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50552. var _this = this;
  50553. if (loop === void 0) { loop = false; }
  50554. if (speedRatio === void 0) { speedRatio = 1; }
  50555. if (this._isStarted || this._targetedAnimations.length === 0) {
  50556. return this;
  50557. }
  50558. var _loop_1 = function (targetedAnimation) {
  50559. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50560. animatable.onAnimationEnd = function () {
  50561. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50562. _this._checkAnimationGroupEnded(animatable);
  50563. };
  50564. this_1._animatables.push(animatable);
  50565. };
  50566. var this_1 = this;
  50567. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50568. var targetedAnimation = _a[_i];
  50569. _loop_1(targetedAnimation);
  50570. }
  50571. this._speedRatio = speedRatio;
  50572. this._isStarted = true;
  50573. return this;
  50574. };
  50575. /**
  50576. * Pause all animations
  50577. */
  50578. AnimationGroup.prototype.pause = function () {
  50579. if (!this._isStarted) {
  50580. return this;
  50581. }
  50582. for (var index = 0; index < this._animatables.length; index++) {
  50583. var animatable = this._animatables[index];
  50584. animatable.pause();
  50585. }
  50586. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50587. return this;
  50588. };
  50589. /**
  50590. * Play all animations to initial state
  50591. * This function will start() the animations if they were not started or will restart() them if they were paused
  50592. * @param loop defines if animations must loop
  50593. */
  50594. AnimationGroup.prototype.play = function (loop) {
  50595. // only if all animatables are ready and exist
  50596. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50597. if (loop !== undefined) {
  50598. for (var index = 0; index < this._animatables.length; index++) {
  50599. var animatable = this._animatables[index];
  50600. animatable.loopAnimation = loop;
  50601. }
  50602. }
  50603. this.restart();
  50604. }
  50605. else {
  50606. this.stop();
  50607. this.start(loop, this._speedRatio);
  50608. }
  50609. return this;
  50610. };
  50611. /**
  50612. * Reset all animations to initial state
  50613. */
  50614. AnimationGroup.prototype.reset = function () {
  50615. if (!this._isStarted) {
  50616. return this;
  50617. }
  50618. for (var index = 0; index < this._animatables.length; index++) {
  50619. var animatable = this._animatables[index];
  50620. animatable.reset();
  50621. }
  50622. return this;
  50623. };
  50624. /**
  50625. * Restart animations from key 0
  50626. */
  50627. AnimationGroup.prototype.restart = function () {
  50628. if (!this._isStarted) {
  50629. return this;
  50630. }
  50631. for (var index = 0; index < this._animatables.length; index++) {
  50632. var animatable = this._animatables[index];
  50633. animatable.restart();
  50634. }
  50635. return this;
  50636. };
  50637. /**
  50638. * Stop all animations
  50639. */
  50640. AnimationGroup.prototype.stop = function () {
  50641. if (!this._isStarted) {
  50642. return this;
  50643. }
  50644. var list = this._animatables.slice();
  50645. for (var index = 0; index < list.length; index++) {
  50646. list[index].stop();
  50647. }
  50648. this._isStarted = false;
  50649. return this;
  50650. };
  50651. /**
  50652. * Set animation weight for all animatables
  50653. * @param weight defines the weight to use
  50654. * @return the animationGroup
  50655. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50656. */
  50657. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50658. for (var index = 0; index < this._animatables.length; index++) {
  50659. var animatable = this._animatables[index];
  50660. animatable.weight = weight;
  50661. }
  50662. return this;
  50663. };
  50664. /**
  50665. * Synchronize and normalize all animatables with a source animatable
  50666. * @param root defines the root animatable to synchronize with
  50667. * @return the animationGroup
  50668. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50669. */
  50670. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50671. for (var index = 0; index < this._animatables.length; index++) {
  50672. var animatable = this._animatables[index];
  50673. animatable.syncWith(root);
  50674. }
  50675. return this;
  50676. };
  50677. /**
  50678. * Goes to a specific frame in this animation group
  50679. * @param frame the frame number to go to
  50680. * @return the animationGroup
  50681. */
  50682. AnimationGroup.prototype.goToFrame = function (frame) {
  50683. if (!this._isStarted) {
  50684. return this;
  50685. }
  50686. for (var index = 0; index < this._animatables.length; index++) {
  50687. var animatable = this._animatables[index];
  50688. animatable.goToFrame(frame);
  50689. }
  50690. return this;
  50691. };
  50692. /**
  50693. * Dispose all associated resources
  50694. */
  50695. AnimationGroup.prototype.dispose = function () {
  50696. this._targetedAnimations = [];
  50697. this._animatables = [];
  50698. var index = this._scene.animationGroups.indexOf(this);
  50699. if (index > -1) {
  50700. this._scene.animationGroups.splice(index, 1);
  50701. }
  50702. };
  50703. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50704. // animatable should be taken out of the array
  50705. var idx = this._animatables.indexOf(animatable);
  50706. if (idx > -1) {
  50707. this._animatables.splice(idx, 1);
  50708. }
  50709. // all animatables were removed? animation group ended!
  50710. if (this._animatables.length === 0) {
  50711. this._isStarted = false;
  50712. this.onAnimationGroupEndObservable.notifyObservers(this);
  50713. }
  50714. };
  50715. // Statics
  50716. /**
  50717. * Returns a new AnimationGroup object parsed from the source provided.
  50718. * @param parsedAnimationGroup defines the source
  50719. * @param scene defines the scene that will receive the animationGroup
  50720. * @returns a new AnimationGroup
  50721. */
  50722. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  50723. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  50724. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  50725. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  50726. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  50727. var id = targetedAnimation.targetId;
  50728. var targetNode = scene.getNodeByID(id);
  50729. if (targetNode != null)
  50730. animationGroup.addTargetedAnimation(animation, targetNode);
  50731. }
  50732. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  50733. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  50734. return animationGroup;
  50735. };
  50736. /**
  50737. * Returns the string "AnimationGroup"
  50738. * @returns "AnimationGroup"
  50739. */
  50740. AnimationGroup.prototype.getClassName = function () {
  50741. return "AnimationGroup";
  50742. };
  50743. /**
  50744. * Creates a detailled string about the object
  50745. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  50746. * @returns a string representing the object
  50747. */
  50748. AnimationGroup.prototype.toString = function (fullDetails) {
  50749. var ret = "Name: " + this.name;
  50750. ret += ", type: " + this.getClassName();
  50751. if (fullDetails) {
  50752. ret += ", from: " + this._from;
  50753. ret += ", to: " + this._to;
  50754. ret += ", isStarted: " + this._isStarted;
  50755. ret += ", speedRatio: " + this._speedRatio;
  50756. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  50757. ret += ", animatables length: " + this._animatables;
  50758. }
  50759. return ret;
  50760. };
  50761. return AnimationGroup;
  50762. }());
  50763. BABYLON.AnimationGroup = AnimationGroup;
  50764. })(BABYLON || (BABYLON = {}));
  50765. //# sourceMappingURL=babylon.animationGroup.js.map
  50766. var BABYLON;
  50767. (function (BABYLON) {
  50768. // Static values to help the garbage collector
  50769. // Quaternion
  50770. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  50771. // Vector3
  50772. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  50773. // Vector2
  50774. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  50775. // Size
  50776. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  50777. // Color3
  50778. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  50779. /**
  50780. * Defines a runtime animation
  50781. */
  50782. var RuntimeAnimation = /** @class */ (function () {
  50783. /**
  50784. * Create a new RuntimeAnimation object
  50785. * @param target defines the target of the animation
  50786. * @param animation defines the source animation object
  50787. * @param scene defines the hosting scene
  50788. * @param host defines the initiating Animatable
  50789. */
  50790. function RuntimeAnimation(target, animation, scene, host) {
  50791. var _this = this;
  50792. this._events = new Array();
  50793. /**
  50794. * The current frame of the runtime animation
  50795. */
  50796. this._currentFrame = 0;
  50797. /**
  50798. * The original value of the runtime animation
  50799. */
  50800. this._originalValue = new Array();
  50801. /**
  50802. * The offsets cache of the runtime animation
  50803. */
  50804. this._offsetsCache = {};
  50805. /**
  50806. * The high limits cache of the runtime animation
  50807. */
  50808. this._highLimitsCache = {};
  50809. /**
  50810. * Specifies if the runtime animation has been stopped
  50811. */
  50812. this._stopped = false;
  50813. /**
  50814. * The blending factor of the runtime animation
  50815. */
  50816. this._blendingFactor = 0;
  50817. /**
  50818. * The target path of the runtime animation
  50819. */
  50820. this._targetPath = "";
  50821. /**
  50822. * The weight of the runtime animation
  50823. */
  50824. this._weight = 1.0;
  50825. /**
  50826. * The ratio offset of the runtime animation
  50827. */
  50828. this._ratioOffset = 0;
  50829. /**
  50830. * The previous delay of the runtime animation
  50831. */
  50832. this._previousDelay = 0;
  50833. /**
  50834. * The previous ratio of the runtime animation
  50835. */
  50836. this._previousRatio = 0;
  50837. this._animation = animation;
  50838. this._target = target;
  50839. this._scene = scene;
  50840. this._host = host;
  50841. animation._runtimeAnimations.push(this);
  50842. // Cloning events locally
  50843. var events = animation.getEvents();
  50844. if (events && events.length > 0) {
  50845. events.forEach(function (e) {
  50846. _this._events.push(e._clone());
  50847. });
  50848. }
  50849. }
  50850. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50851. /**
  50852. * Gets the current frame of the runtime animation
  50853. */
  50854. get: function () {
  50855. return this._currentFrame;
  50856. },
  50857. enumerable: true,
  50858. configurable: true
  50859. });
  50860. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50861. /**
  50862. * Gets the weight of the runtime animation
  50863. */
  50864. get: function () {
  50865. return this._weight;
  50866. },
  50867. enumerable: true,
  50868. configurable: true
  50869. });
  50870. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50871. /**
  50872. * Gets the current value of the runtime animation
  50873. */
  50874. get: function () {
  50875. return this._currentValue;
  50876. },
  50877. enumerable: true,
  50878. configurable: true
  50879. });
  50880. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50881. /**
  50882. * Gets the target path of the runtime animation
  50883. */
  50884. get: function () {
  50885. return this._targetPath;
  50886. },
  50887. enumerable: true,
  50888. configurable: true
  50889. });
  50890. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50891. /**
  50892. * Gets the actual target of the runtime animation
  50893. */
  50894. get: function () {
  50895. return this._activeTarget;
  50896. },
  50897. enumerable: true,
  50898. configurable: true
  50899. });
  50900. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50901. /**
  50902. * Gets the animation from the runtime animation
  50903. */
  50904. get: function () {
  50905. return this._animation;
  50906. },
  50907. enumerable: true,
  50908. configurable: true
  50909. });
  50910. /**
  50911. * Resets the runtime animation to the beginning
  50912. * @param restoreOriginal defines whether to restore the target property to the original value
  50913. */
  50914. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50915. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50916. if (restoreOriginal) {
  50917. if (this._target instanceof Array) {
  50918. var index = 0;
  50919. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50920. var target = _a[_i];
  50921. if (this._originalValue[index] !== undefined) {
  50922. this._setValue(target, this._originalValue[index], -1);
  50923. }
  50924. index++;
  50925. }
  50926. }
  50927. else {
  50928. if (this._originalValue[0] !== undefined) {
  50929. this._setValue(this._target, this._originalValue[0], -1);
  50930. }
  50931. }
  50932. }
  50933. this._offsetsCache = {};
  50934. this._highLimitsCache = {};
  50935. this._currentFrame = 0;
  50936. this._blendingFactor = 0;
  50937. this._originalValue = new Array();
  50938. // Events
  50939. for (var index = 0; index < this._events.length; index++) {
  50940. this._events[index].isDone = false;
  50941. }
  50942. };
  50943. /**
  50944. * Specifies if the runtime animation is stopped
  50945. * @returns Boolean specifying if the runtime animation is stopped
  50946. */
  50947. RuntimeAnimation.prototype.isStopped = function () {
  50948. return this._stopped;
  50949. };
  50950. /**
  50951. * Disposes of the runtime animation
  50952. */
  50953. RuntimeAnimation.prototype.dispose = function () {
  50954. var index = this._animation.runtimeAnimations.indexOf(this);
  50955. if (index > -1) {
  50956. this._animation.runtimeAnimations.splice(index, 1);
  50957. }
  50958. };
  50959. /**
  50960. * Interpolates the animation from the current frame
  50961. * @param currentFrame The frame to interpolate the animation to
  50962. * @param repeatCount The number of times that the animation should loop
  50963. * @param loopMode The type of looping mode to use
  50964. * @param offsetValue Animation offset value
  50965. * @param highLimitValue The high limit value
  50966. * @returns The interpolated value
  50967. */
  50968. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50969. this._currentFrame = currentFrame;
  50970. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50971. this._workValue = BABYLON.Matrix.Zero();
  50972. }
  50973. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50974. };
  50975. /**
  50976. * Apply the interpolated value to the target
  50977. * @param currentValue defines the value computed by the animation
  50978. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50979. */
  50980. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50981. if (weight === void 0) { weight = 1.0; }
  50982. if (this._target instanceof Array) {
  50983. var index = 0;
  50984. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50985. var target = _a[_i];
  50986. this._setValue(target, currentValue, weight, index);
  50987. index++;
  50988. }
  50989. }
  50990. else {
  50991. this._setValue(this._target, currentValue, weight);
  50992. }
  50993. };
  50994. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50995. if (targetIndex === void 0) { targetIndex = 0; }
  50996. // Set value
  50997. var path;
  50998. var destination;
  50999. var targetPropertyPath = this._animation.targetPropertyPath;
  51000. if (targetPropertyPath.length > 1) {
  51001. var property = target[targetPropertyPath[0]];
  51002. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51003. property = property[targetPropertyPath[index]];
  51004. }
  51005. path = targetPropertyPath[targetPropertyPath.length - 1];
  51006. destination = property;
  51007. }
  51008. else {
  51009. path = targetPropertyPath[0];
  51010. destination = target;
  51011. }
  51012. this._targetPath = path;
  51013. this._activeTarget = destination;
  51014. this._weight = weight;
  51015. if (this._originalValue[targetIndex] === undefined) {
  51016. var originalValue = void 0;
  51017. if (destination.getRestPose && path === "_matrix") { // For bones
  51018. originalValue = destination.getRestPose();
  51019. }
  51020. else {
  51021. originalValue = destination[path];
  51022. }
  51023. if (originalValue && originalValue.clone) {
  51024. this._originalValue[targetIndex] = originalValue.clone();
  51025. }
  51026. else {
  51027. this._originalValue[targetIndex] = originalValue;
  51028. }
  51029. }
  51030. // Blending
  51031. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51032. if (enableBlending && this._blendingFactor <= 1.0) {
  51033. if (!this._originalBlendValue) {
  51034. var originalValue = destination[path];
  51035. if (originalValue.clone) {
  51036. this._originalBlendValue = originalValue.clone();
  51037. }
  51038. else {
  51039. this._originalBlendValue = originalValue;
  51040. }
  51041. }
  51042. if (this._originalBlendValue.m) { // Matrix
  51043. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51044. if (this._currentValue) {
  51045. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51046. }
  51047. else {
  51048. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51049. }
  51050. }
  51051. else {
  51052. if (this._currentValue) {
  51053. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51054. }
  51055. else {
  51056. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51057. }
  51058. }
  51059. }
  51060. else {
  51061. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51062. }
  51063. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51064. this._blendingFactor += blendingSpeed;
  51065. }
  51066. else {
  51067. this._currentValue = currentValue;
  51068. }
  51069. if (weight !== -1.0) {
  51070. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51071. }
  51072. else {
  51073. destination[path] = this._currentValue;
  51074. }
  51075. if (target.markAsDirty) {
  51076. target.markAsDirty(this._animation.targetProperty);
  51077. }
  51078. };
  51079. /**
  51080. * Gets the loop pmode of the runtime animation
  51081. * @returns Loop Mode
  51082. */
  51083. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51084. if (this._target && this._target.animationPropertiesOverride) {
  51085. return this._target.animationPropertiesOverride.loopMode;
  51086. }
  51087. return this._animation.loopMode;
  51088. };
  51089. /**
  51090. * Move the current animation to a given frame
  51091. * @param frame defines the frame to move to
  51092. */
  51093. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51094. var keys = this._animation.getKeys();
  51095. if (frame < keys[0].frame) {
  51096. frame = keys[0].frame;
  51097. }
  51098. else if (frame > keys[keys.length - 1].frame) {
  51099. frame = keys[keys.length - 1].frame;
  51100. }
  51101. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51102. this.setValue(currentValue, -1);
  51103. };
  51104. /**
  51105. * @hidden Internal use only
  51106. */
  51107. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51108. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51109. this._ratioOffset = this._previousRatio - newRatio;
  51110. };
  51111. /**
  51112. * Execute the current animation
  51113. * @param delay defines the delay to add to the current frame
  51114. * @param from defines the lower bound of the animation range
  51115. * @param to defines the upper bound of the animation range
  51116. * @param loop defines if the current animation must loop
  51117. * @param speedRatio defines the current speed ratio
  51118. * @param weight defines the weight of the animation (default is -1 so no weight)
  51119. * @returns a boolean indicating if the animation is running
  51120. */
  51121. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51122. if (weight === void 0) { weight = -1.0; }
  51123. var targetPropertyPath = this._animation.targetPropertyPath;
  51124. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51125. this._stopped = true;
  51126. return false;
  51127. }
  51128. var returnValue = true;
  51129. var keys = this._animation.getKeys();
  51130. // Adding a start key at frame 0 if missing
  51131. if (keys[0].frame !== 0) {
  51132. var newKey = { frame: 0, value: keys[0].value };
  51133. keys.splice(0, 0, newKey);
  51134. }
  51135. // Adding a duplicate key when there is only one key at frame zero
  51136. else if (keys.length === 1) {
  51137. var newKey = { frame: 0.001, value: keys[0].value };
  51138. keys.push(newKey);
  51139. }
  51140. // Check limits
  51141. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51142. from = keys[0].frame;
  51143. }
  51144. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51145. to = keys[keys.length - 1].frame;
  51146. }
  51147. //to and from cannot be the same key
  51148. if (from === to) {
  51149. if (from > keys[0].frame) {
  51150. from--;
  51151. }
  51152. else if (to < keys[keys.length - 1].frame) {
  51153. to++;
  51154. }
  51155. }
  51156. // Compute ratio
  51157. var range = to - from;
  51158. var offsetValue;
  51159. // ratio represents the frame delta between from and to
  51160. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51161. var highLimitValue = 0;
  51162. this._previousDelay = delay;
  51163. this._previousRatio = ratio;
  51164. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51165. returnValue = false;
  51166. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51167. }
  51168. else {
  51169. // Get max value if required
  51170. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51171. var keyOffset = to.toString() + from.toString();
  51172. if (!this._offsetsCache[keyOffset]) {
  51173. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51174. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51175. switch (this._animation.dataType) {
  51176. // Float
  51177. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51178. this._offsetsCache[keyOffset] = toValue - fromValue;
  51179. break;
  51180. // Quaternion
  51181. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51182. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51183. break;
  51184. // Vector3
  51185. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51186. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51187. // Vector2
  51188. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51189. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51190. // Size
  51191. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51192. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51193. // Color3
  51194. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51195. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51196. default:
  51197. break;
  51198. }
  51199. this._highLimitsCache[keyOffset] = toValue;
  51200. }
  51201. highLimitValue = this._highLimitsCache[keyOffset];
  51202. offsetValue = this._offsetsCache[keyOffset];
  51203. }
  51204. }
  51205. if (offsetValue === undefined) {
  51206. switch (this._animation.dataType) {
  51207. // Float
  51208. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51209. offsetValue = 0;
  51210. break;
  51211. // Quaternion
  51212. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51213. offsetValue = _staticOffsetValueQuaternion;
  51214. break;
  51215. // Vector3
  51216. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51217. offsetValue = _staticOffsetValueVector3;
  51218. break;
  51219. // Vector2
  51220. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51221. offsetValue = _staticOffsetValueVector2;
  51222. break;
  51223. // Size
  51224. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51225. offsetValue = _staticOffsetValueSize;
  51226. break;
  51227. // Color3
  51228. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51229. offsetValue = _staticOffsetValueColor3;
  51230. }
  51231. }
  51232. // Compute value
  51233. var repeatCount = (ratio / range) >> 0;
  51234. var currentFrame = returnValue ? from + ratio % range : to;
  51235. // Need to normalize?
  51236. if (this._host && this._host.syncRoot) {
  51237. var syncRoot = this._host.syncRoot;
  51238. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51239. currentFrame = from + (to - from) * hostNormalizedFrame;
  51240. }
  51241. // Reset events if looping
  51242. var events = this._events;
  51243. if (range > 0 && this.currentFrame > currentFrame ||
  51244. range < 0 && this.currentFrame < currentFrame) {
  51245. // Need to reset animation events
  51246. for (var index = 0; index < events.length; index++) {
  51247. if (!events[index].onlyOnce) {
  51248. // reset event, the animation is looping
  51249. events[index].isDone = false;
  51250. }
  51251. }
  51252. }
  51253. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51254. // Set value
  51255. this.setValue(currentValue, weight);
  51256. // Check events
  51257. for (var index = 0; index < events.length; index++) {
  51258. // Make sure current frame has passed event frame and that event frame is within the current range
  51259. // Also, handle both forward and reverse animations
  51260. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51261. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51262. var event = events[index];
  51263. if (!event.isDone) {
  51264. // If event should be done only once, remove it.
  51265. if (event.onlyOnce) {
  51266. events.splice(index, 1);
  51267. index--;
  51268. }
  51269. event.isDone = true;
  51270. event.action(currentFrame);
  51271. } // Don't do anything if the event has already be done.
  51272. }
  51273. }
  51274. if (!returnValue) {
  51275. this._stopped = true;
  51276. }
  51277. return returnValue;
  51278. };
  51279. return RuntimeAnimation;
  51280. }());
  51281. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51282. })(BABYLON || (BABYLON = {}));
  51283. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51284. var BABYLON;
  51285. (function (BABYLON) {
  51286. /**
  51287. * Class used to store an actual running animation
  51288. */
  51289. var Animatable = /** @class */ (function () {
  51290. /**
  51291. * Creates a new Animatable
  51292. * @param scene defines the hosting scene
  51293. * @param target defines the target object
  51294. * @param fromFrame defines the starting frame number (default is 0)
  51295. * @param toFrame defines the ending frame number (default is 100)
  51296. * @param loopAnimation defines if the animation must loop (default is false)
  51297. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51298. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51299. * @param animations defines a group of animation to add to the new Animatable
  51300. */
  51301. function Animatable(scene,
  51302. /** defines the target object */
  51303. target,
  51304. /** defines the starting frame number (default is 0) */
  51305. fromFrame,
  51306. /** defines the ending frame number (default is 100) */
  51307. toFrame,
  51308. /** defines if the animation must loop (default is false) */
  51309. loopAnimation, speedRatio,
  51310. /** defines a callback to call when animation ends if it is not looping */
  51311. onAnimationEnd, animations) {
  51312. if (fromFrame === void 0) { fromFrame = 0; }
  51313. if (toFrame === void 0) { toFrame = 100; }
  51314. if (loopAnimation === void 0) { loopAnimation = false; }
  51315. if (speedRatio === void 0) { speedRatio = 1.0; }
  51316. this.target = target;
  51317. this.fromFrame = fromFrame;
  51318. this.toFrame = toFrame;
  51319. this.loopAnimation = loopAnimation;
  51320. this.onAnimationEnd = onAnimationEnd;
  51321. this._localDelayOffset = null;
  51322. this._pausedDelay = null;
  51323. this._runtimeAnimations = new Array();
  51324. this._paused = false;
  51325. this._speedRatio = 1;
  51326. this._weight = -1.0;
  51327. /**
  51328. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51329. * This will only apply for non looping animation (default is true)
  51330. */
  51331. this.disposeOnEnd = true;
  51332. /**
  51333. * Gets a boolean indicating if the animation has started
  51334. */
  51335. this.animationStarted = false;
  51336. /**
  51337. * Observer raised when the animation ends
  51338. */
  51339. this.onAnimationEndObservable = new BABYLON.Observable();
  51340. this._scene = scene;
  51341. if (animations) {
  51342. this.appendAnimations(target, animations);
  51343. }
  51344. this._speedRatio = speedRatio;
  51345. scene._activeAnimatables.push(this);
  51346. }
  51347. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51348. /**
  51349. * Gets the root Animatable used to synchronize and normalize animations
  51350. */
  51351. get: function () {
  51352. return this._syncRoot;
  51353. },
  51354. enumerable: true,
  51355. configurable: true
  51356. });
  51357. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51358. /**
  51359. * Gets the current frame of the first RuntimeAnimation
  51360. * Used to synchronize Animatables
  51361. */
  51362. get: function () {
  51363. if (this._runtimeAnimations.length === 0) {
  51364. return 0;
  51365. }
  51366. return this._runtimeAnimations[0].currentFrame;
  51367. },
  51368. enumerable: true,
  51369. configurable: true
  51370. });
  51371. Object.defineProperty(Animatable.prototype, "weight", {
  51372. /**
  51373. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51374. */
  51375. get: function () {
  51376. return this._weight;
  51377. },
  51378. set: function (value) {
  51379. if (value === -1) { // -1 is ok and means no weight
  51380. this._weight = -1;
  51381. return;
  51382. }
  51383. // Else weight must be in [0, 1] range
  51384. this._weight = Math.min(Math.max(value, 0), 1.0);
  51385. },
  51386. enumerable: true,
  51387. configurable: true
  51388. });
  51389. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51390. /**
  51391. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51392. */
  51393. get: function () {
  51394. return this._speedRatio;
  51395. },
  51396. set: function (value) {
  51397. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51398. var animation = this._runtimeAnimations[index];
  51399. animation._prepareForSpeedRatioChange(value);
  51400. }
  51401. this._speedRatio = value;
  51402. },
  51403. enumerable: true,
  51404. configurable: true
  51405. });
  51406. // Methods
  51407. /**
  51408. * Synchronize and normalize current Animatable with a source Animatable
  51409. * This is useful when using animation weights and when animations are not of the same length
  51410. * @param root defines the root Animatable to synchronize with
  51411. * @returns the current Animatable
  51412. */
  51413. Animatable.prototype.syncWith = function (root) {
  51414. this._syncRoot = root;
  51415. if (root) {
  51416. // Make sure this animatable will animate after the root
  51417. var index = this._scene._activeAnimatables.indexOf(this);
  51418. if (index > -1) {
  51419. this._scene._activeAnimatables.splice(index, 1);
  51420. this._scene._activeAnimatables.push(this);
  51421. }
  51422. }
  51423. return this;
  51424. };
  51425. /**
  51426. * Gets the list of runtime animations
  51427. * @returns an array of RuntimeAnimation
  51428. */
  51429. Animatable.prototype.getAnimations = function () {
  51430. return this._runtimeAnimations;
  51431. };
  51432. /**
  51433. * Adds more animations to the current animatable
  51434. * @param target defines the target of the animations
  51435. * @param animations defines the new animations to add
  51436. */
  51437. Animatable.prototype.appendAnimations = function (target, animations) {
  51438. for (var index = 0; index < animations.length; index++) {
  51439. var animation = animations[index];
  51440. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51441. }
  51442. };
  51443. /**
  51444. * Gets the source animation for a specific property
  51445. * @param property defines the propertyu to look for
  51446. * @returns null or the source animation for the given property
  51447. */
  51448. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51449. var runtimeAnimations = this._runtimeAnimations;
  51450. for (var index = 0; index < runtimeAnimations.length; index++) {
  51451. if (runtimeAnimations[index].animation.targetProperty === property) {
  51452. return runtimeAnimations[index].animation;
  51453. }
  51454. }
  51455. return null;
  51456. };
  51457. /**
  51458. * Gets the runtime animation for a specific property
  51459. * @param property defines the propertyu to look for
  51460. * @returns null or the runtime animation for the given property
  51461. */
  51462. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51463. var runtimeAnimations = this._runtimeAnimations;
  51464. for (var index = 0; index < runtimeAnimations.length; index++) {
  51465. if (runtimeAnimations[index].animation.targetProperty === property) {
  51466. return runtimeAnimations[index];
  51467. }
  51468. }
  51469. return null;
  51470. };
  51471. /**
  51472. * Resets the animatable to its original state
  51473. */
  51474. Animatable.prototype.reset = function () {
  51475. var runtimeAnimations = this._runtimeAnimations;
  51476. for (var index = 0; index < runtimeAnimations.length; index++) {
  51477. runtimeAnimations[index].reset(true);
  51478. }
  51479. this._localDelayOffset = null;
  51480. this._pausedDelay = null;
  51481. };
  51482. /**
  51483. * Allows the animatable to blend with current running animations
  51484. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51485. * @param blendingSpeed defines the blending speed to use
  51486. */
  51487. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51488. var runtimeAnimations = this._runtimeAnimations;
  51489. for (var index = 0; index < runtimeAnimations.length; index++) {
  51490. runtimeAnimations[index].animation.enableBlending = true;
  51491. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51492. }
  51493. };
  51494. /**
  51495. * Disable animation blending
  51496. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51497. */
  51498. Animatable.prototype.disableBlending = function () {
  51499. var runtimeAnimations = this._runtimeAnimations;
  51500. for (var index = 0; index < runtimeAnimations.length; index++) {
  51501. runtimeAnimations[index].animation.enableBlending = false;
  51502. }
  51503. };
  51504. /**
  51505. * Jump directly to a given frame
  51506. * @param frame defines the frame to jump to
  51507. */
  51508. Animatable.prototype.goToFrame = function (frame) {
  51509. var runtimeAnimations = this._runtimeAnimations;
  51510. if (runtimeAnimations[0]) {
  51511. var fps = runtimeAnimations[0].animation.framePerSecond;
  51512. var currentFrame = runtimeAnimations[0].currentFrame;
  51513. var adjustTime = frame - currentFrame;
  51514. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51515. if (this._localDelayOffset === null) {
  51516. this._localDelayOffset = 0;
  51517. }
  51518. this._localDelayOffset -= delay;
  51519. }
  51520. for (var index = 0; index < runtimeAnimations.length; index++) {
  51521. runtimeAnimations[index].goToFrame(frame);
  51522. }
  51523. };
  51524. /**
  51525. * Pause the animation
  51526. */
  51527. Animatable.prototype.pause = function () {
  51528. if (this._paused) {
  51529. return;
  51530. }
  51531. this._paused = true;
  51532. };
  51533. /**
  51534. * Restart the animation
  51535. */
  51536. Animatable.prototype.restart = function () {
  51537. this._paused = false;
  51538. };
  51539. Animatable.prototype._raiseOnAnimationEnd = function () {
  51540. if (this.onAnimationEnd) {
  51541. this.onAnimationEnd();
  51542. }
  51543. this.onAnimationEndObservable.notifyObservers(this);
  51544. };
  51545. /**
  51546. * Stop and delete the current animation
  51547. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51548. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  51549. */
  51550. Animatable.prototype.stop = function (animationName, targetMask) {
  51551. if (animationName || targetMask) {
  51552. var idx = this._scene._activeAnimatables.indexOf(this);
  51553. if (idx > -1) {
  51554. var runtimeAnimations = this._runtimeAnimations;
  51555. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51556. var runtimeAnimation = runtimeAnimations[index];
  51557. if (animationName && runtimeAnimation.animation.name != animationName) {
  51558. continue;
  51559. }
  51560. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51561. continue;
  51562. }
  51563. runtimeAnimation.dispose();
  51564. runtimeAnimations.splice(index, 1);
  51565. }
  51566. if (runtimeAnimations.length == 0) {
  51567. this._scene._activeAnimatables.splice(idx, 1);
  51568. this._raiseOnAnimationEnd();
  51569. }
  51570. }
  51571. }
  51572. else {
  51573. var index = this._scene._activeAnimatables.indexOf(this);
  51574. if (index > -1) {
  51575. this._scene._activeAnimatables.splice(index, 1);
  51576. var runtimeAnimations = this._runtimeAnimations;
  51577. for (var index = 0; index < runtimeAnimations.length; index++) {
  51578. runtimeAnimations[index].dispose();
  51579. }
  51580. this._raiseOnAnimationEnd();
  51581. }
  51582. }
  51583. };
  51584. /**
  51585. * Wait asynchronously for the animation to end
  51586. * @returns a promise which will be fullfilled when the animation ends
  51587. */
  51588. Animatable.prototype.waitAsync = function () {
  51589. var _this = this;
  51590. return new Promise(function (resolve, reject) {
  51591. _this.onAnimationEndObservable.add(function () {
  51592. resolve(_this);
  51593. }, undefined, undefined, _this, true);
  51594. });
  51595. };
  51596. /** @hidden */
  51597. Animatable.prototype._animate = function (delay) {
  51598. if (this._paused) {
  51599. this.animationStarted = false;
  51600. if (this._pausedDelay === null) {
  51601. this._pausedDelay = delay;
  51602. }
  51603. return true;
  51604. }
  51605. if (this._localDelayOffset === null) {
  51606. this._localDelayOffset = delay;
  51607. this._pausedDelay = null;
  51608. }
  51609. else if (this._pausedDelay !== null) {
  51610. this._localDelayOffset += delay - this._pausedDelay;
  51611. this._pausedDelay = null;
  51612. }
  51613. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51614. return true;
  51615. }
  51616. // Animating
  51617. var running = false;
  51618. var runtimeAnimations = this._runtimeAnimations;
  51619. var index;
  51620. for (index = 0; index < runtimeAnimations.length; index++) {
  51621. var animation = runtimeAnimations[index];
  51622. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51623. running = running || isRunning;
  51624. }
  51625. this.animationStarted = running;
  51626. if (!running) {
  51627. if (this.disposeOnEnd) {
  51628. // Remove from active animatables
  51629. index = this._scene._activeAnimatables.indexOf(this);
  51630. this._scene._activeAnimatables.splice(index, 1);
  51631. // Dispose all runtime animations
  51632. for (index = 0; index < runtimeAnimations.length; index++) {
  51633. runtimeAnimations[index].dispose();
  51634. }
  51635. }
  51636. this._raiseOnAnimationEnd();
  51637. if (this.disposeOnEnd) {
  51638. this.onAnimationEnd = null;
  51639. this.onAnimationEndObservable.clear();
  51640. }
  51641. }
  51642. return running;
  51643. };
  51644. return Animatable;
  51645. }());
  51646. BABYLON.Animatable = Animatable;
  51647. })(BABYLON || (BABYLON = {}));
  51648. //# sourceMappingURL=babylon.animatable.js.map
  51649. var BABYLON;
  51650. (function (BABYLON) {
  51651. var EasingFunction = /** @class */ (function () {
  51652. function EasingFunction() {
  51653. // Properties
  51654. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51655. }
  51656. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51657. get: function () {
  51658. return EasingFunction._EASINGMODE_EASEIN;
  51659. },
  51660. enumerable: true,
  51661. configurable: true
  51662. });
  51663. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51664. get: function () {
  51665. return EasingFunction._EASINGMODE_EASEOUT;
  51666. },
  51667. enumerable: true,
  51668. configurable: true
  51669. });
  51670. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51671. get: function () {
  51672. return EasingFunction._EASINGMODE_EASEINOUT;
  51673. },
  51674. enumerable: true,
  51675. configurable: true
  51676. });
  51677. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51678. var n = Math.min(Math.max(easingMode, 0), 2);
  51679. this._easingMode = n;
  51680. };
  51681. EasingFunction.prototype.getEasingMode = function () {
  51682. return this._easingMode;
  51683. };
  51684. EasingFunction.prototype.easeInCore = function (gradient) {
  51685. throw new Error('You must implement this method');
  51686. };
  51687. EasingFunction.prototype.ease = function (gradient) {
  51688. switch (this._easingMode) {
  51689. case EasingFunction.EASINGMODE_EASEIN:
  51690. return this.easeInCore(gradient);
  51691. case EasingFunction.EASINGMODE_EASEOUT:
  51692. return (1 - this.easeInCore(1 - gradient));
  51693. }
  51694. if (gradient >= 0.5) {
  51695. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51696. }
  51697. return (this.easeInCore(gradient * 2) * 0.5);
  51698. };
  51699. //Statics
  51700. EasingFunction._EASINGMODE_EASEIN = 0;
  51701. EasingFunction._EASINGMODE_EASEOUT = 1;
  51702. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51703. return EasingFunction;
  51704. }());
  51705. BABYLON.EasingFunction = EasingFunction;
  51706. var CircleEase = /** @class */ (function (_super) {
  51707. __extends(CircleEase, _super);
  51708. function CircleEase() {
  51709. return _super !== null && _super.apply(this, arguments) || this;
  51710. }
  51711. CircleEase.prototype.easeInCore = function (gradient) {
  51712. gradient = Math.max(0, Math.min(1, gradient));
  51713. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51714. };
  51715. return CircleEase;
  51716. }(EasingFunction));
  51717. BABYLON.CircleEase = CircleEase;
  51718. var BackEase = /** @class */ (function (_super) {
  51719. __extends(BackEase, _super);
  51720. function BackEase(amplitude) {
  51721. if (amplitude === void 0) { amplitude = 1; }
  51722. var _this = _super.call(this) || this;
  51723. _this.amplitude = amplitude;
  51724. return _this;
  51725. }
  51726. BackEase.prototype.easeInCore = function (gradient) {
  51727. var num = Math.max(0, this.amplitude);
  51728. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51729. };
  51730. return BackEase;
  51731. }(EasingFunction));
  51732. BABYLON.BackEase = BackEase;
  51733. var BounceEase = /** @class */ (function (_super) {
  51734. __extends(BounceEase, _super);
  51735. function BounceEase(bounces, bounciness) {
  51736. if (bounces === void 0) { bounces = 3; }
  51737. if (bounciness === void 0) { bounciness = 2; }
  51738. var _this = _super.call(this) || this;
  51739. _this.bounces = bounces;
  51740. _this.bounciness = bounciness;
  51741. return _this;
  51742. }
  51743. BounceEase.prototype.easeInCore = function (gradient) {
  51744. var y = Math.max(0.0, this.bounces);
  51745. var bounciness = this.bounciness;
  51746. if (bounciness <= 1.0) {
  51747. bounciness = 1.001;
  51748. }
  51749. var num9 = Math.pow(bounciness, y);
  51750. var num5 = 1.0 - bounciness;
  51751. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51752. var num15 = gradient * num4;
  51753. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51754. var num3 = Math.floor(num65);
  51755. var num13 = num3 + 1.0;
  51756. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51757. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51758. var num7 = (num8 + num12) * 0.5;
  51759. var num6 = gradient - num7;
  51760. var num2 = num7 - num8;
  51761. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51762. };
  51763. return BounceEase;
  51764. }(EasingFunction));
  51765. BABYLON.BounceEase = BounceEase;
  51766. var CubicEase = /** @class */ (function (_super) {
  51767. __extends(CubicEase, _super);
  51768. function CubicEase() {
  51769. return _super !== null && _super.apply(this, arguments) || this;
  51770. }
  51771. CubicEase.prototype.easeInCore = function (gradient) {
  51772. return (gradient * gradient * gradient);
  51773. };
  51774. return CubicEase;
  51775. }(EasingFunction));
  51776. BABYLON.CubicEase = CubicEase;
  51777. var ElasticEase = /** @class */ (function (_super) {
  51778. __extends(ElasticEase, _super);
  51779. function ElasticEase(oscillations, springiness) {
  51780. if (oscillations === void 0) { oscillations = 3; }
  51781. if (springiness === void 0) { springiness = 3; }
  51782. var _this = _super.call(this) || this;
  51783. _this.oscillations = oscillations;
  51784. _this.springiness = springiness;
  51785. return _this;
  51786. }
  51787. ElasticEase.prototype.easeInCore = function (gradient) {
  51788. var num2;
  51789. var num3 = Math.max(0.0, this.oscillations);
  51790. var num = Math.max(0.0, this.springiness);
  51791. if (num == 0) {
  51792. num2 = gradient;
  51793. }
  51794. else {
  51795. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51796. }
  51797. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51798. };
  51799. return ElasticEase;
  51800. }(EasingFunction));
  51801. BABYLON.ElasticEase = ElasticEase;
  51802. var ExponentialEase = /** @class */ (function (_super) {
  51803. __extends(ExponentialEase, _super);
  51804. function ExponentialEase(exponent) {
  51805. if (exponent === void 0) { exponent = 2; }
  51806. var _this = _super.call(this) || this;
  51807. _this.exponent = exponent;
  51808. return _this;
  51809. }
  51810. ExponentialEase.prototype.easeInCore = function (gradient) {
  51811. if (this.exponent <= 0) {
  51812. return gradient;
  51813. }
  51814. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51815. };
  51816. return ExponentialEase;
  51817. }(EasingFunction));
  51818. BABYLON.ExponentialEase = ExponentialEase;
  51819. var PowerEase = /** @class */ (function (_super) {
  51820. __extends(PowerEase, _super);
  51821. function PowerEase(power) {
  51822. if (power === void 0) { power = 2; }
  51823. var _this = _super.call(this) || this;
  51824. _this.power = power;
  51825. return _this;
  51826. }
  51827. PowerEase.prototype.easeInCore = function (gradient) {
  51828. var y = Math.max(0.0, this.power);
  51829. return Math.pow(gradient, y);
  51830. };
  51831. return PowerEase;
  51832. }(EasingFunction));
  51833. BABYLON.PowerEase = PowerEase;
  51834. var QuadraticEase = /** @class */ (function (_super) {
  51835. __extends(QuadraticEase, _super);
  51836. function QuadraticEase() {
  51837. return _super !== null && _super.apply(this, arguments) || this;
  51838. }
  51839. QuadraticEase.prototype.easeInCore = function (gradient) {
  51840. return (gradient * gradient);
  51841. };
  51842. return QuadraticEase;
  51843. }(EasingFunction));
  51844. BABYLON.QuadraticEase = QuadraticEase;
  51845. var QuarticEase = /** @class */ (function (_super) {
  51846. __extends(QuarticEase, _super);
  51847. function QuarticEase() {
  51848. return _super !== null && _super.apply(this, arguments) || this;
  51849. }
  51850. QuarticEase.prototype.easeInCore = function (gradient) {
  51851. return (gradient * gradient * gradient * gradient);
  51852. };
  51853. return QuarticEase;
  51854. }(EasingFunction));
  51855. BABYLON.QuarticEase = QuarticEase;
  51856. var QuinticEase = /** @class */ (function (_super) {
  51857. __extends(QuinticEase, _super);
  51858. function QuinticEase() {
  51859. return _super !== null && _super.apply(this, arguments) || this;
  51860. }
  51861. QuinticEase.prototype.easeInCore = function (gradient) {
  51862. return (gradient * gradient * gradient * gradient * gradient);
  51863. };
  51864. return QuinticEase;
  51865. }(EasingFunction));
  51866. BABYLON.QuinticEase = QuinticEase;
  51867. var SineEase = /** @class */ (function (_super) {
  51868. __extends(SineEase, _super);
  51869. function SineEase() {
  51870. return _super !== null && _super.apply(this, arguments) || this;
  51871. }
  51872. SineEase.prototype.easeInCore = function (gradient) {
  51873. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51874. };
  51875. return SineEase;
  51876. }(EasingFunction));
  51877. BABYLON.SineEase = SineEase;
  51878. var BezierCurveEase = /** @class */ (function (_super) {
  51879. __extends(BezierCurveEase, _super);
  51880. function BezierCurveEase(x1, y1, x2, y2) {
  51881. if (x1 === void 0) { x1 = 0; }
  51882. if (y1 === void 0) { y1 = 0; }
  51883. if (x2 === void 0) { x2 = 1; }
  51884. if (y2 === void 0) { y2 = 1; }
  51885. var _this = _super.call(this) || this;
  51886. _this.x1 = x1;
  51887. _this.y1 = y1;
  51888. _this.x2 = x2;
  51889. _this.y2 = y2;
  51890. return _this;
  51891. }
  51892. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51893. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51894. };
  51895. return BezierCurveEase;
  51896. }(EasingFunction));
  51897. BABYLON.BezierCurveEase = BezierCurveEase;
  51898. })(BABYLON || (BABYLON = {}));
  51899. //# sourceMappingURL=babylon.easing.js.map
  51900. var BABYLON;
  51901. (function (BABYLON) {
  51902. /**
  51903. * A Condition applied to an Action
  51904. */
  51905. var Condition = /** @class */ (function () {
  51906. /**
  51907. * Creates a new Condition
  51908. * @param actionManager the manager of the action the condition is applied to
  51909. */
  51910. function Condition(actionManager) {
  51911. this._actionManager = actionManager;
  51912. }
  51913. /**
  51914. * Check if the current condition is valid
  51915. * @returns a boolean
  51916. */
  51917. Condition.prototype.isValid = function () {
  51918. return true;
  51919. };
  51920. /**
  51921. * Internal only
  51922. * @hidden
  51923. */
  51924. Condition.prototype._getProperty = function (propertyPath) {
  51925. return this._actionManager._getProperty(propertyPath);
  51926. };
  51927. /**
  51928. * Internal only
  51929. * @hidden
  51930. */
  51931. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51932. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51933. };
  51934. /**
  51935. * Serialize placeholder for child classes
  51936. * @returns the serialized object
  51937. */
  51938. Condition.prototype.serialize = function () {
  51939. };
  51940. /**
  51941. * Internal only
  51942. * @hidden
  51943. */
  51944. Condition.prototype._serialize = function (serializedCondition) {
  51945. return {
  51946. type: 2,
  51947. children: [],
  51948. name: serializedCondition.name,
  51949. properties: serializedCondition.properties
  51950. };
  51951. };
  51952. return Condition;
  51953. }());
  51954. BABYLON.Condition = Condition;
  51955. /**
  51956. * Defines specific conditional operators as extensions of Condition
  51957. */
  51958. var ValueCondition = /** @class */ (function (_super) {
  51959. __extends(ValueCondition, _super);
  51960. /**
  51961. * Creates a new ValueCondition
  51962. * @param actionManager manager for the action the condition applies to
  51963. * @param target for the action
  51964. * @param propertyPath path to specify the property of the target the conditional operator uses
  51965. * @param value the value compared by the conditional operator against the current value of the property
  51966. * @param operator the conditional operator, default ValueCondition.IsEqual
  51967. */
  51968. function ValueCondition(actionManager, target,
  51969. /** path to specify the property of the target the conditional operator uses */
  51970. propertyPath,
  51971. /** the value compared by the conditional operator against the current value of the property */
  51972. value,
  51973. /** the conditional operator, default ValueCondition.IsEqual */
  51974. operator) {
  51975. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51976. var _this = _super.call(this, actionManager) || this;
  51977. _this.propertyPath = propertyPath;
  51978. _this.value = value;
  51979. _this.operator = operator;
  51980. _this._target = target;
  51981. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51982. _this._property = _this._getProperty(_this.propertyPath);
  51983. return _this;
  51984. }
  51985. Object.defineProperty(ValueCondition, "IsEqual", {
  51986. /**
  51987. * returns the number for IsEqual
  51988. */
  51989. get: function () {
  51990. return ValueCondition._IsEqual;
  51991. },
  51992. enumerable: true,
  51993. configurable: true
  51994. });
  51995. Object.defineProperty(ValueCondition, "IsDifferent", {
  51996. /**
  51997. * Returns the number for IsDifferent
  51998. */
  51999. get: function () {
  52000. return ValueCondition._IsDifferent;
  52001. },
  52002. enumerable: true,
  52003. configurable: true
  52004. });
  52005. Object.defineProperty(ValueCondition, "IsGreater", {
  52006. /**
  52007. * Returns the number for IsGreater
  52008. */
  52009. get: function () {
  52010. return ValueCondition._IsGreater;
  52011. },
  52012. enumerable: true,
  52013. configurable: true
  52014. });
  52015. Object.defineProperty(ValueCondition, "IsLesser", {
  52016. /**
  52017. * Returns the number for IsLesser
  52018. */
  52019. get: function () {
  52020. return ValueCondition._IsLesser;
  52021. },
  52022. enumerable: true,
  52023. configurable: true
  52024. });
  52025. /**
  52026. * Compares the given value with the property value for the specified conditional operator
  52027. * @returns the result of the comparison
  52028. */
  52029. ValueCondition.prototype.isValid = function () {
  52030. switch (this.operator) {
  52031. case ValueCondition.IsGreater:
  52032. return this._effectiveTarget[this._property] > this.value;
  52033. case ValueCondition.IsLesser:
  52034. return this._effectiveTarget[this._property] < this.value;
  52035. case ValueCondition.IsEqual:
  52036. case ValueCondition.IsDifferent:
  52037. var check;
  52038. if (this.value.equals) {
  52039. check = this.value.equals(this._effectiveTarget[this._property]);
  52040. }
  52041. else {
  52042. check = this.value === this._effectiveTarget[this._property];
  52043. }
  52044. return this.operator === ValueCondition.IsEqual ? check : !check;
  52045. }
  52046. return false;
  52047. };
  52048. /**
  52049. * Serialize the ValueCondition into a JSON compatible object
  52050. * @returns serialization object
  52051. */
  52052. ValueCondition.prototype.serialize = function () {
  52053. return this._serialize({
  52054. name: "ValueCondition",
  52055. properties: [
  52056. BABYLON.Action._GetTargetProperty(this._target),
  52057. { name: "propertyPath", value: this.propertyPath },
  52058. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52059. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52060. ]
  52061. });
  52062. };
  52063. /**
  52064. * Gets the name of the conditional operator for the ValueCondition
  52065. * @param operator the conditional operator
  52066. * @returns the name
  52067. */
  52068. ValueCondition.GetOperatorName = function (operator) {
  52069. switch (operator) {
  52070. case ValueCondition._IsEqual: return "IsEqual";
  52071. case ValueCondition._IsDifferent: return "IsDifferent";
  52072. case ValueCondition._IsGreater: return "IsGreater";
  52073. case ValueCondition._IsLesser: return "IsLesser";
  52074. default: return "";
  52075. }
  52076. };
  52077. /**
  52078. * Internal only
  52079. * @hidden
  52080. */
  52081. ValueCondition._IsEqual = 0;
  52082. /**
  52083. * Internal only
  52084. * @hidden
  52085. */
  52086. ValueCondition._IsDifferent = 1;
  52087. /**
  52088. * Internal only
  52089. * @hidden
  52090. */
  52091. ValueCondition._IsGreater = 2;
  52092. /**
  52093. * Internal only
  52094. * @hidden
  52095. */
  52096. ValueCondition._IsLesser = 3;
  52097. return ValueCondition;
  52098. }(Condition));
  52099. BABYLON.ValueCondition = ValueCondition;
  52100. /**
  52101. * Defines a predicate condition as an extension of Condition
  52102. */
  52103. var PredicateCondition = /** @class */ (function (_super) {
  52104. __extends(PredicateCondition, _super);
  52105. /**
  52106. * Creates a new PredicateCondition
  52107. * @param actionManager manager for the action the condition applies to
  52108. * @param predicate defines the predicate function used to validate the condition
  52109. */
  52110. function PredicateCondition(actionManager,
  52111. /** defines the predicate function used to validate the condition */
  52112. predicate) {
  52113. var _this = _super.call(this, actionManager) || this;
  52114. _this.predicate = predicate;
  52115. return _this;
  52116. }
  52117. /**
  52118. * @returns the validity of the predicate condition
  52119. */
  52120. PredicateCondition.prototype.isValid = function () {
  52121. return this.predicate();
  52122. };
  52123. return PredicateCondition;
  52124. }(Condition));
  52125. BABYLON.PredicateCondition = PredicateCondition;
  52126. /**
  52127. * Defines a state condition as an extension of Condition
  52128. */
  52129. var StateCondition = /** @class */ (function (_super) {
  52130. __extends(StateCondition, _super);
  52131. /**
  52132. * Creates a new StateCondition
  52133. * @param actionManager manager for the action the condition applies to
  52134. * @param target of the condition
  52135. * @param value to compare with target state
  52136. */
  52137. function StateCondition(actionManager, target, value) {
  52138. var _this = _super.call(this, actionManager) || this;
  52139. _this.value = value;
  52140. _this._target = target;
  52141. return _this;
  52142. }
  52143. /**
  52144. * @returns the validity of the state
  52145. */
  52146. StateCondition.prototype.isValid = function () {
  52147. return this._target.state === this.value;
  52148. };
  52149. /**
  52150. * Serialize the StateCondition into a JSON compatible object
  52151. * @returns serialization object
  52152. */
  52153. StateCondition.prototype.serialize = function () {
  52154. return this._serialize({
  52155. name: "StateCondition",
  52156. properties: [
  52157. BABYLON.Action._GetTargetProperty(this._target),
  52158. { name: "value", value: this.value }
  52159. ]
  52160. });
  52161. };
  52162. return StateCondition;
  52163. }(Condition));
  52164. BABYLON.StateCondition = StateCondition;
  52165. })(BABYLON || (BABYLON = {}));
  52166. //# sourceMappingURL=babylon.condition.js.map
  52167. var BABYLON;
  52168. (function (BABYLON) {
  52169. /**
  52170. * The action to be carried out following a trigger
  52171. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52172. */
  52173. var Action = /** @class */ (function () {
  52174. /**
  52175. * Creates a new Action
  52176. * @param triggerOptions the trigger, with or without parameters, for the action
  52177. * @param condition an optional determinant of action
  52178. */
  52179. function Action(
  52180. /** the trigger, with or without parameters, for the action */
  52181. triggerOptions, condition) {
  52182. this.triggerOptions = triggerOptions;
  52183. /**
  52184. * An event triggered prior to action being executed.
  52185. */
  52186. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52187. if (triggerOptions.parameter) {
  52188. this.trigger = triggerOptions.trigger;
  52189. this._triggerParameter = triggerOptions.parameter;
  52190. }
  52191. else if (triggerOptions.trigger) {
  52192. this.trigger = triggerOptions.trigger;
  52193. }
  52194. else {
  52195. this.trigger = triggerOptions;
  52196. }
  52197. this._nextActiveAction = this;
  52198. this._condition = condition;
  52199. }
  52200. /**
  52201. * Internal only
  52202. * @hidden
  52203. */
  52204. Action.prototype._prepare = function () {
  52205. };
  52206. /**
  52207. * Gets the trigger parameters
  52208. * @returns the trigger parameters
  52209. */
  52210. Action.prototype.getTriggerParameter = function () {
  52211. return this._triggerParameter;
  52212. };
  52213. /**
  52214. * Internal only - executes current action event
  52215. * @hidden
  52216. */
  52217. Action.prototype._executeCurrent = function (evt) {
  52218. if (this._nextActiveAction._condition) {
  52219. var condition = this._nextActiveAction._condition;
  52220. var currentRenderId = this._actionManager.getScene().getRenderId();
  52221. // We cache the current evaluation for the current frame
  52222. if (condition._evaluationId === currentRenderId) {
  52223. if (!condition._currentResult) {
  52224. return;
  52225. }
  52226. }
  52227. else {
  52228. condition._evaluationId = currentRenderId;
  52229. if (!condition.isValid()) {
  52230. condition._currentResult = false;
  52231. return;
  52232. }
  52233. condition._currentResult = true;
  52234. }
  52235. }
  52236. this.onBeforeExecuteObservable.notifyObservers(this);
  52237. this._nextActiveAction.execute(evt);
  52238. this.skipToNextActiveAction();
  52239. };
  52240. /**
  52241. * Execute placeholder for child classes
  52242. * @param evt optional action event
  52243. */
  52244. Action.prototype.execute = function (evt) {
  52245. };
  52246. /**
  52247. * Skips to next active action
  52248. */
  52249. Action.prototype.skipToNextActiveAction = function () {
  52250. if (this._nextActiveAction._child) {
  52251. if (!this._nextActiveAction._child._actionManager) {
  52252. this._nextActiveAction._child._actionManager = this._actionManager;
  52253. }
  52254. this._nextActiveAction = this._nextActiveAction._child;
  52255. }
  52256. else {
  52257. this._nextActiveAction = this;
  52258. }
  52259. };
  52260. /**
  52261. * Adds action to chain of actions, may be a DoNothingAction
  52262. * @param action defines the next action to execute
  52263. * @returns The action passed in
  52264. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52265. */
  52266. Action.prototype.then = function (action) {
  52267. this._child = action;
  52268. action._actionManager = this._actionManager;
  52269. action._prepare();
  52270. return action;
  52271. };
  52272. /**
  52273. * Internal only
  52274. * @hidden
  52275. */
  52276. Action.prototype._getProperty = function (propertyPath) {
  52277. return this._actionManager._getProperty(propertyPath);
  52278. };
  52279. /**
  52280. * Internal only
  52281. * @hidden
  52282. */
  52283. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52284. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52285. };
  52286. /**
  52287. * Serialize placeholder for child classes
  52288. * @param parent of child
  52289. * @returns the serialized object
  52290. */
  52291. Action.prototype.serialize = function (parent) {
  52292. };
  52293. /**
  52294. * Internal only called by serialize
  52295. * @hidden
  52296. */
  52297. Action.prototype._serialize = function (serializedAction, parent) {
  52298. var serializationObject = {
  52299. type: 1,
  52300. children: [],
  52301. name: serializedAction.name,
  52302. properties: serializedAction.properties || []
  52303. };
  52304. // Serialize child
  52305. if (this._child) {
  52306. this._child.serialize(serializationObject);
  52307. }
  52308. // Check if "this" has a condition
  52309. if (this._condition) {
  52310. var serializedCondition = this._condition.serialize();
  52311. serializedCondition.children.push(serializationObject);
  52312. if (parent) {
  52313. parent.children.push(serializedCondition);
  52314. }
  52315. return serializedCondition;
  52316. }
  52317. if (parent) {
  52318. parent.children.push(serializationObject);
  52319. }
  52320. return serializationObject;
  52321. };
  52322. /**
  52323. * Internal only
  52324. * @hidden
  52325. */
  52326. Action._SerializeValueAsString = function (value) {
  52327. if (typeof value === "number") {
  52328. return value.toString();
  52329. }
  52330. if (typeof value === "boolean") {
  52331. return value ? "true" : "false";
  52332. }
  52333. if (value instanceof BABYLON.Vector2) {
  52334. return value.x + ", " + value.y;
  52335. }
  52336. if (value instanceof BABYLON.Vector3) {
  52337. return value.x + ", " + value.y + ", " + value.z;
  52338. }
  52339. if (value instanceof BABYLON.Color3) {
  52340. return value.r + ", " + value.g + ", " + value.b;
  52341. }
  52342. if (value instanceof BABYLON.Color4) {
  52343. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52344. }
  52345. return value; // string
  52346. };
  52347. /**
  52348. * Internal only
  52349. * @hidden
  52350. */
  52351. Action._GetTargetProperty = function (target) {
  52352. return {
  52353. name: "target",
  52354. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52355. : target instanceof BABYLON.Light ? "LightProperties"
  52356. : target instanceof BABYLON.Camera ? "CameraProperties"
  52357. : "SceneProperties",
  52358. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52359. };
  52360. };
  52361. return Action;
  52362. }());
  52363. BABYLON.Action = Action;
  52364. })(BABYLON || (BABYLON = {}));
  52365. //# sourceMappingURL=babylon.action.js.map
  52366. var BABYLON;
  52367. (function (BABYLON) {
  52368. /**
  52369. * ActionEvent is the event being sent when an action is triggered.
  52370. */
  52371. var ActionEvent = /** @class */ (function () {
  52372. /**
  52373. * Creates a new ActionEvent
  52374. * @param source The mesh or sprite that triggered the action
  52375. * @param pointerX The X mouse cursor position at the time of the event
  52376. * @param pointerY The Y mouse cursor position at the time of the event
  52377. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52378. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52379. * @param additionalData additional data for the event
  52380. */
  52381. function ActionEvent(
  52382. /** The mesh or sprite that triggered the action */
  52383. source,
  52384. /** The X mouse cursor position at the time of the event */
  52385. pointerX,
  52386. /** The Y mouse cursor position at the time of the event */
  52387. pointerY,
  52388. /** The mesh that is currently pointed at (can be null) */
  52389. meshUnderPointer,
  52390. /** the original (browser) event that triggered the ActionEvent */
  52391. sourceEvent,
  52392. /** additional data for the event */
  52393. additionalData) {
  52394. this.source = source;
  52395. this.pointerX = pointerX;
  52396. this.pointerY = pointerY;
  52397. this.meshUnderPointer = meshUnderPointer;
  52398. this.sourceEvent = sourceEvent;
  52399. this.additionalData = additionalData;
  52400. }
  52401. /**
  52402. * Helper function to auto-create an ActionEvent from a source mesh.
  52403. * @param source The source mesh that triggered the event
  52404. * @param evt The original (browser) event
  52405. * @param additionalData additional data for the event
  52406. * @returns the new ActionEvent
  52407. */
  52408. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52409. var scene = source.getScene();
  52410. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52411. };
  52412. /**
  52413. * Helper function to auto-create an ActionEvent from a source sprite
  52414. * @param source The source sprite that triggered the event
  52415. * @param scene Scene associated with the sprite
  52416. * @param evt The original (browser) event
  52417. * @param additionalData additional data for the event
  52418. * @returns the new ActionEvent
  52419. */
  52420. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52421. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52422. };
  52423. /**
  52424. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52425. * @param scene the scene where the event occurred
  52426. * @param evt The original (browser) event
  52427. * @returns the new ActionEvent
  52428. */
  52429. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52430. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52431. };
  52432. /**
  52433. * Helper function to auto-create an ActionEvent from a primitive
  52434. * @param prim defines the target primitive
  52435. * @param pointerPos defines the pointer position
  52436. * @param evt The original (browser) event
  52437. * @param additionalData additional data for the event
  52438. * @returns the new ActionEvent
  52439. */
  52440. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52441. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52442. };
  52443. return ActionEvent;
  52444. }());
  52445. BABYLON.ActionEvent = ActionEvent;
  52446. /**
  52447. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52448. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52449. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52450. */
  52451. var ActionManager = /** @class */ (function () {
  52452. /**
  52453. * Creates a new action manager
  52454. * @param scene defines the hosting scene
  52455. */
  52456. function ActionManager(scene) {
  52457. // Members
  52458. /** Gets the list of actions */
  52459. this.actions = new Array();
  52460. /** Gets the cursor to use when hovering items */
  52461. this.hoverCursor = '';
  52462. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52463. scene.actionManagers.push(this);
  52464. }
  52465. Object.defineProperty(ActionManager, "NothingTrigger", {
  52466. /**
  52467. * Nothing
  52468. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52469. */
  52470. get: function () {
  52471. return ActionManager._NothingTrigger;
  52472. },
  52473. enumerable: true,
  52474. configurable: true
  52475. });
  52476. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52477. /**
  52478. * On pick
  52479. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52480. */
  52481. get: function () {
  52482. return ActionManager._OnPickTrigger;
  52483. },
  52484. enumerable: true,
  52485. configurable: true
  52486. });
  52487. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52488. /**
  52489. * On left pick
  52490. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52491. */
  52492. get: function () {
  52493. return ActionManager._OnLeftPickTrigger;
  52494. },
  52495. enumerable: true,
  52496. configurable: true
  52497. });
  52498. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52499. /**
  52500. * On right pick
  52501. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52502. */
  52503. get: function () {
  52504. return ActionManager._OnRightPickTrigger;
  52505. },
  52506. enumerable: true,
  52507. configurable: true
  52508. });
  52509. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52510. /**
  52511. * On center pick
  52512. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52513. */
  52514. get: function () {
  52515. return ActionManager._OnCenterPickTrigger;
  52516. },
  52517. enumerable: true,
  52518. configurable: true
  52519. });
  52520. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52521. /**
  52522. * On pick down
  52523. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52524. */
  52525. get: function () {
  52526. return ActionManager._OnPickDownTrigger;
  52527. },
  52528. enumerable: true,
  52529. configurable: true
  52530. });
  52531. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52532. /**
  52533. * On double pick
  52534. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52535. */
  52536. get: function () {
  52537. return ActionManager._OnDoublePickTrigger;
  52538. },
  52539. enumerable: true,
  52540. configurable: true
  52541. });
  52542. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52543. /**
  52544. * On pick up
  52545. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52546. */
  52547. get: function () {
  52548. return ActionManager._OnPickUpTrigger;
  52549. },
  52550. enumerable: true,
  52551. configurable: true
  52552. });
  52553. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52554. /**
  52555. * On pick out.
  52556. * This trigger will only be raised if you also declared a OnPickDown
  52557. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52558. */
  52559. get: function () {
  52560. return ActionManager._OnPickOutTrigger;
  52561. },
  52562. enumerable: true,
  52563. configurable: true
  52564. });
  52565. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52566. /**
  52567. * On long press
  52568. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52569. */
  52570. get: function () {
  52571. return ActionManager._OnLongPressTrigger;
  52572. },
  52573. enumerable: true,
  52574. configurable: true
  52575. });
  52576. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52577. /**
  52578. * On pointer over
  52579. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52580. */
  52581. get: function () {
  52582. return ActionManager._OnPointerOverTrigger;
  52583. },
  52584. enumerable: true,
  52585. configurable: true
  52586. });
  52587. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52588. /**
  52589. * On pointer out
  52590. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52591. */
  52592. get: function () {
  52593. return ActionManager._OnPointerOutTrigger;
  52594. },
  52595. enumerable: true,
  52596. configurable: true
  52597. });
  52598. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52599. /**
  52600. * On every frame
  52601. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52602. */
  52603. get: function () {
  52604. return ActionManager._OnEveryFrameTrigger;
  52605. },
  52606. enumerable: true,
  52607. configurable: true
  52608. });
  52609. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52610. /**
  52611. * On intersection enter
  52612. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52613. */
  52614. get: function () {
  52615. return ActionManager._OnIntersectionEnterTrigger;
  52616. },
  52617. enumerable: true,
  52618. configurable: true
  52619. });
  52620. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52621. /**
  52622. * On intersection exit
  52623. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52624. */
  52625. get: function () {
  52626. return ActionManager._OnIntersectionExitTrigger;
  52627. },
  52628. enumerable: true,
  52629. configurable: true
  52630. });
  52631. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52632. /**
  52633. * On key down
  52634. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52635. */
  52636. get: function () {
  52637. return ActionManager._OnKeyDownTrigger;
  52638. },
  52639. enumerable: true,
  52640. configurable: true
  52641. });
  52642. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52643. /**
  52644. * On key up
  52645. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52646. */
  52647. get: function () {
  52648. return ActionManager._OnKeyUpTrigger;
  52649. },
  52650. enumerable: true,
  52651. configurable: true
  52652. });
  52653. // Methods
  52654. /**
  52655. * Releases all associated resources
  52656. */
  52657. ActionManager.prototype.dispose = function () {
  52658. var index = this._scene.actionManagers.indexOf(this);
  52659. for (var i = 0; i < this.actions.length; i++) {
  52660. var action = this.actions[i];
  52661. ActionManager.Triggers[action.trigger]--;
  52662. if (ActionManager.Triggers[action.trigger] === 0) {
  52663. delete ActionManager.Triggers[action.trigger];
  52664. }
  52665. }
  52666. if (index > -1) {
  52667. this._scene.actionManagers.splice(index, 1);
  52668. }
  52669. };
  52670. /**
  52671. * Gets hosting scene
  52672. * @returns the hosting scene
  52673. */
  52674. ActionManager.prototype.getScene = function () {
  52675. return this._scene;
  52676. };
  52677. /**
  52678. * Does this action manager handles actions of any of the given triggers
  52679. * @param triggers defines the triggers to be tested
  52680. * @return a boolean indicating whether one (or more) of the triggers is handled
  52681. */
  52682. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52683. for (var index = 0; index < this.actions.length; index++) {
  52684. var action = this.actions[index];
  52685. if (triggers.indexOf(action.trigger) > -1) {
  52686. return true;
  52687. }
  52688. }
  52689. return false;
  52690. };
  52691. /**
  52692. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52693. * speed.
  52694. * @param triggerA defines the trigger to be tested
  52695. * @param triggerB defines the trigger to be tested
  52696. * @return a boolean indicating whether one (or more) of the triggers is handled
  52697. */
  52698. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  52699. for (var index = 0; index < this.actions.length; index++) {
  52700. var action = this.actions[index];
  52701. if (triggerA == action.trigger || triggerB == action.trigger) {
  52702. return true;
  52703. }
  52704. }
  52705. return false;
  52706. };
  52707. /**
  52708. * Does this action manager handles actions of a given trigger
  52709. * @param trigger defines the trigger to be tested
  52710. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52711. * @return whether the trigger is handled
  52712. */
  52713. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52714. for (var index = 0; index < this.actions.length; index++) {
  52715. var action = this.actions[index];
  52716. if (action.trigger === trigger) {
  52717. if (parameterPredicate) {
  52718. if (parameterPredicate(action.getTriggerParameter())) {
  52719. return true;
  52720. }
  52721. }
  52722. else {
  52723. return true;
  52724. }
  52725. }
  52726. }
  52727. return false;
  52728. };
  52729. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52730. /**
  52731. * Does this action manager has pointer triggers
  52732. */
  52733. get: function () {
  52734. for (var index = 0; index < this.actions.length; index++) {
  52735. var action = this.actions[index];
  52736. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52737. return true;
  52738. }
  52739. }
  52740. return false;
  52741. },
  52742. enumerable: true,
  52743. configurable: true
  52744. });
  52745. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52746. /**
  52747. * Does this action manager has pick triggers
  52748. */
  52749. get: function () {
  52750. for (var index = 0; index < this.actions.length; index++) {
  52751. var action = this.actions[index];
  52752. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52753. return true;
  52754. }
  52755. }
  52756. return false;
  52757. },
  52758. enumerable: true,
  52759. configurable: true
  52760. });
  52761. Object.defineProperty(ActionManager, "HasTriggers", {
  52762. /**
  52763. * Does exist one action manager with at least one trigger
  52764. **/
  52765. get: function () {
  52766. for (var t in ActionManager.Triggers) {
  52767. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52768. return true;
  52769. }
  52770. }
  52771. return false;
  52772. },
  52773. enumerable: true,
  52774. configurable: true
  52775. });
  52776. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52777. /**
  52778. * Does exist one action manager with at least one pick trigger
  52779. **/
  52780. get: function () {
  52781. for (var t in ActionManager.Triggers) {
  52782. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52783. var t_int = parseInt(t);
  52784. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52785. return true;
  52786. }
  52787. }
  52788. }
  52789. return false;
  52790. },
  52791. enumerable: true,
  52792. configurable: true
  52793. });
  52794. /**
  52795. * Does exist one action manager that handles actions of a given trigger
  52796. * @param trigger defines the trigger to be tested
  52797. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52798. **/
  52799. ActionManager.HasSpecificTrigger = function (trigger) {
  52800. for (var t in ActionManager.Triggers) {
  52801. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52802. var t_int = parseInt(t);
  52803. if (t_int === trigger) {
  52804. return true;
  52805. }
  52806. }
  52807. }
  52808. return false;
  52809. };
  52810. /**
  52811. * Registers an action to this action manager
  52812. * @param action defines the action to be registered
  52813. * @return the action amended (prepared) after registration
  52814. */
  52815. ActionManager.prototype.registerAction = function (action) {
  52816. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52817. if (this.getScene().actionManager !== this) {
  52818. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52819. return null;
  52820. }
  52821. }
  52822. this.actions.push(action);
  52823. if (ActionManager.Triggers[action.trigger]) {
  52824. ActionManager.Triggers[action.trigger]++;
  52825. }
  52826. else {
  52827. ActionManager.Triggers[action.trigger] = 1;
  52828. }
  52829. action._actionManager = this;
  52830. action._prepare();
  52831. return action;
  52832. };
  52833. /**
  52834. * Unregisters an action to this action manager
  52835. * @param action defines the action to be unregistered
  52836. * @return a boolean indicating whether the action has been unregistered
  52837. */
  52838. ActionManager.prototype.unregisterAction = function (action) {
  52839. var index = this.actions.indexOf(action);
  52840. if (index !== -1) {
  52841. this.actions.splice(index, 1);
  52842. ActionManager.Triggers[action.trigger] -= 1;
  52843. if (ActionManager.Triggers[action.trigger] === 0) {
  52844. delete ActionManager.Triggers[action.trigger];
  52845. }
  52846. delete action._actionManager;
  52847. return true;
  52848. }
  52849. return false;
  52850. };
  52851. /**
  52852. * Process a specific trigger
  52853. * @param trigger defines the trigger to process
  52854. * @param evt defines the event details to be processed
  52855. */
  52856. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52857. for (var index = 0; index < this.actions.length; index++) {
  52858. var action = this.actions[index];
  52859. if (action.trigger === trigger) {
  52860. if (evt) {
  52861. if (trigger === ActionManager.OnKeyUpTrigger
  52862. || trigger === ActionManager.OnKeyDownTrigger) {
  52863. var parameter = action.getTriggerParameter();
  52864. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52865. if (!parameter.toLowerCase) {
  52866. continue;
  52867. }
  52868. var lowerCase = parameter.toLowerCase();
  52869. if (lowerCase !== evt.sourceEvent.key) {
  52870. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52871. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52872. if (actualkey !== lowerCase) {
  52873. continue;
  52874. }
  52875. }
  52876. }
  52877. }
  52878. }
  52879. action._executeCurrent(evt);
  52880. }
  52881. }
  52882. };
  52883. /** @hidden */
  52884. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52885. var properties = propertyPath.split(".");
  52886. for (var index = 0; index < properties.length - 1; index++) {
  52887. target = target[properties[index]];
  52888. }
  52889. return target;
  52890. };
  52891. /** @hidden */
  52892. ActionManager.prototype._getProperty = function (propertyPath) {
  52893. var properties = propertyPath.split(".");
  52894. return properties[properties.length - 1];
  52895. };
  52896. /**
  52897. * Serialize this manager to a JSON object
  52898. * @param name defines the property name to store this manager
  52899. * @returns a JSON representation of this manager
  52900. */
  52901. ActionManager.prototype.serialize = function (name) {
  52902. var root = {
  52903. children: new Array(),
  52904. name: name,
  52905. type: 3,
  52906. properties: new Array() // Empty for root but required
  52907. };
  52908. for (var i = 0; i < this.actions.length; i++) {
  52909. var triggerObject = {
  52910. type: 0,
  52911. children: new Array(),
  52912. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52913. properties: new Array()
  52914. };
  52915. var triggerOptions = this.actions[i].triggerOptions;
  52916. if (triggerOptions && typeof triggerOptions !== "number") {
  52917. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52918. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52919. }
  52920. else {
  52921. var parameter = {};
  52922. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52923. if (triggerOptions.parameter.mesh) {
  52924. parameter._meshId = triggerOptions.parameter.mesh.id;
  52925. }
  52926. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52927. }
  52928. }
  52929. // Serialize child action, recursively
  52930. this.actions[i].serialize(triggerObject);
  52931. // Add serialized trigger
  52932. root.children.push(triggerObject);
  52933. }
  52934. return root;
  52935. };
  52936. /**
  52937. * Creates a new ActionManager from a JSON data
  52938. * @param parsedActions defines the JSON data to read from
  52939. * @param object defines the hosting mesh
  52940. * @param scene defines the hosting scene
  52941. */
  52942. ActionManager.Parse = function (parsedActions, object, scene) {
  52943. var actionManager = new ActionManager(scene);
  52944. if (object === null)
  52945. scene.actionManager = actionManager;
  52946. else
  52947. object.actionManager = actionManager;
  52948. // instanciate a new object
  52949. var instanciate = function (name, params) {
  52950. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52951. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52952. newInstance.constructor.apply(newInstance, params);
  52953. return newInstance;
  52954. };
  52955. var parseParameter = function (name, value, target, propertyPath) {
  52956. if (propertyPath === null) {
  52957. // String, boolean or float
  52958. var floatValue = parseFloat(value);
  52959. if (value === "true" || value === "false")
  52960. return value === "true";
  52961. else
  52962. return isNaN(floatValue) ? value : floatValue;
  52963. }
  52964. var effectiveTarget = propertyPath.split(".");
  52965. var values = value.split(",");
  52966. // Get effective Target
  52967. for (var i = 0; i < effectiveTarget.length; i++) {
  52968. target = target[effectiveTarget[i]];
  52969. }
  52970. // Return appropriate value with its type
  52971. if (typeof (target) === "boolean")
  52972. return values[0] === "true";
  52973. if (typeof (target) === "string")
  52974. return values[0];
  52975. // Parameters with multiple values such as Vector3 etc.
  52976. var split = new Array();
  52977. for (var i = 0; i < values.length; i++)
  52978. split.push(parseFloat(values[i]));
  52979. if (target instanceof BABYLON.Vector3)
  52980. return BABYLON.Vector3.FromArray(split);
  52981. if (target instanceof BABYLON.Vector4)
  52982. return BABYLON.Vector4.FromArray(split);
  52983. if (target instanceof BABYLON.Color3)
  52984. return BABYLON.Color3.FromArray(split);
  52985. if (target instanceof BABYLON.Color4)
  52986. return BABYLON.Color4.FromArray(split);
  52987. return parseFloat(values[0]);
  52988. };
  52989. // traverse graph per trigger
  52990. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52991. if (combineArray === void 0) { combineArray = null; }
  52992. if (parsedAction.detached)
  52993. return;
  52994. var parameters = new Array();
  52995. var target = null;
  52996. var propertyPath = null;
  52997. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52998. // Parameters
  52999. if (parsedAction.type === 2)
  53000. parameters.push(actionManager);
  53001. else
  53002. parameters.push(trigger);
  53003. if (combine) {
  53004. var actions = new Array();
  53005. for (var j = 0; j < parsedAction.combine.length; j++) {
  53006. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53007. }
  53008. parameters.push(actions);
  53009. }
  53010. else {
  53011. for (var i = 0; i < parsedAction.properties.length; i++) {
  53012. var value = parsedAction.properties[i].value;
  53013. var name = parsedAction.properties[i].name;
  53014. var targetType = parsedAction.properties[i].targetType;
  53015. if (name === "target")
  53016. if (targetType !== null && targetType === "SceneProperties")
  53017. value = target = scene;
  53018. else
  53019. value = target = scene.getNodeByName(value);
  53020. else if (name === "parent")
  53021. value = scene.getNodeByName(value);
  53022. else if (name === "sound") {
  53023. // Can not externalize to component, so only checks for the presence off the API.
  53024. if (scene.getSoundByName) {
  53025. value = scene.getSoundByName(value);
  53026. }
  53027. }
  53028. else if (name !== "propertyPath") {
  53029. if (parsedAction.type === 2 && name === "operator")
  53030. value = BABYLON.ValueCondition[value];
  53031. else
  53032. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53033. }
  53034. else {
  53035. propertyPath = value;
  53036. }
  53037. parameters.push(value);
  53038. }
  53039. }
  53040. if (combineArray === null) {
  53041. parameters.push(condition);
  53042. }
  53043. else {
  53044. parameters.push(null);
  53045. }
  53046. // If interpolate value action
  53047. if (parsedAction.name === "InterpolateValueAction") {
  53048. var param = parameters[parameters.length - 2];
  53049. parameters[parameters.length - 1] = param;
  53050. parameters[parameters.length - 2] = condition;
  53051. }
  53052. // Action or condition(s) and not CombineAction
  53053. var newAction = instanciate(parsedAction.name, parameters);
  53054. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53055. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53056. if (action)
  53057. action.then(nothing);
  53058. else
  53059. actionManager.registerAction(nothing);
  53060. action = nothing;
  53061. }
  53062. if (combineArray === null) {
  53063. if (newAction instanceof BABYLON.Condition) {
  53064. condition = newAction;
  53065. newAction = action;
  53066. }
  53067. else {
  53068. condition = null;
  53069. if (action)
  53070. action.then(newAction);
  53071. else
  53072. actionManager.registerAction(newAction);
  53073. }
  53074. }
  53075. else {
  53076. combineArray.push(newAction);
  53077. }
  53078. for (var i = 0; i < parsedAction.children.length; i++)
  53079. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53080. };
  53081. // triggers
  53082. for (var i = 0; i < parsedActions.children.length; i++) {
  53083. var triggerParams;
  53084. var trigger = parsedActions.children[i];
  53085. if (trigger.properties.length > 0) {
  53086. var param = trigger.properties[0].value;
  53087. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53088. if (value._meshId) {
  53089. value.mesh = scene.getMeshByID(value._meshId);
  53090. }
  53091. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53092. }
  53093. else
  53094. triggerParams = ActionManager[trigger.name];
  53095. for (var j = 0; j < trigger.children.length; j++) {
  53096. if (!trigger.detached)
  53097. traverse(trigger.children[j], triggerParams, null, null);
  53098. }
  53099. }
  53100. };
  53101. /**
  53102. * Get a trigger name by index
  53103. * @param trigger defines the trigger index
  53104. * @returns a trigger name
  53105. */
  53106. ActionManager.GetTriggerName = function (trigger) {
  53107. switch (trigger) {
  53108. case 0: return "NothingTrigger";
  53109. case 1: return "OnPickTrigger";
  53110. case 2: return "OnLeftPickTrigger";
  53111. case 3: return "OnRightPickTrigger";
  53112. case 4: return "OnCenterPickTrigger";
  53113. case 5: return "OnPickDownTrigger";
  53114. case 6: return "OnPickUpTrigger";
  53115. case 7: return "OnLongPressTrigger";
  53116. case 8: return "OnPointerOverTrigger";
  53117. case 9: return "OnPointerOutTrigger";
  53118. case 10: return "OnEveryFrameTrigger";
  53119. case 11: return "OnIntersectionEnterTrigger";
  53120. case 12: return "OnIntersectionExitTrigger";
  53121. case 13: return "OnKeyDownTrigger";
  53122. case 14: return "OnKeyUpTrigger";
  53123. case 15: return "OnPickOutTrigger";
  53124. default: return "";
  53125. }
  53126. };
  53127. // Statics
  53128. ActionManager._NothingTrigger = 0;
  53129. ActionManager._OnPickTrigger = 1;
  53130. ActionManager._OnLeftPickTrigger = 2;
  53131. ActionManager._OnRightPickTrigger = 3;
  53132. ActionManager._OnCenterPickTrigger = 4;
  53133. ActionManager._OnPickDownTrigger = 5;
  53134. ActionManager._OnDoublePickTrigger = 6;
  53135. ActionManager._OnPickUpTrigger = 7;
  53136. ActionManager._OnLongPressTrigger = 8;
  53137. ActionManager._OnPointerOverTrigger = 9;
  53138. ActionManager._OnPointerOutTrigger = 10;
  53139. ActionManager._OnEveryFrameTrigger = 11;
  53140. ActionManager._OnIntersectionEnterTrigger = 12;
  53141. ActionManager._OnIntersectionExitTrigger = 13;
  53142. ActionManager._OnKeyDownTrigger = 14;
  53143. ActionManager._OnKeyUpTrigger = 15;
  53144. ActionManager._OnPickOutTrigger = 16;
  53145. /** Gets the list of active triggers */
  53146. ActionManager.Triggers = {};
  53147. return ActionManager;
  53148. }());
  53149. BABYLON.ActionManager = ActionManager;
  53150. })(BABYLON || (BABYLON = {}));
  53151. //# sourceMappingURL=babylon.actionManager.js.map
  53152. var BABYLON;
  53153. (function (BABYLON) {
  53154. var InterpolateValueAction = /** @class */ (function (_super) {
  53155. __extends(InterpolateValueAction, _super);
  53156. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53157. if (duration === void 0) { duration = 1000; }
  53158. var _this = _super.call(this, triggerOptions, condition) || this;
  53159. _this.propertyPath = propertyPath;
  53160. _this.value = value;
  53161. _this.duration = duration;
  53162. _this.stopOtherAnimations = stopOtherAnimations;
  53163. _this.onInterpolationDone = onInterpolationDone;
  53164. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53165. _this._target = _this._effectiveTarget = target;
  53166. return _this;
  53167. }
  53168. /** @hidden */
  53169. InterpolateValueAction.prototype._prepare = function () {
  53170. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53171. this._property = this._getProperty(this.propertyPath);
  53172. };
  53173. InterpolateValueAction.prototype.execute = function () {
  53174. var _this = this;
  53175. var scene = this._actionManager.getScene();
  53176. var keys = [
  53177. {
  53178. frame: 0,
  53179. value: this._effectiveTarget[this._property]
  53180. }, {
  53181. frame: 100,
  53182. value: this.value
  53183. }
  53184. ];
  53185. var dataType;
  53186. if (typeof this.value === "number") {
  53187. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53188. }
  53189. else if (this.value instanceof BABYLON.Color3) {
  53190. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53191. }
  53192. else if (this.value instanceof BABYLON.Vector3) {
  53193. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53194. }
  53195. else if (this.value instanceof BABYLON.Matrix) {
  53196. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53197. }
  53198. else if (this.value instanceof BABYLON.Quaternion) {
  53199. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53200. }
  53201. else {
  53202. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53203. return;
  53204. }
  53205. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53206. animation.setKeys(keys);
  53207. if (this.stopOtherAnimations) {
  53208. scene.stopAnimation(this._effectiveTarget);
  53209. }
  53210. var wrapper = function () {
  53211. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53212. if (_this.onInterpolationDone) {
  53213. _this.onInterpolationDone();
  53214. }
  53215. };
  53216. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53217. };
  53218. InterpolateValueAction.prototype.serialize = function (parent) {
  53219. return _super.prototype._serialize.call(this, {
  53220. name: "InterpolateValueAction",
  53221. properties: [
  53222. BABYLON.Action._GetTargetProperty(this._target),
  53223. { name: "propertyPath", value: this.propertyPath },
  53224. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53225. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53226. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53227. ]
  53228. }, parent);
  53229. };
  53230. return InterpolateValueAction;
  53231. }(BABYLON.Action));
  53232. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53233. })(BABYLON || (BABYLON = {}));
  53234. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53235. var BABYLON;
  53236. (function (BABYLON) {
  53237. var SwitchBooleanAction = /** @class */ (function (_super) {
  53238. __extends(SwitchBooleanAction, _super);
  53239. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53240. var _this = _super.call(this, triggerOptions, condition) || this;
  53241. _this.propertyPath = propertyPath;
  53242. _this._target = _this._effectiveTarget = target;
  53243. return _this;
  53244. }
  53245. /** @hidden */
  53246. SwitchBooleanAction.prototype._prepare = function () {
  53247. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53248. this._property = this._getProperty(this.propertyPath);
  53249. };
  53250. SwitchBooleanAction.prototype.execute = function () {
  53251. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53252. };
  53253. SwitchBooleanAction.prototype.serialize = function (parent) {
  53254. return _super.prototype._serialize.call(this, {
  53255. name: "SwitchBooleanAction",
  53256. properties: [
  53257. BABYLON.Action._GetTargetProperty(this._target),
  53258. { name: "propertyPath", value: this.propertyPath }
  53259. ]
  53260. }, parent);
  53261. };
  53262. return SwitchBooleanAction;
  53263. }(BABYLON.Action));
  53264. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53265. var SetStateAction = /** @class */ (function (_super) {
  53266. __extends(SetStateAction, _super);
  53267. function SetStateAction(triggerOptions, target, value, condition) {
  53268. var _this = _super.call(this, triggerOptions, condition) || this;
  53269. _this.value = value;
  53270. _this._target = target;
  53271. return _this;
  53272. }
  53273. SetStateAction.prototype.execute = function () {
  53274. this._target.state = this.value;
  53275. };
  53276. SetStateAction.prototype.serialize = function (parent) {
  53277. return _super.prototype._serialize.call(this, {
  53278. name: "SetStateAction",
  53279. properties: [
  53280. BABYLON.Action._GetTargetProperty(this._target),
  53281. { name: "value", value: this.value }
  53282. ]
  53283. }, parent);
  53284. };
  53285. return SetStateAction;
  53286. }(BABYLON.Action));
  53287. BABYLON.SetStateAction = SetStateAction;
  53288. var SetValueAction = /** @class */ (function (_super) {
  53289. __extends(SetValueAction, _super);
  53290. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53291. var _this = _super.call(this, triggerOptions, condition) || this;
  53292. _this.propertyPath = propertyPath;
  53293. _this.value = value;
  53294. _this._target = _this._effectiveTarget = target;
  53295. return _this;
  53296. }
  53297. /** @hidden */
  53298. SetValueAction.prototype._prepare = function () {
  53299. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53300. this._property = this._getProperty(this.propertyPath);
  53301. };
  53302. SetValueAction.prototype.execute = function () {
  53303. this._effectiveTarget[this._property] = this.value;
  53304. if (this._target.markAsDirty) {
  53305. this._target.markAsDirty(this._property);
  53306. }
  53307. };
  53308. SetValueAction.prototype.serialize = function (parent) {
  53309. return _super.prototype._serialize.call(this, {
  53310. name: "SetValueAction",
  53311. properties: [
  53312. BABYLON.Action._GetTargetProperty(this._target),
  53313. { name: "propertyPath", value: this.propertyPath },
  53314. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53315. ]
  53316. }, parent);
  53317. };
  53318. return SetValueAction;
  53319. }(BABYLON.Action));
  53320. BABYLON.SetValueAction = SetValueAction;
  53321. var IncrementValueAction = /** @class */ (function (_super) {
  53322. __extends(IncrementValueAction, _super);
  53323. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53324. var _this = _super.call(this, triggerOptions, condition) || this;
  53325. _this.propertyPath = propertyPath;
  53326. _this.value = value;
  53327. _this._target = _this._effectiveTarget = target;
  53328. return _this;
  53329. }
  53330. /** @hidden */
  53331. IncrementValueAction.prototype._prepare = function () {
  53332. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53333. this._property = this._getProperty(this.propertyPath);
  53334. if (typeof this._effectiveTarget[this._property] !== "number") {
  53335. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53336. }
  53337. };
  53338. IncrementValueAction.prototype.execute = function () {
  53339. this._effectiveTarget[this._property] += this.value;
  53340. if (this._target.markAsDirty) {
  53341. this._target.markAsDirty(this._property);
  53342. }
  53343. };
  53344. IncrementValueAction.prototype.serialize = function (parent) {
  53345. return _super.prototype._serialize.call(this, {
  53346. name: "IncrementValueAction",
  53347. properties: [
  53348. BABYLON.Action._GetTargetProperty(this._target),
  53349. { name: "propertyPath", value: this.propertyPath },
  53350. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53351. ]
  53352. }, parent);
  53353. };
  53354. return IncrementValueAction;
  53355. }(BABYLON.Action));
  53356. BABYLON.IncrementValueAction = IncrementValueAction;
  53357. var PlayAnimationAction = /** @class */ (function (_super) {
  53358. __extends(PlayAnimationAction, _super);
  53359. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53360. var _this = _super.call(this, triggerOptions, condition) || this;
  53361. _this.from = from;
  53362. _this.to = to;
  53363. _this.loop = loop;
  53364. _this._target = target;
  53365. return _this;
  53366. }
  53367. /** @hidden */
  53368. PlayAnimationAction.prototype._prepare = function () {
  53369. };
  53370. PlayAnimationAction.prototype.execute = function () {
  53371. var scene = this._actionManager.getScene();
  53372. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53373. };
  53374. PlayAnimationAction.prototype.serialize = function (parent) {
  53375. return _super.prototype._serialize.call(this, {
  53376. name: "PlayAnimationAction",
  53377. properties: [
  53378. BABYLON.Action._GetTargetProperty(this._target),
  53379. { name: "from", value: String(this.from) },
  53380. { name: "to", value: String(this.to) },
  53381. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53382. ]
  53383. }, parent);
  53384. };
  53385. return PlayAnimationAction;
  53386. }(BABYLON.Action));
  53387. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53388. var StopAnimationAction = /** @class */ (function (_super) {
  53389. __extends(StopAnimationAction, _super);
  53390. function StopAnimationAction(triggerOptions, target, condition) {
  53391. var _this = _super.call(this, triggerOptions, condition) || this;
  53392. _this._target = target;
  53393. return _this;
  53394. }
  53395. /** @hidden */
  53396. StopAnimationAction.prototype._prepare = function () {
  53397. };
  53398. StopAnimationAction.prototype.execute = function () {
  53399. var scene = this._actionManager.getScene();
  53400. scene.stopAnimation(this._target);
  53401. };
  53402. StopAnimationAction.prototype.serialize = function (parent) {
  53403. return _super.prototype._serialize.call(this, {
  53404. name: "StopAnimationAction",
  53405. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53406. }, parent);
  53407. };
  53408. return StopAnimationAction;
  53409. }(BABYLON.Action));
  53410. BABYLON.StopAnimationAction = StopAnimationAction;
  53411. var DoNothingAction = /** @class */ (function (_super) {
  53412. __extends(DoNothingAction, _super);
  53413. function DoNothingAction(triggerOptions, condition) {
  53414. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53415. return _super.call(this, triggerOptions, condition) || this;
  53416. }
  53417. DoNothingAction.prototype.execute = function () {
  53418. };
  53419. DoNothingAction.prototype.serialize = function (parent) {
  53420. return _super.prototype._serialize.call(this, {
  53421. name: "DoNothingAction",
  53422. properties: []
  53423. }, parent);
  53424. };
  53425. return DoNothingAction;
  53426. }(BABYLON.Action));
  53427. BABYLON.DoNothingAction = DoNothingAction;
  53428. var CombineAction = /** @class */ (function (_super) {
  53429. __extends(CombineAction, _super);
  53430. function CombineAction(triggerOptions, children, condition) {
  53431. var _this = _super.call(this, triggerOptions, condition) || this;
  53432. _this.children = children;
  53433. return _this;
  53434. }
  53435. /** @hidden */
  53436. CombineAction.prototype._prepare = function () {
  53437. for (var index = 0; index < this.children.length; index++) {
  53438. this.children[index]._actionManager = this._actionManager;
  53439. this.children[index]._prepare();
  53440. }
  53441. };
  53442. CombineAction.prototype.execute = function (evt) {
  53443. for (var index = 0; index < this.children.length; index++) {
  53444. this.children[index].execute(evt);
  53445. }
  53446. };
  53447. CombineAction.prototype.serialize = function (parent) {
  53448. var serializationObject = _super.prototype._serialize.call(this, {
  53449. name: "CombineAction",
  53450. properties: [],
  53451. combine: []
  53452. }, parent);
  53453. for (var i = 0; i < this.children.length; i++) {
  53454. serializationObject.combine.push(this.children[i].serialize(null));
  53455. }
  53456. return serializationObject;
  53457. };
  53458. return CombineAction;
  53459. }(BABYLON.Action));
  53460. BABYLON.CombineAction = CombineAction;
  53461. var ExecuteCodeAction = /** @class */ (function (_super) {
  53462. __extends(ExecuteCodeAction, _super);
  53463. function ExecuteCodeAction(triggerOptions, func, condition) {
  53464. var _this = _super.call(this, triggerOptions, condition) || this;
  53465. _this.func = func;
  53466. return _this;
  53467. }
  53468. ExecuteCodeAction.prototype.execute = function (evt) {
  53469. this.func(evt);
  53470. };
  53471. return ExecuteCodeAction;
  53472. }(BABYLON.Action));
  53473. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53474. var SetParentAction = /** @class */ (function (_super) {
  53475. __extends(SetParentAction, _super);
  53476. function SetParentAction(triggerOptions, target, parent, condition) {
  53477. var _this = _super.call(this, triggerOptions, condition) || this;
  53478. _this._target = target;
  53479. _this._parent = parent;
  53480. return _this;
  53481. }
  53482. /** @hidden */
  53483. SetParentAction.prototype._prepare = function () {
  53484. };
  53485. SetParentAction.prototype.execute = function () {
  53486. if (this._target.parent === this._parent) {
  53487. return;
  53488. }
  53489. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53490. invertParentWorldMatrix.invert();
  53491. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53492. this._target.parent = this._parent;
  53493. };
  53494. SetParentAction.prototype.serialize = function (parent) {
  53495. return _super.prototype._serialize.call(this, {
  53496. name: "SetParentAction",
  53497. properties: [
  53498. BABYLON.Action._GetTargetProperty(this._target),
  53499. BABYLON.Action._GetTargetProperty(this._parent),
  53500. ]
  53501. }, parent);
  53502. };
  53503. return SetParentAction;
  53504. }(BABYLON.Action));
  53505. BABYLON.SetParentAction = SetParentAction;
  53506. })(BABYLON || (BABYLON = {}));
  53507. //# sourceMappingURL=babylon.directActions.js.map
  53508. var BABYLON;
  53509. (function (BABYLON) {
  53510. var SpriteManager = /** @class */ (function () {
  53511. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53512. if (epsilon === void 0) { epsilon = 0.01; }
  53513. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53514. this.name = name;
  53515. this.sprites = new Array();
  53516. this.renderingGroupId = 0;
  53517. this.layerMask = 0x0FFFFFFF;
  53518. this.fogEnabled = true;
  53519. this.isPickable = false;
  53520. /**
  53521. * An event triggered when the manager is disposed.
  53522. */
  53523. this.onDisposeObservable = new BABYLON.Observable();
  53524. this._vertexBuffers = {};
  53525. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53526. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53527. }
  53528. this._capacity = capacity;
  53529. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53530. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53531. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53532. if (cellSize.width && cellSize.height) {
  53533. this.cellWidth = cellSize.width;
  53534. this.cellHeight = cellSize.height;
  53535. }
  53536. else if (cellSize !== undefined) {
  53537. this.cellWidth = cellSize;
  53538. this.cellHeight = cellSize;
  53539. }
  53540. else {
  53541. return;
  53542. }
  53543. this._epsilon = epsilon;
  53544. this._scene = scene;
  53545. this._scene.spriteManagers.push(this);
  53546. var indices = [];
  53547. var index = 0;
  53548. for (var count = 0; count < capacity; count++) {
  53549. indices.push(index);
  53550. indices.push(index + 1);
  53551. indices.push(index + 2);
  53552. indices.push(index);
  53553. indices.push(index + 2);
  53554. indices.push(index + 3);
  53555. index += 4;
  53556. }
  53557. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53558. // VBO
  53559. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53560. this._vertexData = new Float32Array(capacity * 16 * 4);
  53561. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53562. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53563. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53564. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53565. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53566. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53567. this._vertexBuffers["options"] = options;
  53568. this._vertexBuffers["cellInfo"] = cellInfo;
  53569. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53570. // Effects
  53571. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53572. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53573. }
  53574. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53575. set: function (callback) {
  53576. if (this._onDisposeObserver) {
  53577. this.onDisposeObservable.remove(this._onDisposeObserver);
  53578. }
  53579. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53580. },
  53581. enumerable: true,
  53582. configurable: true
  53583. });
  53584. Object.defineProperty(SpriteManager.prototype, "texture", {
  53585. get: function () {
  53586. return this._spriteTexture;
  53587. },
  53588. set: function (value) {
  53589. this._spriteTexture = value;
  53590. },
  53591. enumerable: true,
  53592. configurable: true
  53593. });
  53594. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53595. var arrayOffset = index * 16;
  53596. if (offsetX === 0)
  53597. offsetX = this._epsilon;
  53598. else if (offsetX === 1)
  53599. offsetX = 1 - this._epsilon;
  53600. if (offsetY === 0)
  53601. offsetY = this._epsilon;
  53602. else if (offsetY === 1)
  53603. offsetY = 1 - this._epsilon;
  53604. this._vertexData[arrayOffset] = sprite.position.x;
  53605. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53606. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53607. this._vertexData[arrayOffset + 3] = sprite.angle;
  53608. this._vertexData[arrayOffset + 4] = sprite.width;
  53609. this._vertexData[arrayOffset + 5] = sprite.height;
  53610. this._vertexData[arrayOffset + 6] = offsetX;
  53611. this._vertexData[arrayOffset + 7] = offsetY;
  53612. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53613. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53614. var offset = (sprite.cellIndex / rowSize) >> 0;
  53615. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53616. this._vertexData[arrayOffset + 11] = offset;
  53617. // Color
  53618. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53619. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53620. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53621. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53622. };
  53623. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53624. var count = Math.min(this._capacity, this.sprites.length);
  53625. var min = BABYLON.Vector3.Zero();
  53626. var max = BABYLON.Vector3.Zero();
  53627. var distance = Number.MAX_VALUE;
  53628. var currentSprite = null;
  53629. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53630. var cameraView = camera.getViewMatrix();
  53631. for (var index = 0; index < count; index++) {
  53632. var sprite = this.sprites[index];
  53633. if (!sprite) {
  53634. continue;
  53635. }
  53636. if (predicate) {
  53637. if (!predicate(sprite)) {
  53638. continue;
  53639. }
  53640. }
  53641. else if (!sprite.isPickable) {
  53642. continue;
  53643. }
  53644. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53645. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53646. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53647. if (ray.intersectsBoxMinMax(min, max)) {
  53648. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53649. if (distance > currentDistance) {
  53650. distance = currentDistance;
  53651. currentSprite = sprite;
  53652. if (fastCheck) {
  53653. break;
  53654. }
  53655. }
  53656. }
  53657. }
  53658. if (currentSprite) {
  53659. var result = new BABYLON.PickingInfo();
  53660. result.hit = true;
  53661. result.pickedSprite = currentSprite;
  53662. result.distance = distance;
  53663. return result;
  53664. }
  53665. return null;
  53666. };
  53667. SpriteManager.prototype.render = function () {
  53668. // Check
  53669. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53670. return;
  53671. var engine = this._scene.getEngine();
  53672. var baseSize = this._spriteTexture.getBaseSize();
  53673. // Sprites
  53674. var deltaTime = engine.getDeltaTime();
  53675. var max = Math.min(this._capacity, this.sprites.length);
  53676. var rowSize = baseSize.width / this.cellWidth;
  53677. var offset = 0;
  53678. for (var index = 0; index < max; index++) {
  53679. var sprite = this.sprites[index];
  53680. if (!sprite || !sprite.isVisible) {
  53681. continue;
  53682. }
  53683. sprite._animate(deltaTime);
  53684. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53685. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53686. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53687. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53688. }
  53689. this._buffer.update(this._vertexData);
  53690. // Render
  53691. var effect = this._effectBase;
  53692. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53693. effect = this._effectFog;
  53694. }
  53695. engine.enableEffect(effect);
  53696. var viewMatrix = this._scene.getViewMatrix();
  53697. effect.setTexture("diffuseSampler", this._spriteTexture);
  53698. effect.setMatrix("view", viewMatrix);
  53699. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53700. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53701. // Fog
  53702. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53703. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53704. effect.setColor3("vFogColor", this._scene.fogColor);
  53705. }
  53706. // VBOs
  53707. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53708. // Draw order
  53709. engine.setDepthFunctionToLessOrEqual();
  53710. effect.setBool("alphaTest", true);
  53711. engine.setColorWrite(false);
  53712. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53713. engine.setColorWrite(true);
  53714. effect.setBool("alphaTest", false);
  53715. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53716. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53717. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53718. };
  53719. SpriteManager.prototype.dispose = function () {
  53720. if (this._buffer) {
  53721. this._buffer.dispose();
  53722. this._buffer = null;
  53723. }
  53724. if (this._indexBuffer) {
  53725. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53726. this._indexBuffer = null;
  53727. }
  53728. if (this._spriteTexture) {
  53729. this._spriteTexture.dispose();
  53730. this._spriteTexture = null;
  53731. }
  53732. // Remove from scene
  53733. var index = this._scene.spriteManagers.indexOf(this);
  53734. this._scene.spriteManagers.splice(index, 1);
  53735. // Callback
  53736. this.onDisposeObservable.notifyObservers(this);
  53737. this.onDisposeObservable.clear();
  53738. };
  53739. return SpriteManager;
  53740. }());
  53741. BABYLON.SpriteManager = SpriteManager;
  53742. })(BABYLON || (BABYLON = {}));
  53743. //# sourceMappingURL=babylon.spriteManager.js.map
  53744. var BABYLON;
  53745. (function (BABYLON) {
  53746. var Sprite = /** @class */ (function () {
  53747. function Sprite(name, manager) {
  53748. this.name = name;
  53749. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53750. this.width = 1.0;
  53751. this.height = 1.0;
  53752. this.angle = 0;
  53753. this.cellIndex = 0;
  53754. this.invertU = 0;
  53755. this.invertV = 0;
  53756. this.animations = new Array();
  53757. this.isPickable = false;
  53758. this._animationStarted = false;
  53759. this._loopAnimation = false;
  53760. this._fromIndex = 0;
  53761. this._toIndex = 0;
  53762. this._delay = 0;
  53763. this._direction = 1;
  53764. this._time = 0;
  53765. /**
  53766. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53767. */
  53768. this.isVisible = true;
  53769. this._manager = manager;
  53770. this._manager.sprites.push(this);
  53771. this.position = BABYLON.Vector3.Zero();
  53772. }
  53773. Object.defineProperty(Sprite.prototype, "size", {
  53774. get: function () {
  53775. return this.width;
  53776. },
  53777. set: function (value) {
  53778. this.width = value;
  53779. this.height = value;
  53780. },
  53781. enumerable: true,
  53782. configurable: true
  53783. });
  53784. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53785. this._fromIndex = from;
  53786. this._toIndex = to;
  53787. this._loopAnimation = loop;
  53788. this._delay = delay;
  53789. this._animationStarted = true;
  53790. this._direction = from < to ? 1 : -1;
  53791. this.cellIndex = from;
  53792. this._time = 0;
  53793. this._onAnimationEnd = onAnimationEnd;
  53794. };
  53795. Sprite.prototype.stopAnimation = function () {
  53796. this._animationStarted = false;
  53797. };
  53798. /** @hidden */
  53799. Sprite.prototype._animate = function (deltaTime) {
  53800. if (!this._animationStarted)
  53801. return;
  53802. this._time += deltaTime;
  53803. if (this._time > this._delay) {
  53804. this._time = this._time % this._delay;
  53805. this.cellIndex += this._direction;
  53806. if (this.cellIndex > this._toIndex) {
  53807. if (this._loopAnimation) {
  53808. this.cellIndex = this._fromIndex;
  53809. }
  53810. else {
  53811. this.cellIndex = this._toIndex;
  53812. this._animationStarted = false;
  53813. if (this._onAnimationEnd) {
  53814. this._onAnimationEnd();
  53815. }
  53816. if (this.disposeWhenFinishedAnimating) {
  53817. this.dispose();
  53818. }
  53819. }
  53820. }
  53821. }
  53822. };
  53823. Sprite.prototype.dispose = function () {
  53824. for (var i = 0; i < this._manager.sprites.length; i++) {
  53825. if (this._manager.sprites[i] == this) {
  53826. this._manager.sprites.splice(i, 1);
  53827. }
  53828. }
  53829. };
  53830. return Sprite;
  53831. }());
  53832. BABYLON.Sprite = Sprite;
  53833. })(BABYLON || (BABYLON = {}));
  53834. //# sourceMappingURL=babylon.sprite.js.map
  53835. var BABYLON;
  53836. (function (BABYLON) {
  53837. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  53838. if (!BABYLON.PickingInfo) {
  53839. return null;
  53840. }
  53841. var pickingInfo = null;
  53842. if (!camera) {
  53843. if (!this.activeCamera) {
  53844. return null;
  53845. }
  53846. camera = this.activeCamera;
  53847. }
  53848. if (this.spriteManagers.length > 0) {
  53849. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  53850. var spriteManager = this.spriteManagers[spriteIndex];
  53851. if (!spriteManager.isPickable) {
  53852. continue;
  53853. }
  53854. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  53855. if (!result || !result.hit)
  53856. continue;
  53857. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  53858. continue;
  53859. pickingInfo = result;
  53860. if (fastCheck) {
  53861. break;
  53862. }
  53863. }
  53864. }
  53865. return pickingInfo || new BABYLON.PickingInfo();
  53866. };
  53867. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  53868. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  53869. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  53870. };
  53871. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  53872. if (!this._tempSpritePickingRay) {
  53873. return null;
  53874. }
  53875. if (!camera) {
  53876. if (!this.activeCamera) {
  53877. return null;
  53878. }
  53879. camera = this.activeCamera;
  53880. }
  53881. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  53882. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  53883. };
  53884. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  53885. if (this._pointerOverSprite === sprite) {
  53886. return;
  53887. }
  53888. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  53889. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  53890. }
  53891. this._pointerOverSprite = sprite;
  53892. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  53893. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  53894. }
  53895. };
  53896. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  53897. return this._pointerOverSprite;
  53898. };
  53899. /**
  53900. * Defines the sprite scene component responsible to manage sprites
  53901. * in a given scene.
  53902. */
  53903. var SpriteSceneComponent = /** @class */ (function () {
  53904. /**
  53905. * Creates a new instance of the component for the given scene
  53906. * @param scene Defines the scene to register the component in
  53907. */
  53908. function SpriteSceneComponent(scene) {
  53909. /**
  53910. * The component name helpfull to identify the component in the list of scene components.
  53911. */
  53912. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  53913. this.scene = scene;
  53914. this.scene.spriteManagers = new Array();
  53915. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  53916. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  53917. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  53918. this._spritePredicate = function (sprite) {
  53919. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  53920. };
  53921. }
  53922. /**
  53923. * Registers the component in a given scene
  53924. */
  53925. SpriteSceneComponent.prototype.register = function () {
  53926. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  53927. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  53928. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  53929. };
  53930. /**
  53931. * Rebuilds the elements related to this component in case of
  53932. * context lost for instance.
  53933. */
  53934. SpriteSceneComponent.prototype.rebuild = function () {
  53935. /** Nothing to do for sprites */
  53936. };
  53937. /**
  53938. * Disposes the component and the associated ressources.
  53939. */
  53940. SpriteSceneComponent.prototype.dispose = function () {
  53941. this.scene.onBeforeSpritesRenderingObservable.clear();
  53942. this.scene.onAfterSpritesRenderingObservable.clear();
  53943. var spriteManagers = this.scene.spriteManagers;
  53944. while (spriteManagers.length) {
  53945. spriteManagers[0].dispose();
  53946. }
  53947. };
  53948. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  53949. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  53950. if (result) {
  53951. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  53952. }
  53953. return result;
  53954. };
  53955. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  53956. var scene = this.scene;
  53957. if (isMeshPicked) {
  53958. scene.setPointerOverSprite(null);
  53959. }
  53960. else {
  53961. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  53962. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  53963. scene.setPointerOverSprite(pickResult.pickedSprite);
  53964. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  53965. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  53966. }
  53967. else {
  53968. canvas.style.cursor = scene.hoverCursor;
  53969. }
  53970. }
  53971. else {
  53972. scene.setPointerOverSprite(null);
  53973. }
  53974. }
  53975. return pickResult;
  53976. };
  53977. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  53978. var scene = this.scene;
  53979. scene._pickedDownSprite = null;
  53980. if (scene.spriteManagers.length > 0) {
  53981. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  53982. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  53983. if (pickResult.pickedSprite.actionManager) {
  53984. scene._pickedDownSprite = pickResult.pickedSprite;
  53985. switch (evt.button) {
  53986. case 0:
  53987. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53988. break;
  53989. case 1:
  53990. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53991. break;
  53992. case 2:
  53993. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53994. break;
  53995. }
  53996. if (pickResult.pickedSprite.actionManager) {
  53997. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53998. }
  53999. }
  54000. }
  54001. }
  54002. return pickResult;
  54003. };
  54004. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54005. var scene = this.scene;
  54006. if (scene.spriteManagers.length > 0) {
  54007. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54008. if (spritePickResult) {
  54009. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  54010. if (spritePickResult.pickedSprite.actionManager) {
  54011. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54012. if (spritePickResult.pickedSprite.actionManager) {
  54013. if (!this.scene._isPointerSwiping()) {
  54014. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54015. }
  54016. }
  54017. }
  54018. }
  54019. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  54020. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  54021. }
  54022. }
  54023. }
  54024. return pickResult;
  54025. };
  54026. return SpriteSceneComponent;
  54027. }());
  54028. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54029. })(BABYLON || (BABYLON = {}));
  54030. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54031. var BABYLON;
  54032. (function (BABYLON) {
  54033. var IntersectionInfo = /** @class */ (function () {
  54034. function IntersectionInfo(bu, bv, distance) {
  54035. this.bu = bu;
  54036. this.bv = bv;
  54037. this.distance = distance;
  54038. this.faceId = 0;
  54039. this.subMeshId = 0;
  54040. }
  54041. return IntersectionInfo;
  54042. }());
  54043. BABYLON.IntersectionInfo = IntersectionInfo;
  54044. /**
  54045. * Information about the result of picking within a scene
  54046. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54047. */
  54048. var PickingInfo = /** @class */ (function () {
  54049. function PickingInfo() {
  54050. /**
  54051. * If the pick collided with an object
  54052. */
  54053. this.hit = false;
  54054. /**
  54055. * Distance away where the pick collided
  54056. */
  54057. this.distance = 0;
  54058. /**
  54059. * The location of pick collision
  54060. */
  54061. this.pickedPoint = null;
  54062. /**
  54063. * The mesh corresponding the the pick collision
  54064. */
  54065. this.pickedMesh = null;
  54066. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54067. this.bu = 0;
  54068. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54069. this.bv = 0;
  54070. /** The id of the face on the mesh that was picked */
  54071. this.faceId = -1;
  54072. /** Id of the the submesh that was picked */
  54073. this.subMeshId = 0;
  54074. /** If a sprite was picked, this will be the sprite the pick collided with */
  54075. this.pickedSprite = null;
  54076. /**
  54077. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54078. */
  54079. this.originMesh = null;
  54080. /**
  54081. * The ray that was used to perform the picking.
  54082. */
  54083. this.ray = null;
  54084. }
  54085. /**
  54086. * Gets the normal correspodning to the face the pick collided with
  54087. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54088. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54089. * @returns The normal correspodning to the face the pick collided with
  54090. */
  54091. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54092. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54093. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54094. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54095. return null;
  54096. }
  54097. var indices = this.pickedMesh.getIndices();
  54098. if (!indices) {
  54099. return null;
  54100. }
  54101. var result;
  54102. if (useVerticesNormals) {
  54103. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54104. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54105. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54106. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54107. normal0 = normal0.scale(this.bu);
  54108. normal1 = normal1.scale(this.bv);
  54109. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54110. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54111. }
  54112. else {
  54113. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54114. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54115. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54116. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54117. var p1p2 = vertex1.subtract(vertex2);
  54118. var p3p2 = vertex3.subtract(vertex2);
  54119. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54120. }
  54121. if (useWorldCoordinates) {
  54122. var wm = this.pickedMesh.getWorldMatrix();
  54123. if (this.pickedMesh.nonUniformScaling) {
  54124. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54125. wm = BABYLON.Tmp.Matrix[0];
  54126. wm.setTranslationFromFloats(0, 0, 0);
  54127. wm.invert();
  54128. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54129. wm = BABYLON.Tmp.Matrix[1];
  54130. }
  54131. result = BABYLON.Vector3.TransformNormal(result, wm);
  54132. }
  54133. result.normalize();
  54134. return result;
  54135. };
  54136. /**
  54137. * Gets the texture coordinates of where the pick occured
  54138. * @returns the vector containing the coordnates of the texture
  54139. */
  54140. PickingInfo.prototype.getTextureCoordinates = function () {
  54141. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54142. return null;
  54143. }
  54144. var indices = this.pickedMesh.getIndices();
  54145. if (!indices) {
  54146. return null;
  54147. }
  54148. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54149. if (!uvs) {
  54150. return null;
  54151. }
  54152. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54153. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54154. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54155. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54156. uv1 = uv1.scale(this.bu);
  54157. uv2 = uv2.scale(this.bv);
  54158. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54159. };
  54160. return PickingInfo;
  54161. }());
  54162. BABYLON.PickingInfo = PickingInfo;
  54163. })(BABYLON || (BABYLON = {}));
  54164. //# sourceMappingURL=babylon.pickingInfo.js.map
  54165. var BABYLON;
  54166. (function (BABYLON) {
  54167. var Ray = /** @class */ (function () {
  54168. function Ray(origin, direction, length) {
  54169. if (length === void 0) { length = Number.MAX_VALUE; }
  54170. this.origin = origin;
  54171. this.direction = direction;
  54172. this.length = length;
  54173. }
  54174. // Methods
  54175. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54176. var d = 0.0;
  54177. var maxValue = Number.MAX_VALUE;
  54178. var inv;
  54179. var min;
  54180. var max;
  54181. var temp;
  54182. if (Math.abs(this.direction.x) < 0.0000001) {
  54183. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54184. return false;
  54185. }
  54186. }
  54187. else {
  54188. inv = 1.0 / this.direction.x;
  54189. min = (minimum.x - this.origin.x) * inv;
  54190. max = (maximum.x - this.origin.x) * inv;
  54191. if (max === -Infinity) {
  54192. max = Infinity;
  54193. }
  54194. if (min > max) {
  54195. temp = min;
  54196. min = max;
  54197. max = temp;
  54198. }
  54199. d = Math.max(min, d);
  54200. maxValue = Math.min(max, maxValue);
  54201. if (d > maxValue) {
  54202. return false;
  54203. }
  54204. }
  54205. if (Math.abs(this.direction.y) < 0.0000001) {
  54206. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54207. return false;
  54208. }
  54209. }
  54210. else {
  54211. inv = 1.0 / this.direction.y;
  54212. min = (minimum.y - this.origin.y) * inv;
  54213. max = (maximum.y - this.origin.y) * inv;
  54214. if (max === -Infinity) {
  54215. max = Infinity;
  54216. }
  54217. if (min > max) {
  54218. temp = min;
  54219. min = max;
  54220. max = temp;
  54221. }
  54222. d = Math.max(min, d);
  54223. maxValue = Math.min(max, maxValue);
  54224. if (d > maxValue) {
  54225. return false;
  54226. }
  54227. }
  54228. if (Math.abs(this.direction.z) < 0.0000001) {
  54229. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54230. return false;
  54231. }
  54232. }
  54233. else {
  54234. inv = 1.0 / this.direction.z;
  54235. min = (minimum.z - this.origin.z) * inv;
  54236. max = (maximum.z - this.origin.z) * inv;
  54237. if (max === -Infinity) {
  54238. max = Infinity;
  54239. }
  54240. if (min > max) {
  54241. temp = min;
  54242. min = max;
  54243. max = temp;
  54244. }
  54245. d = Math.max(min, d);
  54246. maxValue = Math.min(max, maxValue);
  54247. if (d > maxValue) {
  54248. return false;
  54249. }
  54250. }
  54251. return true;
  54252. };
  54253. Ray.prototype.intersectsBox = function (box) {
  54254. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54255. };
  54256. Ray.prototype.intersectsSphere = function (sphere) {
  54257. var x = sphere.center.x - this.origin.x;
  54258. var y = sphere.center.y - this.origin.y;
  54259. var z = sphere.center.z - this.origin.z;
  54260. var pyth = (x * x) + (y * y) + (z * z);
  54261. var rr = sphere.radius * sphere.radius;
  54262. if (pyth <= rr) {
  54263. return true;
  54264. }
  54265. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54266. if (dot < 0.0) {
  54267. return false;
  54268. }
  54269. var temp = pyth - (dot * dot);
  54270. return temp <= rr;
  54271. };
  54272. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54273. if (!this._edge1) {
  54274. this._edge1 = BABYLON.Vector3.Zero();
  54275. this._edge2 = BABYLON.Vector3.Zero();
  54276. this._pvec = BABYLON.Vector3.Zero();
  54277. this._tvec = BABYLON.Vector3.Zero();
  54278. this._qvec = BABYLON.Vector3.Zero();
  54279. }
  54280. vertex1.subtractToRef(vertex0, this._edge1);
  54281. vertex2.subtractToRef(vertex0, this._edge2);
  54282. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54283. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54284. if (det === 0) {
  54285. return null;
  54286. }
  54287. var invdet = 1 / det;
  54288. this.origin.subtractToRef(vertex0, this._tvec);
  54289. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54290. if (bu < 0 || bu > 1.0) {
  54291. return null;
  54292. }
  54293. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54294. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54295. if (bv < 0 || bu + bv > 1.0) {
  54296. return null;
  54297. }
  54298. //check if the distance is longer than the predefined length.
  54299. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54300. if (distance > this.length) {
  54301. return null;
  54302. }
  54303. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54304. };
  54305. Ray.prototype.intersectsPlane = function (plane) {
  54306. var distance;
  54307. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54308. if (Math.abs(result1) < 9.99999997475243E-07) {
  54309. return null;
  54310. }
  54311. else {
  54312. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54313. distance = (-plane.d - result2) / result1;
  54314. if (distance < 0.0) {
  54315. if (distance < -9.99999997475243E-07) {
  54316. return null;
  54317. }
  54318. else {
  54319. return 0;
  54320. }
  54321. }
  54322. return distance;
  54323. }
  54324. };
  54325. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54326. var tm = BABYLON.Tmp.Matrix[0];
  54327. mesh.getWorldMatrix().invertToRef(tm);
  54328. if (this._tmpRay) {
  54329. Ray.TransformToRef(this, tm, this._tmpRay);
  54330. }
  54331. else {
  54332. this._tmpRay = Ray.Transform(this, tm);
  54333. }
  54334. return mesh.intersects(this._tmpRay, fastCheck);
  54335. };
  54336. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54337. if (results) {
  54338. results.length = 0;
  54339. }
  54340. else {
  54341. results = [];
  54342. }
  54343. for (var i = 0; i < meshes.length; i++) {
  54344. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54345. if (pickInfo.hit) {
  54346. results.push(pickInfo);
  54347. }
  54348. }
  54349. results.sort(this._comparePickingInfo);
  54350. return results;
  54351. };
  54352. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54353. if (pickingInfoA.distance < pickingInfoB.distance) {
  54354. return -1;
  54355. }
  54356. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54357. return 1;
  54358. }
  54359. else {
  54360. return 0;
  54361. }
  54362. };
  54363. /**
  54364. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54365. * @param sega the first point of the segment to test the intersection against
  54366. * @param segb the second point of the segment to test the intersection against
  54367. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54368. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54369. */
  54370. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54371. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54372. var u = segb.subtract(sega);
  54373. var v = rsegb.subtract(this.origin);
  54374. var w = sega.subtract(this.origin);
  54375. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54376. var b = BABYLON.Vector3.Dot(u, v);
  54377. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54378. var d = BABYLON.Vector3.Dot(u, w);
  54379. var e = BABYLON.Vector3.Dot(v, w);
  54380. var D = a * c - b * b; // always >= 0
  54381. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54382. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54383. // compute the line parameters of the two closest points
  54384. if (D < Ray.smallnum) { // the lines are almost parallel
  54385. sN = 0.0; // force using point P0 on segment S1
  54386. sD = 1.0; // to prevent possible division by 0.0 later
  54387. tN = e;
  54388. tD = c;
  54389. }
  54390. else { // get the closest points on the infinite lines
  54391. sN = (b * e - c * d);
  54392. tN = (a * e - b * d);
  54393. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54394. sN = 0.0;
  54395. tN = e;
  54396. tD = c;
  54397. }
  54398. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54399. sN = sD;
  54400. tN = e + b;
  54401. tD = c;
  54402. }
  54403. }
  54404. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54405. tN = 0.0;
  54406. // recompute sc for this edge
  54407. if (-d < 0.0) {
  54408. sN = 0.0;
  54409. }
  54410. else if (-d > a)
  54411. sN = sD;
  54412. else {
  54413. sN = -d;
  54414. sD = a;
  54415. }
  54416. }
  54417. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54418. tN = tD;
  54419. // recompute sc for this edge
  54420. if ((-d + b) < 0.0) {
  54421. sN = 0;
  54422. }
  54423. else if ((-d + b) > a) {
  54424. sN = sD;
  54425. }
  54426. else {
  54427. sN = (-d + b);
  54428. sD = a;
  54429. }
  54430. }
  54431. // finally do the division to get sc and tc
  54432. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54433. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54434. // get the difference of the two closest points
  54435. var qtc = v.multiplyByFloats(tc, tc, tc);
  54436. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54437. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54438. if (isIntersected) {
  54439. return qtc.length();
  54440. }
  54441. return -1;
  54442. };
  54443. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54444. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54445. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54446. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54447. this.direction.normalize();
  54448. return this;
  54449. };
  54450. // Statics
  54451. Ray.Zero = function () {
  54452. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54453. };
  54454. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54455. var result = Ray.Zero();
  54456. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54457. };
  54458. /**
  54459. * 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
  54460. * transformed to the given world matrix.
  54461. * @param origin The origin point
  54462. * @param end The end point
  54463. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54464. */
  54465. Ray.CreateNewFromTo = function (origin, end, world) {
  54466. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54467. var direction = end.subtract(origin);
  54468. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54469. direction.normalize();
  54470. return Ray.Transform(new Ray(origin, direction, length), world);
  54471. };
  54472. Ray.Transform = function (ray, matrix) {
  54473. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54474. Ray.TransformToRef(ray, matrix, result);
  54475. return result;
  54476. };
  54477. Ray.TransformToRef = function (ray, matrix, result) {
  54478. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54479. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54480. result.length = ray.length;
  54481. var dir = result.direction;
  54482. var len = dir.length();
  54483. if (!(len === 0 || len === 1)) {
  54484. var num = 1.0 / len;
  54485. dir.x *= num;
  54486. dir.y *= num;
  54487. dir.z *= num;
  54488. result.length *= len;
  54489. }
  54490. };
  54491. Ray.smallnum = 0.00000001;
  54492. Ray.rayl = 10e8;
  54493. return Ray;
  54494. }());
  54495. BABYLON.Ray = Ray;
  54496. })(BABYLON || (BABYLON = {}));
  54497. //# sourceMappingURL=babylon.ray.js.map
  54498. var BABYLON;
  54499. (function (BABYLON) {
  54500. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54501. if (boxMin.x > sphereCenter.x + sphereRadius)
  54502. return false;
  54503. if (sphereCenter.x - sphereRadius > boxMax.x)
  54504. return false;
  54505. if (boxMin.y > sphereCenter.y + sphereRadius)
  54506. return false;
  54507. if (sphereCenter.y - sphereRadius > boxMax.y)
  54508. return false;
  54509. if (boxMin.z > sphereCenter.z + sphereRadius)
  54510. return false;
  54511. if (sphereCenter.z - sphereRadius > boxMax.z)
  54512. return false;
  54513. return true;
  54514. };
  54515. var getLowestRoot = (function () {
  54516. var result = { root: 0, found: false };
  54517. return function (a, b, c, maxR) {
  54518. result.root = 0;
  54519. result.found = false;
  54520. var determinant = b * b - 4.0 * a * c;
  54521. if (determinant < 0)
  54522. return result;
  54523. var sqrtD = Math.sqrt(determinant);
  54524. var r1 = (-b - sqrtD) / (2.0 * a);
  54525. var r2 = (-b + sqrtD) / (2.0 * a);
  54526. if (r1 > r2) {
  54527. var temp = r2;
  54528. r2 = r1;
  54529. r1 = temp;
  54530. }
  54531. if (r1 > 0 && r1 < maxR) {
  54532. result.root = r1;
  54533. result.found = true;
  54534. return result;
  54535. }
  54536. if (r2 > 0 && r2 < maxR) {
  54537. result.root = r2;
  54538. result.found = true;
  54539. return result;
  54540. }
  54541. return result;
  54542. };
  54543. })();
  54544. var Collider = /** @class */ (function () {
  54545. function Collider() {
  54546. this._collisionPoint = BABYLON.Vector3.Zero();
  54547. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54548. this._tempVector = BABYLON.Vector3.Zero();
  54549. this._tempVector2 = BABYLON.Vector3.Zero();
  54550. this._tempVector3 = BABYLON.Vector3.Zero();
  54551. this._tempVector4 = BABYLON.Vector3.Zero();
  54552. this._edge = BABYLON.Vector3.Zero();
  54553. this._baseToVertex = BABYLON.Vector3.Zero();
  54554. this._destinationPoint = BABYLON.Vector3.Zero();
  54555. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54556. this._displacementVector = BABYLON.Vector3.Zero();
  54557. /** @hidden */
  54558. this._radius = BABYLON.Vector3.One();
  54559. /** @hidden */
  54560. this._retry = 0;
  54561. /** @hidden */
  54562. this._basePointWorld = BABYLON.Vector3.Zero();
  54563. this._velocityWorld = BABYLON.Vector3.Zero();
  54564. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54565. this._collisionMask = -1;
  54566. }
  54567. Object.defineProperty(Collider.prototype, "collisionMask", {
  54568. get: function () {
  54569. return this._collisionMask;
  54570. },
  54571. set: function (mask) {
  54572. this._collisionMask = !isNaN(mask) ? mask : -1;
  54573. },
  54574. enumerable: true,
  54575. configurable: true
  54576. });
  54577. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54578. /**
  54579. * Gets the plane normal used to compute the sliding response (in local space)
  54580. */
  54581. get: function () {
  54582. return this._slidePlaneNormal;
  54583. },
  54584. enumerable: true,
  54585. configurable: true
  54586. });
  54587. // Methods
  54588. /** @hidden */
  54589. Collider.prototype._initialize = function (source, dir, e) {
  54590. this._velocity = dir;
  54591. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54592. this._basePoint = source;
  54593. source.multiplyToRef(this._radius, this._basePointWorld);
  54594. dir.multiplyToRef(this._radius, this._velocityWorld);
  54595. this._velocityWorldLength = this._velocityWorld.length();
  54596. this._epsilon = e;
  54597. this.collisionFound = false;
  54598. };
  54599. /** @hidden */
  54600. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54601. pa.subtractToRef(point, this._tempVector);
  54602. pb.subtractToRef(point, this._tempVector2);
  54603. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54604. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54605. if (d < 0)
  54606. return false;
  54607. pc.subtractToRef(point, this._tempVector3);
  54608. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54609. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54610. if (d < 0)
  54611. return false;
  54612. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54613. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54614. return d >= 0;
  54615. };
  54616. /** @hidden */
  54617. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54618. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54619. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54620. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54621. return false;
  54622. }
  54623. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54624. return false;
  54625. return true;
  54626. };
  54627. /** @hidden */
  54628. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54629. var t0;
  54630. var embeddedInPlane = false;
  54631. //defensive programming, actually not needed.
  54632. if (!trianglePlaneArray) {
  54633. trianglePlaneArray = [];
  54634. }
  54635. if (!trianglePlaneArray[faceIndex]) {
  54636. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54637. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54638. }
  54639. var trianglePlane = trianglePlaneArray[faceIndex];
  54640. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54641. return;
  54642. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54643. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54644. if (normalDotVelocity == 0) {
  54645. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54646. return;
  54647. embeddedInPlane = true;
  54648. t0 = 0;
  54649. }
  54650. else {
  54651. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54652. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54653. if (t0 > t1) {
  54654. var temp = t1;
  54655. t1 = t0;
  54656. t0 = temp;
  54657. }
  54658. if (t0 > 1.0 || t1 < 0.0)
  54659. return;
  54660. if (t0 < 0)
  54661. t0 = 0;
  54662. if (t0 > 1.0)
  54663. t0 = 1.0;
  54664. }
  54665. this._collisionPoint.copyFromFloats(0, 0, 0);
  54666. var found = false;
  54667. var t = 1.0;
  54668. if (!embeddedInPlane) {
  54669. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54670. this._velocity.scaleToRef(t0, this._tempVector);
  54671. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54672. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54673. found = true;
  54674. t = t0;
  54675. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54676. }
  54677. }
  54678. if (!found) {
  54679. var velocitySquaredLength = this._velocity.lengthSquared();
  54680. var a = velocitySquaredLength;
  54681. this._basePoint.subtractToRef(p1, this._tempVector);
  54682. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54683. var c = this._tempVector.lengthSquared() - 1.0;
  54684. var lowestRoot = getLowestRoot(a, b, c, t);
  54685. if (lowestRoot.found) {
  54686. t = lowestRoot.root;
  54687. found = true;
  54688. this._collisionPoint.copyFrom(p1);
  54689. }
  54690. this._basePoint.subtractToRef(p2, this._tempVector);
  54691. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54692. c = this._tempVector.lengthSquared() - 1.0;
  54693. lowestRoot = getLowestRoot(a, b, c, t);
  54694. if (lowestRoot.found) {
  54695. t = lowestRoot.root;
  54696. found = true;
  54697. this._collisionPoint.copyFrom(p2);
  54698. }
  54699. this._basePoint.subtractToRef(p3, this._tempVector);
  54700. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54701. c = this._tempVector.lengthSquared() - 1.0;
  54702. lowestRoot = getLowestRoot(a, b, c, t);
  54703. if (lowestRoot.found) {
  54704. t = lowestRoot.root;
  54705. found = true;
  54706. this._collisionPoint.copyFrom(p3);
  54707. }
  54708. p2.subtractToRef(p1, this._edge);
  54709. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54710. var edgeSquaredLength = this._edge.lengthSquared();
  54711. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54712. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54713. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54714. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54715. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54716. lowestRoot = getLowestRoot(a, b, c, t);
  54717. if (lowestRoot.found) {
  54718. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54719. if (f >= 0.0 && f <= 1.0) {
  54720. t = lowestRoot.root;
  54721. found = true;
  54722. this._edge.scaleInPlace(f);
  54723. p1.addToRef(this._edge, this._collisionPoint);
  54724. }
  54725. }
  54726. p3.subtractToRef(p2, this._edge);
  54727. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54728. edgeSquaredLength = this._edge.lengthSquared();
  54729. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54730. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54731. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54732. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54733. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54734. lowestRoot = getLowestRoot(a, b, c, t);
  54735. if (lowestRoot.found) {
  54736. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54737. if (f >= 0.0 && f <= 1.0) {
  54738. t = lowestRoot.root;
  54739. found = true;
  54740. this._edge.scaleInPlace(f);
  54741. p2.addToRef(this._edge, this._collisionPoint);
  54742. }
  54743. }
  54744. p1.subtractToRef(p3, this._edge);
  54745. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54746. edgeSquaredLength = this._edge.lengthSquared();
  54747. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54748. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54749. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54750. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54751. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54752. lowestRoot = getLowestRoot(a, b, c, t);
  54753. if (lowestRoot.found) {
  54754. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54755. if (f >= 0.0 && f <= 1.0) {
  54756. t = lowestRoot.root;
  54757. found = true;
  54758. this._edge.scaleInPlace(f);
  54759. p3.addToRef(this._edge, this._collisionPoint);
  54760. }
  54761. }
  54762. }
  54763. if (found) {
  54764. var distToCollision = t * this._velocity.length();
  54765. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54766. if (!this.intersectionPoint) {
  54767. this.intersectionPoint = this._collisionPoint.clone();
  54768. }
  54769. else {
  54770. this.intersectionPoint.copyFrom(this._collisionPoint);
  54771. }
  54772. this._nearestDistance = distToCollision;
  54773. this.collisionFound = true;
  54774. }
  54775. }
  54776. };
  54777. /** @hidden */
  54778. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54779. for (var i = indexStart; i < indexEnd; i += 3) {
  54780. var p1 = pts[indices[i] - decal];
  54781. var p2 = pts[indices[i + 1] - decal];
  54782. var p3 = pts[indices[i + 2] - decal];
  54783. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54784. }
  54785. };
  54786. /** @hidden */
  54787. Collider.prototype._getResponse = function (pos, vel) {
  54788. pos.addToRef(vel, this._destinationPoint);
  54789. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54790. this._basePoint.addToRef(vel, pos);
  54791. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54792. this._slidePlaneNormal.normalize();
  54793. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54794. pos.addInPlace(this._displacementVector);
  54795. this.intersectionPoint.addInPlace(this._displacementVector);
  54796. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54797. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54798. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54799. };
  54800. return Collider;
  54801. }());
  54802. BABYLON.Collider = Collider;
  54803. })(BABYLON || (BABYLON = {}));
  54804. //# sourceMappingURL=babylon.collider.js.map
  54805. var BABYLON;
  54806. (function (BABYLON) {
  54807. //WebWorker code will be inserted to this variable.
  54808. BABYLON.CollisionWorker = "";
  54809. /** Defines supported task for worker process */
  54810. var WorkerTaskType;
  54811. (function (WorkerTaskType) {
  54812. /** Initialization */
  54813. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54814. /** Update of geometry */
  54815. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54816. /** Evaluate collision */
  54817. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54818. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54819. /** Defines kind of replies returned by worker */
  54820. var WorkerReplyType;
  54821. (function (WorkerReplyType) {
  54822. /** Success */
  54823. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54824. /** Unkown error */
  54825. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54826. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54827. var CollisionCoordinatorWorker = /** @class */ (function () {
  54828. function CollisionCoordinatorWorker() {
  54829. var _this = this;
  54830. this._scaledPosition = BABYLON.Vector3.Zero();
  54831. this._scaledVelocity = BABYLON.Vector3.Zero();
  54832. this.onMeshUpdated = function (transformNode) {
  54833. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54834. };
  54835. this.onGeometryUpdated = function (geometry) {
  54836. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54837. };
  54838. this._afterRender = function () {
  54839. if (!_this._init)
  54840. return;
  54841. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54842. return;
  54843. }
  54844. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54845. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54846. if (_this._runningUpdated > 4) {
  54847. return;
  54848. }
  54849. ++_this._runningUpdated;
  54850. var payload = {
  54851. updatedMeshes: _this._addUpdateMeshesList,
  54852. updatedGeometries: _this._addUpdateGeometriesList,
  54853. removedGeometries: _this._toRemoveGeometryArray,
  54854. removedMeshes: _this._toRemoveMeshesArray
  54855. };
  54856. var message = {
  54857. payload: payload,
  54858. taskType: WorkerTaskType.UPDATE
  54859. };
  54860. var serializable = [];
  54861. for (var id in payload.updatedGeometries) {
  54862. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54863. //prepare transferables
  54864. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54865. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54866. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54867. }
  54868. }
  54869. _this._worker.postMessage(message, serializable);
  54870. _this._addUpdateMeshesList = {};
  54871. _this._addUpdateGeometriesList = {};
  54872. _this._toRemoveGeometryArray = [];
  54873. _this._toRemoveMeshesArray = [];
  54874. };
  54875. this._onMessageFromWorker = function (e) {
  54876. var returnData = e.data;
  54877. if (returnData.error != WorkerReplyType.SUCCESS) {
  54878. //TODO what errors can be returned from the worker?
  54879. BABYLON.Tools.Warn("error returned from worker!");
  54880. return;
  54881. }
  54882. switch (returnData.taskType) {
  54883. case WorkerTaskType.INIT:
  54884. _this._init = true;
  54885. //Update the worked with ALL of the scene's current state
  54886. _this._scene.meshes.forEach(function (mesh) {
  54887. _this.onMeshAdded(mesh);
  54888. });
  54889. _this._scene.getGeometries().forEach(function (geometry) {
  54890. _this.onGeometryAdded(geometry);
  54891. });
  54892. break;
  54893. case WorkerTaskType.UPDATE:
  54894. _this._runningUpdated--;
  54895. break;
  54896. case WorkerTaskType.COLLIDE:
  54897. var returnPayload = returnData.payload;
  54898. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54899. return;
  54900. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54901. if (callback) {
  54902. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54903. if (mesh) {
  54904. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54905. }
  54906. }
  54907. //cleanup
  54908. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54909. break;
  54910. }
  54911. };
  54912. this._collisionsCallbackArray = [];
  54913. this._init = false;
  54914. this._runningUpdated = 0;
  54915. this._addUpdateMeshesList = {};
  54916. this._addUpdateGeometriesList = {};
  54917. this._toRemoveGeometryArray = [];
  54918. this._toRemoveMeshesArray = [];
  54919. }
  54920. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54921. if (!this._init)
  54922. return;
  54923. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54924. return;
  54925. position.divideToRef(collider._radius, this._scaledPosition);
  54926. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54927. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54928. var payload = {
  54929. collider: {
  54930. position: this._scaledPosition.asArray(),
  54931. velocity: this._scaledVelocity.asArray(),
  54932. radius: collider._radius.asArray()
  54933. },
  54934. collisionId: collisionIndex,
  54935. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54936. maximumRetry: maximumRetry
  54937. };
  54938. var message = {
  54939. payload: payload,
  54940. taskType: WorkerTaskType.COLLIDE
  54941. };
  54942. this._worker.postMessage(message);
  54943. };
  54944. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54945. this._scene = scene;
  54946. this._scene.registerAfterRender(this._afterRender);
  54947. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54948. this._worker = new Worker(workerUrl);
  54949. this._worker.onmessage = this._onMessageFromWorker;
  54950. var message = {
  54951. payload: {},
  54952. taskType: WorkerTaskType.INIT
  54953. };
  54954. this._worker.postMessage(message);
  54955. };
  54956. CollisionCoordinatorWorker.prototype.destroy = function () {
  54957. this._scene.unregisterAfterRender(this._afterRender);
  54958. this._worker.terminate();
  54959. };
  54960. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54961. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54962. this.onMeshUpdated(mesh);
  54963. };
  54964. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54965. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54966. };
  54967. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54968. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54969. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54970. this.onGeometryUpdated(geometry);
  54971. };
  54972. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54973. this._toRemoveGeometryArray.push(geometry.id);
  54974. };
  54975. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54976. var submeshes = [];
  54977. if (mesh.subMeshes) {
  54978. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54979. var boundingInfo = sm.getBoundingInfo();
  54980. return {
  54981. position: idx,
  54982. verticesStart: sm.verticesStart,
  54983. verticesCount: sm.verticesCount,
  54984. indexStart: sm.indexStart,
  54985. indexCount: sm.indexCount,
  54986. hasMaterial: !!sm.getMaterial(),
  54987. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54988. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54989. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54990. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54991. };
  54992. });
  54993. }
  54994. var geometryId = null;
  54995. if (mesh instanceof BABYLON.Mesh) {
  54996. var geometry = mesh.geometry;
  54997. geometryId = geometry ? geometry.id : null;
  54998. }
  54999. else if (mesh instanceof BABYLON.InstancedMesh) {
  55000. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55001. geometryId = geometry ? geometry.id : null;
  55002. }
  55003. var boundingInfo = mesh.getBoundingInfo();
  55004. return {
  55005. uniqueId: mesh.uniqueId,
  55006. id: mesh.id,
  55007. name: mesh.name,
  55008. geometryId: geometryId,
  55009. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55010. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55011. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55012. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55013. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55014. subMeshes: submeshes,
  55015. checkCollisions: mesh.checkCollisions
  55016. };
  55017. };
  55018. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55019. return {
  55020. id: geometry.id,
  55021. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55022. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55023. indices: new Uint32Array(geometry.getIndices() || []),
  55024. };
  55025. };
  55026. return CollisionCoordinatorWorker;
  55027. }());
  55028. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55029. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55030. function CollisionCoordinatorLegacy() {
  55031. this._scaledPosition = BABYLON.Vector3.Zero();
  55032. this._scaledVelocity = BABYLON.Vector3.Zero();
  55033. this._finalPosition = BABYLON.Vector3.Zero();
  55034. }
  55035. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55036. position.divideToRef(collider._radius, this._scaledPosition);
  55037. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55038. collider.collidedMesh = null;
  55039. collider._retry = 0;
  55040. collider._initialVelocity = this._scaledVelocity;
  55041. collider._initialPosition = this._scaledPosition;
  55042. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55043. this._finalPosition.multiplyInPlace(collider._radius);
  55044. //run the callback
  55045. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55046. };
  55047. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55048. this._scene = scene;
  55049. };
  55050. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55051. //Legacy need no destruction method.
  55052. };
  55053. //No update in legacy mode
  55054. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55055. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55056. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55057. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55058. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55059. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55060. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55061. if (excludedMesh === void 0) { excludedMesh = null; }
  55062. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55063. if (collider._retry >= maximumRetry) {
  55064. finalPosition.copyFrom(position);
  55065. return;
  55066. }
  55067. // Check if this is a mesh else camera or -1
  55068. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55069. collider._initialize(position, velocity, closeDistance);
  55070. // Check all meshes
  55071. for (var index = 0; index < this._scene.meshes.length; index++) {
  55072. var mesh = this._scene.meshes[index];
  55073. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55074. mesh._checkCollision(collider);
  55075. }
  55076. }
  55077. if (!collider.collisionFound) {
  55078. position.addToRef(velocity, finalPosition);
  55079. return;
  55080. }
  55081. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55082. collider._getResponse(position, velocity);
  55083. }
  55084. if (velocity.length() <= closeDistance) {
  55085. finalPosition.copyFrom(position);
  55086. return;
  55087. }
  55088. collider._retry++;
  55089. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55090. };
  55091. return CollisionCoordinatorLegacy;
  55092. }());
  55093. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55094. })(BABYLON || (BABYLON = {}));
  55095. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55096. var BABYLON;
  55097. (function (BABYLON) {
  55098. /**
  55099. * A particle represents one of the element emitted by a particle system.
  55100. * This is mainly define by its coordinates, direction, velocity and age.
  55101. */
  55102. var Particle = /** @class */ (function () {
  55103. /**
  55104. * Creates a new instance Particle
  55105. * @param particleSystem the particle system the particle belongs to
  55106. */
  55107. function Particle(
  55108. /**
  55109. * The particle system the particle belongs to.
  55110. */
  55111. particleSystem) {
  55112. this.particleSystem = particleSystem;
  55113. /**
  55114. * The world position of the particle in the scene.
  55115. */
  55116. this.position = BABYLON.Vector3.Zero();
  55117. /**
  55118. * The world direction of the particle in the scene.
  55119. */
  55120. this.direction = BABYLON.Vector3.Zero();
  55121. /**
  55122. * The color of the particle.
  55123. */
  55124. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55125. /**
  55126. * The color change of the particle per step.
  55127. */
  55128. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55129. /**
  55130. * Defines how long will the life of the particle be.
  55131. */
  55132. this.lifeTime = 1.0;
  55133. /**
  55134. * The current age of the particle.
  55135. */
  55136. this.age = 0;
  55137. /**
  55138. * The current size of the particle.
  55139. */
  55140. this.size = 0;
  55141. /**
  55142. * The current scale of the particle.
  55143. */
  55144. this.scale = new BABYLON.Vector2(1, 1);
  55145. /**
  55146. * The current angle of the particle.
  55147. */
  55148. this.angle = 0;
  55149. /**
  55150. * Defines how fast is the angle changing.
  55151. */
  55152. this.angularSpeed = 0;
  55153. /**
  55154. * Defines the cell index used by the particle to be rendered from a sprite.
  55155. */
  55156. this.cellIndex = 0;
  55157. /** @hidden */
  55158. this._attachedSubEmitters = null;
  55159. /** @hidden */
  55160. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55161. /** @hidden */
  55162. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55163. /** @hidden */
  55164. this._currentSize1 = 0;
  55165. /** @hidden */
  55166. this._currentSize2 = 0;
  55167. /** @hidden */
  55168. this._currentAngularSpeed1 = 0;
  55169. /** @hidden */
  55170. this._currentAngularSpeed2 = 0;
  55171. /** @hidden */
  55172. this._currentVelocity1 = 0;
  55173. /** @hidden */
  55174. this._currentVelocity2 = 0;
  55175. /** @hidden */
  55176. this._currentLimitVelocity1 = 0;
  55177. /** @hidden */
  55178. this._currentLimitVelocity2 = 0;
  55179. /** @hidden */
  55180. this._currentDrag1 = 0;
  55181. /** @hidden */
  55182. this._currentDrag2 = 0;
  55183. this.id = Particle._Count++;
  55184. if (!this.particleSystem.isAnimationSheetEnabled) {
  55185. return;
  55186. }
  55187. this.updateCellInfoFromSystem();
  55188. }
  55189. Particle.prototype.updateCellInfoFromSystem = function () {
  55190. this.cellIndex = this.particleSystem.startSpriteCellID;
  55191. };
  55192. /**
  55193. * Defines how the sprite cell index is updated for the particle
  55194. */
  55195. Particle.prototype.updateCellIndex = function () {
  55196. var offsetAge = this.age;
  55197. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  55198. if (this.particleSystem.spriteRandomStartCell) {
  55199. if (this._randomCellOffset === undefined) {
  55200. this._randomCellOffset = Math.random() * this.lifeTime;
  55201. }
  55202. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  55203. changeSpeed = 1;
  55204. offsetAge = this._randomCellOffset;
  55205. }
  55206. else {
  55207. offsetAge += this._randomCellOffset;
  55208. }
  55209. }
  55210. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55211. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  55212. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55213. };
  55214. /** @hidden */
  55215. Particle.prototype._reset = function () {
  55216. this.age = 0;
  55217. this._currentColorGradient = null;
  55218. this._currentSizeGradient = null;
  55219. this._currentAngularSpeedGradient = null;
  55220. this._currentVelocityGradient = null;
  55221. this._currentLimitVelocityGradient = null;
  55222. this._currentDragGradient = null;
  55223. this.cellIndex = this.particleSystem.startSpriteCellID;
  55224. this._randomCellOffset = undefined;
  55225. };
  55226. /**
  55227. * Copy the properties of particle to another one.
  55228. * @param other the particle to copy the information to.
  55229. */
  55230. Particle.prototype.copyTo = function (other) {
  55231. other.position.copyFrom(this.position);
  55232. if (this._initialDirection) {
  55233. if (other._initialDirection) {
  55234. other._initialDirection.copyFrom(this._initialDirection);
  55235. }
  55236. else {
  55237. other._initialDirection = this._initialDirection.clone();
  55238. }
  55239. }
  55240. else {
  55241. other._initialDirection = null;
  55242. }
  55243. other.direction.copyFrom(this.direction);
  55244. other.color.copyFrom(this.color);
  55245. other.colorStep.copyFrom(this.colorStep);
  55246. other.lifeTime = this.lifeTime;
  55247. other.age = this.age;
  55248. other._randomCellOffset = undefined;
  55249. other.size = this.size;
  55250. other.scale.copyFrom(this.scale);
  55251. other.angle = this.angle;
  55252. other.angularSpeed = this.angularSpeed;
  55253. other.particleSystem = this.particleSystem;
  55254. other.cellIndex = this.cellIndex;
  55255. other.id = this.id;
  55256. other._attachedSubEmitters = this._attachedSubEmitters;
  55257. if (this._currentColorGradient) {
  55258. other._currentColorGradient = this._currentColorGradient;
  55259. other._currentColor1.copyFrom(this._currentColor1);
  55260. other._currentColor2.copyFrom(this._currentColor2);
  55261. }
  55262. if (this._currentSizeGradient) {
  55263. other._currentSizeGradient = this._currentSizeGradient;
  55264. other._currentSize1 = this._currentSize1;
  55265. other._currentSize2 = this._currentSize2;
  55266. }
  55267. if (this._currentAngularSpeedGradient) {
  55268. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55269. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55270. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55271. }
  55272. if (this._currentVelocityGradient) {
  55273. other._currentVelocityGradient = this._currentVelocityGradient;
  55274. other._currentVelocity1 = this._currentVelocity1;
  55275. other._currentVelocity2 = this._currentVelocity2;
  55276. }
  55277. if (this._currentLimitVelocityGradient) {
  55278. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55279. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55280. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55281. }
  55282. if (this._currentDragGradient) {
  55283. other._currentDragGradient = this._currentDragGradient;
  55284. other._currentDrag1 = this._currentDrag1;
  55285. other._currentDrag2 = this._currentDrag2;
  55286. }
  55287. if (this.particleSystem.isAnimationSheetEnabled) {
  55288. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55289. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55290. }
  55291. if (this.particleSystem.useRampGradients) {
  55292. other.remapData.copyFrom(this.remapData);
  55293. }
  55294. if (this._randomNoiseCoordinates1) {
  55295. if (other._randomNoiseCoordinates1) {
  55296. other._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  55297. other._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  55298. }
  55299. else {
  55300. other._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  55301. other._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  55302. }
  55303. }
  55304. };
  55305. Particle._Count = 0;
  55306. return Particle;
  55307. }());
  55308. BABYLON.Particle = Particle;
  55309. })(BABYLON || (BABYLON = {}));
  55310. //# sourceMappingURL=babylon.particle.js.map
  55311. var BABYLON;
  55312. (function (BABYLON) {
  55313. /**
  55314. * This represents the base class for particle system in Babylon.
  55315. * 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.
  55316. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55317. * @example https://doc.babylonjs.com/babylon101/particles
  55318. */
  55319. var BaseParticleSystem = /** @class */ (function () {
  55320. /**
  55321. * Instantiates a particle system.
  55322. * 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.
  55323. * @param name The name of the particle system
  55324. */
  55325. function BaseParticleSystem(name) {
  55326. /**
  55327. * List of animations used by the particle system.
  55328. */
  55329. this.animations = [];
  55330. /**
  55331. * The rendering group used by the Particle system to chose when to render.
  55332. */
  55333. this.renderingGroupId = 0;
  55334. /**
  55335. * The emitter represents the Mesh or position we are attaching the particle system to.
  55336. */
  55337. this.emitter = null;
  55338. /**
  55339. * The maximum number of particles to emit per frame
  55340. */
  55341. this.emitRate = 10;
  55342. /**
  55343. * If you want to launch only a few particles at once, that can be done, as well.
  55344. */
  55345. this.manualEmitCount = -1;
  55346. /**
  55347. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55348. */
  55349. this.updateSpeed = 0.01;
  55350. /**
  55351. * The amount of time the particle system is running (depends of the overall update speed).
  55352. */
  55353. this.targetStopDuration = 0;
  55354. /**
  55355. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55356. */
  55357. this.disposeOnStop = false;
  55358. /**
  55359. * Minimum power of emitting particles.
  55360. */
  55361. this.minEmitPower = 1;
  55362. /**
  55363. * Maximum power of emitting particles.
  55364. */
  55365. this.maxEmitPower = 1;
  55366. /**
  55367. * Minimum life time of emitting particles.
  55368. */
  55369. this.minLifeTime = 1;
  55370. /**
  55371. * Maximum life time of emitting particles.
  55372. */
  55373. this.maxLifeTime = 1;
  55374. /**
  55375. * Minimum Size of emitting particles.
  55376. */
  55377. this.minSize = 1;
  55378. /**
  55379. * Maximum Size of emitting particles.
  55380. */
  55381. this.maxSize = 1;
  55382. /**
  55383. * Minimum scale of emitting particles on X axis.
  55384. */
  55385. this.minScaleX = 1;
  55386. /**
  55387. * Maximum scale of emitting particles on X axis.
  55388. */
  55389. this.maxScaleX = 1;
  55390. /**
  55391. * Minimum scale of emitting particles on Y axis.
  55392. */
  55393. this.minScaleY = 1;
  55394. /**
  55395. * Maximum scale of emitting particles on Y axis.
  55396. */
  55397. this.maxScaleY = 1;
  55398. /**
  55399. * Gets or sets the minimal initial rotation in radians.
  55400. */
  55401. this.minInitialRotation = 0;
  55402. /**
  55403. * Gets or sets the maximal initial rotation in radians.
  55404. */
  55405. this.maxInitialRotation = 0;
  55406. /**
  55407. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55408. */
  55409. this.minAngularSpeed = 0;
  55410. /**
  55411. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55412. */
  55413. this.maxAngularSpeed = 0;
  55414. /**
  55415. * The layer mask we are rendering the particles through.
  55416. */
  55417. this.layerMask = 0x0FFFFFFF;
  55418. /**
  55419. * This can help using your own shader to render the particle system.
  55420. * The according effect will be created
  55421. */
  55422. this.customShader = null;
  55423. /**
  55424. * By default particle system starts as soon as they are created. This prevents the
  55425. * automatic start to happen and let you decide when to start emitting particles.
  55426. */
  55427. this.preventAutoStart = false;
  55428. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55429. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55430. /**
  55431. * Callback triggered when the particle animation is ending.
  55432. */
  55433. this.onAnimationEnd = null;
  55434. /**
  55435. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55436. */
  55437. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55438. /**
  55439. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55440. * to override the particles.
  55441. */
  55442. this.forceDepthWrite = false;
  55443. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55444. this.preWarmCycles = 0;
  55445. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55446. this.preWarmStepOffset = 1;
  55447. /**
  55448. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55449. */
  55450. this.spriteCellChangeSpeed = 1;
  55451. /**
  55452. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55453. */
  55454. this.startSpriteCellID = 0;
  55455. /**
  55456. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55457. */
  55458. this.endSpriteCellID = 0;
  55459. /**
  55460. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55461. */
  55462. this.spriteCellWidth = 0;
  55463. /**
  55464. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55465. */
  55466. this.spriteCellHeight = 0;
  55467. /**
  55468. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55469. */
  55470. this.spriteRandomStartCell = false;
  55471. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55472. this.translationPivot = new BABYLON.Vector2(0, 0);
  55473. /**
  55474. * You can use gravity if you want to give an orientation to your particles.
  55475. */
  55476. this.gravity = BABYLON.Vector3.Zero();
  55477. this._colorGradients = null;
  55478. this._sizeGradients = null;
  55479. this._lifeTimeGradients = null;
  55480. this._angularSpeedGradients = null;
  55481. this._velocityGradients = null;
  55482. this._limitVelocityGradients = null;
  55483. this._dragGradients = null;
  55484. this._emitRateGradients = null;
  55485. this._startSizeGradients = null;
  55486. this._rampGradients = null;
  55487. this._colorRemapGradients = null;
  55488. this._alphaRemapGradients = null;
  55489. /**
  55490. * Defines the delay in milliseconds before starting the system (0 by default)
  55491. */
  55492. this.startDelay = 0;
  55493. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55494. this.limitVelocityDamping = 0.4;
  55495. /**
  55496. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55497. */
  55498. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55499. /**
  55500. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55501. */
  55502. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55503. /**
  55504. * Color the particle will have at the end of its lifetime
  55505. */
  55506. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55507. /**
  55508. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55509. */
  55510. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55511. /**
  55512. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55513. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55514. */
  55515. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55516. this._isBillboardBased = true;
  55517. /**
  55518. * Local cache of defines for image processing.
  55519. */
  55520. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55521. this.id = name;
  55522. this.name = name;
  55523. }
  55524. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55525. /**
  55526. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55527. */
  55528. get: function () {
  55529. return this._isAnimationSheetEnabled;
  55530. },
  55531. set: function (value) {
  55532. if (this._isAnimationSheetEnabled == value) {
  55533. return;
  55534. }
  55535. this._isAnimationSheetEnabled = value;
  55536. this._reset();
  55537. },
  55538. enumerable: true,
  55539. configurable: true
  55540. });
  55541. /**
  55542. * Get hosting scene
  55543. * @returns the scene
  55544. */
  55545. BaseParticleSystem.prototype.getScene = function () {
  55546. return this._scene;
  55547. };
  55548. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  55549. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  55550. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  55551. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  55552. };
  55553. /**
  55554. * Gets the current list of drag gradients.
  55555. * You must use addDragGradient and removeDragGradient to udpate this list
  55556. * @returns the list of drag gradients
  55557. */
  55558. BaseParticleSystem.prototype.getDragGradients = function () {
  55559. return this._dragGradients;
  55560. };
  55561. /**
  55562. * Gets the current list of limit velocity gradients.
  55563. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55564. * @returns the list of limit velocity gradients
  55565. */
  55566. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55567. return this._limitVelocityGradients;
  55568. };
  55569. /**
  55570. * Gets the current list of color gradients.
  55571. * You must use addColorGradient and removeColorGradient to udpate this list
  55572. * @returns the list of color gradients
  55573. */
  55574. BaseParticleSystem.prototype.getColorGradients = function () {
  55575. return this._colorGradients;
  55576. };
  55577. /**
  55578. * Gets the current list of size gradients.
  55579. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55580. * @returns the list of size gradients
  55581. */
  55582. BaseParticleSystem.prototype.getSizeGradients = function () {
  55583. return this._sizeGradients;
  55584. };
  55585. /**
  55586. * Gets the current list of color remap gradients.
  55587. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  55588. * @returns the list of color remap gradients
  55589. */
  55590. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  55591. return this._colorRemapGradients;
  55592. };
  55593. /**
  55594. * Gets the current list of alpha remap gradients.
  55595. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  55596. * @returns the list of alpha remap gradients
  55597. */
  55598. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  55599. return this._alphaRemapGradients;
  55600. };
  55601. /**
  55602. * Gets the current list of life time gradients.
  55603. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55604. * @returns the list of life time gradients
  55605. */
  55606. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55607. return this._lifeTimeGradients;
  55608. };
  55609. /**
  55610. * Gets the current list of angular speed gradients.
  55611. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55612. * @returns the list of angular speed gradients
  55613. */
  55614. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55615. return this._angularSpeedGradients;
  55616. };
  55617. /**
  55618. * Gets the current list of velocity gradients.
  55619. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55620. * @returns the list of velocity gradients
  55621. */
  55622. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55623. return this._velocityGradients;
  55624. };
  55625. /**
  55626. * Gets the current list of start size gradients.
  55627. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55628. * @returns the list of start size gradients
  55629. */
  55630. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55631. return this._startSizeGradients;
  55632. };
  55633. /**
  55634. * Gets the current list of emit rate gradients.
  55635. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55636. * @returns the list of emit rate gradients
  55637. */
  55638. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55639. return this._emitRateGradients;
  55640. };
  55641. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55642. /**
  55643. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55644. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55645. */
  55646. get: function () {
  55647. if (this.particleEmitterType.direction1) {
  55648. return this.particleEmitterType.direction1;
  55649. }
  55650. return BABYLON.Vector3.Zero();
  55651. },
  55652. set: function (value) {
  55653. if (this.particleEmitterType.direction1) {
  55654. this.particleEmitterType.direction1 = value;
  55655. }
  55656. },
  55657. enumerable: true,
  55658. configurable: true
  55659. });
  55660. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55661. /**
  55662. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55663. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55664. */
  55665. get: function () {
  55666. if (this.particleEmitterType.direction2) {
  55667. return this.particleEmitterType.direction2;
  55668. }
  55669. return BABYLON.Vector3.Zero();
  55670. },
  55671. set: function (value) {
  55672. if (this.particleEmitterType.direction2) {
  55673. this.particleEmitterType.direction2 = value;
  55674. }
  55675. },
  55676. enumerable: true,
  55677. configurable: true
  55678. });
  55679. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55680. /**
  55681. * 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.
  55682. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55683. */
  55684. get: function () {
  55685. if (this.particleEmitterType.minEmitBox) {
  55686. return this.particleEmitterType.minEmitBox;
  55687. }
  55688. return BABYLON.Vector3.Zero();
  55689. },
  55690. set: function (value) {
  55691. if (this.particleEmitterType.minEmitBox) {
  55692. this.particleEmitterType.minEmitBox = value;
  55693. }
  55694. },
  55695. enumerable: true,
  55696. configurable: true
  55697. });
  55698. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55699. /**
  55700. * 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.
  55701. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55702. */
  55703. get: function () {
  55704. if (this.particleEmitterType.maxEmitBox) {
  55705. return this.particleEmitterType.maxEmitBox;
  55706. }
  55707. return BABYLON.Vector3.Zero();
  55708. },
  55709. set: function (value) {
  55710. if (this.particleEmitterType.maxEmitBox) {
  55711. this.particleEmitterType.maxEmitBox = value;
  55712. }
  55713. },
  55714. enumerable: true,
  55715. configurable: true
  55716. });
  55717. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55718. /**
  55719. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55720. */
  55721. get: function () {
  55722. return this._isBillboardBased;
  55723. },
  55724. set: function (value) {
  55725. if (this._isBillboardBased === value) {
  55726. return;
  55727. }
  55728. this._isBillboardBased = value;
  55729. this._reset();
  55730. },
  55731. enumerable: true,
  55732. configurable: true
  55733. });
  55734. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55735. /**
  55736. * Gets the image processing configuration used either in this material.
  55737. */
  55738. get: function () {
  55739. return this._imageProcessingConfiguration;
  55740. },
  55741. /**
  55742. * Sets the Default image processing configuration used either in the this material.
  55743. *
  55744. * If sets to null, the scene one is in use.
  55745. */
  55746. set: function (value) {
  55747. this._attachImageProcessingConfiguration(value);
  55748. },
  55749. enumerable: true,
  55750. configurable: true
  55751. });
  55752. /**
  55753. * Attaches a new image processing configuration to the Standard Material.
  55754. * @param configuration
  55755. */
  55756. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55757. if (configuration === this._imageProcessingConfiguration) {
  55758. return;
  55759. }
  55760. // Pick the scene configuration if needed.
  55761. if (!configuration) {
  55762. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55763. }
  55764. else {
  55765. this._imageProcessingConfiguration = configuration;
  55766. }
  55767. };
  55768. /** @hidden */
  55769. BaseParticleSystem.prototype._reset = function () {
  55770. };
  55771. /** @hidden */
  55772. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  55773. if (!gradients) {
  55774. return this;
  55775. }
  55776. var index = 0;
  55777. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  55778. var valueGradient = gradients_1[_i];
  55779. if (valueGradient.gradient === gradient) {
  55780. gradients.splice(index, 1);
  55781. break;
  55782. }
  55783. index++;
  55784. }
  55785. if (texture) {
  55786. texture.dispose();
  55787. }
  55788. return this;
  55789. };
  55790. /**
  55791. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55792. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55793. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55794. * @returns the emitter
  55795. */
  55796. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55797. var particleEmitter = new BABYLON.PointParticleEmitter();
  55798. particleEmitter.direction1 = direction1;
  55799. particleEmitter.direction2 = direction2;
  55800. this.particleEmitterType = particleEmitter;
  55801. return particleEmitter;
  55802. };
  55803. /**
  55804. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55805. * @param radius The radius of the hemisphere to emit from
  55806. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55807. * @returns the emitter
  55808. */
  55809. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  55810. if (radius === void 0) { radius = 1; }
  55811. if (radiusRange === void 0) { radiusRange = 1; }
  55812. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  55813. this.particleEmitterType = particleEmitter;
  55814. return particleEmitter;
  55815. };
  55816. /**
  55817. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  55818. * @param radius The radius of the sphere to emit from
  55819. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55820. * @returns the emitter
  55821. */
  55822. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  55823. if (radius === void 0) { radius = 1; }
  55824. if (radiusRange === void 0) { radiusRange = 1; }
  55825. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  55826. this.particleEmitterType = particleEmitter;
  55827. return particleEmitter;
  55828. };
  55829. /**
  55830. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  55831. * @param radius The radius of the sphere to emit from
  55832. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55833. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55834. * @returns the emitter
  55835. */
  55836. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55837. if (radius === void 0) { radius = 1; }
  55838. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55839. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55840. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55841. this.particleEmitterType = particleEmitter;
  55842. return particleEmitter;
  55843. };
  55844. /**
  55845. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  55846. * @param radius The radius of the emission cylinder
  55847. * @param height The height of the emission cylinder
  55848. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  55849. * @param directionRandomizer How much to randomize the particle direction [0-1]
  55850. * @returns the emitter
  55851. */
  55852. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  55853. if (radius === void 0) { radius = 1; }
  55854. if (height === void 0) { height = 1; }
  55855. if (radiusRange === void 0) { radiusRange = 1; }
  55856. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55857. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  55858. this.particleEmitterType = particleEmitter;
  55859. return particleEmitter;
  55860. };
  55861. /**
  55862. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  55863. * @param radius The radius of the cylinder to emit from
  55864. * @param height The height of the emission cylinder
  55865. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  55866. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  55867. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  55868. * @returns the emitter
  55869. */
  55870. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  55871. if (radius === void 0) { radius = 1; }
  55872. if (height === void 0) { height = 1; }
  55873. if (radiusRange === void 0) { radiusRange = 1; }
  55874. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55875. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55876. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  55877. this.particleEmitterType = particleEmitter;
  55878. return particleEmitter;
  55879. };
  55880. /**
  55881. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  55882. * @param radius The radius of the cone to emit from
  55883. * @param angle The base angle of the cone
  55884. * @returns the emitter
  55885. */
  55886. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55887. if (radius === void 0) { radius = 1; }
  55888. if (angle === void 0) { angle = Math.PI / 4; }
  55889. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55890. this.particleEmitterType = particleEmitter;
  55891. return particleEmitter;
  55892. };
  55893. /**
  55894. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55895. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55896. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55897. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55898. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55899. * @returns the emitter
  55900. */
  55901. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55902. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55903. this.particleEmitterType = particleEmitter;
  55904. this.direction1 = direction1;
  55905. this.direction2 = direction2;
  55906. this.minEmitBox = minEmitBox;
  55907. this.maxEmitBox = maxEmitBox;
  55908. return particleEmitter;
  55909. };
  55910. /**
  55911. * Source color is added to the destination color without alpha affecting the result
  55912. */
  55913. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  55914. /**
  55915. * Blend current color and particle color using particle’s alpha
  55916. */
  55917. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  55918. /**
  55919. * Add current color and particle color multiplied by particle’s alpha
  55920. */
  55921. BaseParticleSystem.BLENDMODE_ADD = 2;
  55922. /**
  55923. * Multiply current color with particle color
  55924. */
  55925. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  55926. /**
  55927. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  55928. */
  55929. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  55930. return BaseParticleSystem;
  55931. }());
  55932. BABYLON.BaseParticleSystem = BaseParticleSystem;
  55933. })(BABYLON || (BABYLON = {}));
  55934. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  55935. var BABYLON;
  55936. (function (BABYLON) {
  55937. /**
  55938. * This represents a particle system in Babylon.
  55939. * 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.
  55940. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55941. * @example https://doc.babylonjs.com/babylon101/particles
  55942. */
  55943. var ParticleSystem = /** @class */ (function (_super) {
  55944. __extends(ParticleSystem, _super);
  55945. /**
  55946. * Instantiates a particle system.
  55947. * 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.
  55948. * @param name The name of the particle system
  55949. * @param capacity The max number of particles alive at the same time
  55950. * @param scene The scene the particle system belongs to
  55951. * @param customEffect a custom effect used to change the way particles are rendered by default
  55952. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55953. * @param epsilon Offset used to render the particles
  55954. */
  55955. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55956. if (customEffect === void 0) { customEffect = null; }
  55957. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55958. if (epsilon === void 0) { epsilon = 0.01; }
  55959. var _this = _super.call(this, name) || this;
  55960. /**
  55961. * @hidden
  55962. */
  55963. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  55964. /**
  55965. * An event triggered when the system is disposed
  55966. */
  55967. _this.onDisposeObservable = new BABYLON.Observable();
  55968. _this._particles = new Array();
  55969. _this._stockParticles = new Array();
  55970. _this._newPartsExcess = 0;
  55971. _this._vertexBuffers = {};
  55972. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55973. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55974. _this._scaledDirection = BABYLON.Vector3.Zero();
  55975. _this._scaledGravity = BABYLON.Vector3.Zero();
  55976. _this._currentRenderId = -1;
  55977. _this._useInstancing = false;
  55978. _this._started = false;
  55979. _this._stopped = false;
  55980. _this._actualFrame = 0;
  55981. /** @hidden */
  55982. _this._currentEmitRate1 = 0;
  55983. /** @hidden */
  55984. _this._currentEmitRate2 = 0;
  55985. /** @hidden */
  55986. _this._currentStartSize1 = 0;
  55987. /** @hidden */
  55988. _this._currentStartSize2 = 0;
  55989. _this._rawTextureWidth = 256;
  55990. _this._useRampGradients = false;
  55991. /**
  55992. * @hidden
  55993. * If the particle systems emitter should be disposed when the particle system is disposed
  55994. */
  55995. _this._disposeEmitterOnDispose = false;
  55996. // start of sub system methods
  55997. /**
  55998. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55999. * Its lifetime will start back at 0.
  56000. */
  56001. _this.recycleParticle = function (particle) {
  56002. // move particle from activeParticle list to stock particles
  56003. var lastParticle = _this._particles.pop();
  56004. if (lastParticle !== particle) {
  56005. lastParticle.copyTo(particle);
  56006. }
  56007. _this._stockParticles.push(lastParticle);
  56008. };
  56009. _this._createParticle = function () {
  56010. var particle;
  56011. if (_this._stockParticles.length !== 0) {
  56012. particle = _this._stockParticles.pop();
  56013. particle._reset();
  56014. }
  56015. else {
  56016. particle = new BABYLON.Particle(_this);
  56017. }
  56018. // Attach emitters
  56019. if (_this._subEmitters && _this._subEmitters.length > 0) {
  56020. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  56021. particle._attachedSubEmitters = [];
  56022. subEmitters.forEach(function (subEmitter) {
  56023. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  56024. var newEmitter = subEmitter.clone();
  56025. particle._attachedSubEmitters.push(newEmitter);
  56026. newEmitter.particleSystem.start();
  56027. }
  56028. });
  56029. }
  56030. return particle;
  56031. };
  56032. _this._emitFromParticle = function (particle) {
  56033. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  56034. return;
  56035. }
  56036. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  56037. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  56038. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  56039. var subSystem = subEmitter.clone();
  56040. ParticleSystem._InheritParticleInfoToSubEmitter(subSystem, particle);
  56041. subSystem.particleSystem._rootParticleSystem = _this;
  56042. _this.activeSubSystems.push(subSystem.particleSystem);
  56043. subSystem.particleSystem.start();
  56044. }
  56045. });
  56046. };
  56047. _this._capacity = capacity;
  56048. _this._epsilon = epsilon;
  56049. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56050. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56051. // Setup the default processing configuration to the scene.
  56052. _this._attachImageProcessingConfiguration(null);
  56053. _this._customEffect = customEffect;
  56054. _this._scene.particleSystems.push(_this);
  56055. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56056. _this._createIndexBuffer();
  56057. _this._createVertexBuffers();
  56058. // Default emitter type
  56059. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56060. // Update
  56061. _this.updateFunction = function (particles) {
  56062. var noiseTextureSize = null;
  56063. var noiseTextureData = null;
  56064. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56065. noiseTextureSize = _this.noiseTexture.getSize();
  56066. noiseTextureData = (_this.noiseTexture.getContent());
  56067. }
  56068. var _loop_1 = function () {
  56069. particle = particles[index];
  56070. particle.age += _this._scaledUpdateSpeed;
  56071. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56072. _this._emitFromParticle(particle);
  56073. if (particle._attachedSubEmitters) {
  56074. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56075. subEmitter.particleSystem.disposeOnStop = true;
  56076. subEmitter.particleSystem.stop();
  56077. });
  56078. particle._attachedSubEmitters = null;
  56079. }
  56080. _this.recycleParticle(particle);
  56081. index--;
  56082. return "continue";
  56083. }
  56084. else {
  56085. var ratio = particle.age / particle.lifeTime;
  56086. // Color
  56087. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56088. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56089. if (currentGradient !== particle._currentColorGradient) {
  56090. particle._currentColor1.copyFrom(particle._currentColor2);
  56091. nextGradient.getColorToRef(particle._currentColor2);
  56092. particle._currentColorGradient = currentGradient;
  56093. }
  56094. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56095. });
  56096. }
  56097. else {
  56098. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56099. particle.color.addInPlace(_this._scaledColorStep);
  56100. if (particle.color.a < 0) {
  56101. particle.color.a = 0;
  56102. }
  56103. }
  56104. // Angular speed
  56105. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56106. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56107. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56108. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56109. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56110. particle._currentAngularSpeedGradient = currentGradient;
  56111. }
  56112. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56113. });
  56114. }
  56115. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56116. // Direction
  56117. var directionScale_1 = _this._scaledUpdateSpeed;
  56118. /// Velocity
  56119. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56120. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56121. if (currentGradient !== particle._currentVelocityGradient) {
  56122. particle._currentVelocity1 = particle._currentVelocity2;
  56123. particle._currentVelocity2 = nextGradient.getFactor();
  56124. particle._currentVelocityGradient = currentGradient;
  56125. }
  56126. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56127. });
  56128. }
  56129. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56130. /// Limit velocity
  56131. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56132. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56133. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56134. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56135. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56136. particle._currentLimitVelocityGradient = currentGradient;
  56137. }
  56138. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56139. var currentVelocity = particle.direction.length();
  56140. if (currentVelocity > limitVelocity) {
  56141. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56142. }
  56143. });
  56144. }
  56145. /// Drag
  56146. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56147. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56148. if (currentGradient !== particle._currentDragGradient) {
  56149. particle._currentDrag1 = particle._currentDrag2;
  56150. particle._currentDrag2 = nextGradient.getFactor();
  56151. particle._currentDragGradient = currentGradient;
  56152. }
  56153. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56154. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56155. });
  56156. }
  56157. particle.position.addInPlace(_this._scaledDirection);
  56158. // Noise
  56159. if (noiseTextureData && noiseTextureSize) {
  56160. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56161. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56162. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56163. var force = BABYLON.Tmp.Vector3[0];
  56164. var scaledForce = BABYLON.Tmp.Vector3[1];
  56165. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56166. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56167. particle.direction.addInPlace(scaledForce);
  56168. }
  56169. // Gravity
  56170. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56171. particle.direction.addInPlace(_this._scaledGravity);
  56172. // Size
  56173. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56174. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56175. if (currentGradient !== particle._currentSizeGradient) {
  56176. particle._currentSize1 = particle._currentSize2;
  56177. particle._currentSize2 = nextGradient.getFactor();
  56178. particle._currentSizeGradient = currentGradient;
  56179. }
  56180. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56181. });
  56182. }
  56183. // Remap data
  56184. if (_this._useRampGradients) {
  56185. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  56186. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  56187. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56188. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56189. particle.remapData.x = min;
  56190. particle.remapData.y = max - min;
  56191. });
  56192. }
  56193. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  56194. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  56195. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56196. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56197. particle.remapData.z = min;
  56198. particle.remapData.w = max - min;
  56199. });
  56200. }
  56201. }
  56202. if (_this._isAnimationSheetEnabled) {
  56203. particle.updateCellIndex();
  56204. }
  56205. // Update the position of the attached sub-emitters to match their attached particle
  56206. if (particle._attachedSubEmitters && particle._attachedSubEmitters.length > 0) {
  56207. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56208. ParticleSystem._InheritParticleInfoToSubEmitter(subEmitter, particle);
  56209. });
  56210. }
  56211. }
  56212. };
  56213. var particle;
  56214. for (var index = 0; index < particles.length; index++) {
  56215. _loop_1();
  56216. }
  56217. };
  56218. return _this;
  56219. }
  56220. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56221. /**
  56222. * Sets a callback that will be triggered when the system is disposed
  56223. */
  56224. set: function (callback) {
  56225. if (this._onDisposeObserver) {
  56226. this.onDisposeObservable.remove(this._onDisposeObserver);
  56227. }
  56228. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56229. },
  56230. enumerable: true,
  56231. configurable: true
  56232. });
  56233. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  56234. /** Gets or sets a boolean indicating that ramp gradients must be used
  56235. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  56236. */
  56237. get: function () {
  56238. return this._useRampGradients;
  56239. },
  56240. set: function (value) {
  56241. if (this._useRampGradients === value) {
  56242. return;
  56243. }
  56244. this._useRampGradients = value;
  56245. this._resetEffect();
  56246. },
  56247. enumerable: true,
  56248. configurable: true
  56249. });
  56250. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56251. //end of Sub-emitter
  56252. /**
  56253. * Gets the current list of active particles
  56254. */
  56255. get: function () {
  56256. return this._particles;
  56257. },
  56258. enumerable: true,
  56259. configurable: true
  56260. });
  56261. /**
  56262. * Returns the string "ParticleSystem"
  56263. * @returns a string containing the class name
  56264. */
  56265. ParticleSystem.prototype.getClassName = function () {
  56266. return "ParticleSystem";
  56267. };
  56268. ParticleSystem._InheritParticleInfoToSubEmitter = function (subEmitter, particle) {
  56269. if (subEmitter.particleSystem.emitter.position) {
  56270. var emitterMesh = subEmitter.particleSystem.emitter;
  56271. emitterMesh.position.copyFrom(particle.position);
  56272. if (subEmitter.inheritDirection) {
  56273. emitterMesh.position.subtractToRef(particle.direction, BABYLON.Tmp.Vector3[0]);
  56274. // Look at using Y as forward
  56275. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56276. }
  56277. }
  56278. else {
  56279. var emitterPosition = subEmitter.particleSystem.emitter;
  56280. emitterPosition.copyFrom(particle.position);
  56281. }
  56282. // Set inheritedVelocityOffset to be used when new particles are created
  56283. particle.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56284. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56285. };
  56286. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56287. var newGradient = new BABYLON.FactorGradient();
  56288. newGradient.gradient = gradient;
  56289. newGradient.factor1 = factor;
  56290. newGradient.factor2 = factor2;
  56291. factorGradients.push(newGradient);
  56292. factorGradients.sort(function (a, b) {
  56293. if (a.gradient < b.gradient) {
  56294. return -1;
  56295. }
  56296. else if (a.gradient > b.gradient) {
  56297. return 1;
  56298. }
  56299. return 0;
  56300. });
  56301. };
  56302. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56303. if (!factorGradients) {
  56304. return;
  56305. }
  56306. var index = 0;
  56307. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56308. var factorGradient = factorGradients_1[_i];
  56309. if (factorGradient.gradient === gradient) {
  56310. factorGradients.splice(index, 1);
  56311. break;
  56312. }
  56313. index++;
  56314. }
  56315. };
  56316. /**
  56317. * Adds a new life time gradient
  56318. * @param gradient defines the gradient to use (between 0 and 1)
  56319. * @param factor defines the life time factor to affect to the specified gradient
  56320. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56321. * @returns the current particle system
  56322. */
  56323. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56324. if (!this._lifeTimeGradients) {
  56325. this._lifeTimeGradients = [];
  56326. }
  56327. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56328. return this;
  56329. };
  56330. /**
  56331. * Remove a specific life time gradient
  56332. * @param gradient defines the gradient to remove
  56333. * @returns the current particle system
  56334. */
  56335. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56336. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56337. return this;
  56338. };
  56339. /**
  56340. * Adds a new size gradient
  56341. * @param gradient defines the gradient to use (between 0 and 1)
  56342. * @param factor defines the size factor to affect to the specified gradient
  56343. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56344. * @returns the current particle system
  56345. */
  56346. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56347. if (!this._sizeGradients) {
  56348. this._sizeGradients = [];
  56349. }
  56350. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56351. return this;
  56352. };
  56353. /**
  56354. * Remove a specific size gradient
  56355. * @param gradient defines the gradient to remove
  56356. * @returns the current particle system
  56357. */
  56358. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56359. this._removeFactorGradient(this._sizeGradients, gradient);
  56360. return this;
  56361. };
  56362. /**
  56363. * Adds a new color remap gradient
  56364. * @param gradient defines the gradient to use (between 0 and 1)
  56365. * @param min defines the color remap minimal range
  56366. * @param max defines the color remap maximal range
  56367. * @returns the current particle system
  56368. */
  56369. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  56370. if (!this._colorRemapGradients) {
  56371. this._colorRemapGradients = [];
  56372. }
  56373. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  56374. return this;
  56375. };
  56376. /**
  56377. * Remove a specific color remap gradient
  56378. * @param gradient defines the gradient to remove
  56379. * @returns the current particle system
  56380. */
  56381. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  56382. this._removeFactorGradient(this._colorRemapGradients, gradient);
  56383. return this;
  56384. };
  56385. /**
  56386. * Adds a new alpha remap gradient
  56387. * @param gradient defines the gradient to use (between 0 and 1)
  56388. * @param min defines the alpha remap minimal range
  56389. * @param max defines the alpha remap maximal range
  56390. * @returns the current particle system
  56391. */
  56392. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  56393. if (!this._alphaRemapGradients) {
  56394. this._alphaRemapGradients = [];
  56395. }
  56396. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  56397. return this;
  56398. };
  56399. /**
  56400. * Remove a specific alpha remap gradient
  56401. * @param gradient defines the gradient to remove
  56402. * @returns the current particle system
  56403. */
  56404. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  56405. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  56406. return this;
  56407. };
  56408. /**
  56409. * Adds a new angular speed gradient
  56410. * @param gradient defines the gradient to use (between 0 and 1)
  56411. * @param factor defines the angular speed to affect to the specified gradient
  56412. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56413. * @returns the current particle system
  56414. */
  56415. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56416. if (!this._angularSpeedGradients) {
  56417. this._angularSpeedGradients = [];
  56418. }
  56419. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56420. return this;
  56421. };
  56422. /**
  56423. * Remove a specific angular speed gradient
  56424. * @param gradient defines the gradient to remove
  56425. * @returns the current particle system
  56426. */
  56427. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56428. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56429. return this;
  56430. };
  56431. /**
  56432. * Adds a new velocity gradient
  56433. * @param gradient defines the gradient to use (between 0 and 1)
  56434. * @param factor defines the velocity to affect to the specified gradient
  56435. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56436. * @returns the current particle system
  56437. */
  56438. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56439. if (!this._velocityGradients) {
  56440. this._velocityGradients = [];
  56441. }
  56442. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56443. return this;
  56444. };
  56445. /**
  56446. * Remove a specific velocity gradient
  56447. * @param gradient defines the gradient to remove
  56448. * @returns the current particle system
  56449. */
  56450. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56451. this._removeFactorGradient(this._velocityGradients, gradient);
  56452. return this;
  56453. };
  56454. /**
  56455. * Adds a new limit velocity gradient
  56456. * @param gradient defines the gradient to use (between 0 and 1)
  56457. * @param factor defines the limit velocity value to affect to the specified gradient
  56458. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56459. * @returns the current particle system
  56460. */
  56461. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56462. if (!this._limitVelocityGradients) {
  56463. this._limitVelocityGradients = [];
  56464. }
  56465. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56466. return this;
  56467. };
  56468. /**
  56469. * Remove a specific limit velocity gradient
  56470. * @param gradient defines the gradient to remove
  56471. * @returns the current particle system
  56472. */
  56473. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56474. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56475. return this;
  56476. };
  56477. /**
  56478. * Adds a new drag gradient
  56479. * @param gradient defines the gradient to use (between 0 and 1)
  56480. * @param factor defines the drag value to affect to the specified gradient
  56481. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56482. * @returns the current particle system
  56483. */
  56484. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56485. if (!this._dragGradients) {
  56486. this._dragGradients = [];
  56487. }
  56488. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56489. return this;
  56490. };
  56491. /**
  56492. * Remove a specific drag gradient
  56493. * @param gradient defines the gradient to remove
  56494. * @returns the current particle system
  56495. */
  56496. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56497. this._removeFactorGradient(this._dragGradients, gradient);
  56498. return this;
  56499. };
  56500. /**
  56501. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56502. * @param gradient defines the gradient to use (between 0 and 1)
  56503. * @param factor defines the emit rate value to affect to the specified gradient
  56504. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56505. * @returns the current particle system
  56506. */
  56507. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56508. if (!this._emitRateGradients) {
  56509. this._emitRateGradients = [];
  56510. }
  56511. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56512. if (!this._currentEmitRateGradient) {
  56513. this._currentEmitRateGradient = this._emitRateGradients[0];
  56514. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56515. this._currentEmitRate2 = this._currentEmitRate1;
  56516. }
  56517. if (this._emitRateGradients.length === 2) {
  56518. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56519. }
  56520. return this;
  56521. };
  56522. /**
  56523. * Remove a specific emit rate gradient
  56524. * @param gradient defines the gradient to remove
  56525. * @returns the current particle system
  56526. */
  56527. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56528. this._removeFactorGradient(this._emitRateGradients, gradient);
  56529. return this;
  56530. };
  56531. /**
  56532. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56533. * @param gradient defines the gradient to use (between 0 and 1)
  56534. * @param factor defines the start size value to affect to the specified gradient
  56535. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56536. * @returns the current particle system
  56537. */
  56538. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56539. if (!this._startSizeGradients) {
  56540. this._startSizeGradients = [];
  56541. }
  56542. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56543. if (!this._currentStartSizeGradient) {
  56544. this._currentStartSizeGradient = this._startSizeGradients[0];
  56545. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56546. this._currentStartSize2 = this._currentStartSize1;
  56547. }
  56548. if (this._startSizeGradients.length === 2) {
  56549. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56550. }
  56551. return this;
  56552. };
  56553. /**
  56554. * Remove a specific start size gradient
  56555. * @param gradient defines the gradient to remove
  56556. * @returns the current particle system
  56557. */
  56558. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56559. this._removeFactorGradient(this._emitRateGradients, gradient);
  56560. return this;
  56561. };
  56562. ParticleSystem.prototype._createRampGradientTexture = function () {
  56563. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  56564. return;
  56565. }
  56566. var data = new Uint8Array(this._rawTextureWidth * 4);
  56567. var tmpColor = BABYLON.Tmp.Color3[0];
  56568. for (var x = 0; x < this._rawTextureWidth; x++) {
  56569. var ratio = x / this._rawTextureWidth;
  56570. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  56571. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  56572. data[x * 4] = tmpColor.r * 255;
  56573. data[x * 4 + 1] = tmpColor.g * 255;
  56574. data[x * 4 + 2] = tmpColor.b * 255;
  56575. data[x * 4 + 3] = 255;
  56576. });
  56577. }
  56578. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56579. };
  56580. /**
  56581. * Gets the current list of ramp gradients.
  56582. * You must use addRampGradient and removeRampGradient to udpate this list
  56583. * @returns the list of ramp gradients
  56584. */
  56585. ParticleSystem.prototype.getRampGradients = function () {
  56586. return this._rampGradients;
  56587. };
  56588. /**
  56589. * Adds a new ramp gradient used to remap particle colors
  56590. * @param gradient defines the gradient to use (between 0 and 1)
  56591. * @param color defines the color to affect to the specified gradient
  56592. * @returns the current particle system
  56593. */
  56594. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  56595. if (!this._rampGradients) {
  56596. this._rampGradients = [];
  56597. }
  56598. var rampGradient = new BABYLON.Color3Gradient();
  56599. rampGradient.gradient = gradient;
  56600. rampGradient.color = color;
  56601. this._rampGradients.push(rampGradient);
  56602. this._rampGradients.sort(function (a, b) {
  56603. if (a.gradient < b.gradient) {
  56604. return -1;
  56605. }
  56606. else if (a.gradient > b.gradient) {
  56607. return 1;
  56608. }
  56609. return 0;
  56610. });
  56611. if (this._rampGradientsTexture) {
  56612. this._rampGradientsTexture.dispose();
  56613. this._rampGradientsTexture = null;
  56614. }
  56615. this._createRampGradientTexture();
  56616. return this;
  56617. };
  56618. /**
  56619. * Remove a specific ramp gradient
  56620. * @param gradient defines the gradient to remove
  56621. * @returns the current particle system
  56622. */
  56623. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  56624. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  56625. this._rampGradientsTexture = null;
  56626. if (this._rampGradients && this._rampGradients.length > 0) {
  56627. this._createRampGradientTexture();
  56628. }
  56629. return this;
  56630. };
  56631. /**
  56632. * Adds a new color gradient
  56633. * @param gradient defines the gradient to use (between 0 and 1)
  56634. * @param color defines the color to affect to the specified gradient
  56635. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56636. */
  56637. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56638. if (!this._colorGradients) {
  56639. this._colorGradients = [];
  56640. }
  56641. var colorGradient = new BABYLON.ColorGradient();
  56642. colorGradient.gradient = gradient;
  56643. colorGradient.color1 = color;
  56644. colorGradient.color2 = color2;
  56645. this._colorGradients.push(colorGradient);
  56646. this._colorGradients.sort(function (a, b) {
  56647. if (a.gradient < b.gradient) {
  56648. return -1;
  56649. }
  56650. else if (a.gradient > b.gradient) {
  56651. return 1;
  56652. }
  56653. return 0;
  56654. });
  56655. return this;
  56656. };
  56657. /**
  56658. * Remove a specific color gradient
  56659. * @param gradient defines the gradient to remove
  56660. */
  56661. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56662. if (!this._colorGradients) {
  56663. return this;
  56664. }
  56665. var index = 0;
  56666. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56667. var colorGradient = _a[_i];
  56668. if (colorGradient.gradient === gradient) {
  56669. this._colorGradients.splice(index, 1);
  56670. break;
  56671. }
  56672. index++;
  56673. }
  56674. return this;
  56675. };
  56676. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56677. u = Math.abs(u) * 0.5 + 0.5;
  56678. v = Math.abs(v) * 0.5 + 0.5;
  56679. var wrappedU = ((u * width) % width) | 0;
  56680. var wrappedV = ((v * height) % height) | 0;
  56681. var position = (wrappedU + wrappedV * width) * 4;
  56682. return pixels[position] / 255;
  56683. };
  56684. ParticleSystem.prototype._reset = function () {
  56685. this._resetEffect();
  56686. };
  56687. ParticleSystem.prototype._resetEffect = function () {
  56688. if (this._vertexBuffer) {
  56689. this._vertexBuffer.dispose();
  56690. this._vertexBuffer = null;
  56691. }
  56692. if (this._spriteBuffer) {
  56693. this._spriteBuffer.dispose();
  56694. this._spriteBuffer = null;
  56695. }
  56696. this._createVertexBuffers();
  56697. };
  56698. ParticleSystem.prototype._createVertexBuffers = function () {
  56699. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56700. if (this._isAnimationSheetEnabled) {
  56701. this._vertexBufferSize += 1;
  56702. }
  56703. if (!this._isBillboardBased) {
  56704. this._vertexBufferSize += 3;
  56705. }
  56706. if (this._useRampGradients) {
  56707. this._vertexBufferSize += 4;
  56708. }
  56709. var engine = this._scene.getEngine();
  56710. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56711. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56712. var dataOffset = 0;
  56713. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56714. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56715. dataOffset += 3;
  56716. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56717. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56718. dataOffset += 4;
  56719. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56720. this._vertexBuffers["angle"] = options;
  56721. dataOffset += 1;
  56722. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56723. this._vertexBuffers["size"] = size;
  56724. dataOffset += 2;
  56725. if (this._isAnimationSheetEnabled) {
  56726. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56727. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56728. dataOffset += 1;
  56729. }
  56730. if (!this._isBillboardBased) {
  56731. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56732. this._vertexBuffers["direction"] = directionBuffer;
  56733. dataOffset += 3;
  56734. }
  56735. if (this._useRampGradients) {
  56736. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56737. this._vertexBuffers["remapData"] = rampDataBuffer;
  56738. dataOffset += 4;
  56739. }
  56740. var offsets;
  56741. if (this._useInstancing) {
  56742. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56743. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56744. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56745. }
  56746. else {
  56747. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56748. dataOffset += 2;
  56749. }
  56750. this._vertexBuffers["offset"] = offsets;
  56751. };
  56752. ParticleSystem.prototype._createIndexBuffer = function () {
  56753. if (this._useInstancing) {
  56754. return;
  56755. }
  56756. var indices = [];
  56757. var index = 0;
  56758. for (var count = 0; count < this._capacity; count++) {
  56759. indices.push(index);
  56760. indices.push(index + 1);
  56761. indices.push(index + 2);
  56762. indices.push(index);
  56763. indices.push(index + 2);
  56764. indices.push(index + 3);
  56765. index += 4;
  56766. }
  56767. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56768. };
  56769. /**
  56770. * Gets the maximum number of particles active at the same time.
  56771. * @returns The max number of active particles.
  56772. */
  56773. ParticleSystem.prototype.getCapacity = function () {
  56774. return this._capacity;
  56775. };
  56776. /**
  56777. * Gets whether there are still active particles in the system.
  56778. * @returns True if it is alive, otherwise false.
  56779. */
  56780. ParticleSystem.prototype.isAlive = function () {
  56781. return this._alive;
  56782. };
  56783. /**
  56784. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56785. * @returns True if it has been started, otherwise false.
  56786. */
  56787. ParticleSystem.prototype.isStarted = function () {
  56788. return this._started;
  56789. };
  56790. /**
  56791. * Starts the particle system and begins to emit
  56792. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  56793. */
  56794. ParticleSystem.prototype.start = function (delay) {
  56795. var _this = this;
  56796. if (delay === void 0) { delay = this.startDelay; }
  56797. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  56798. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  56799. }
  56800. if (delay) {
  56801. setTimeout(function () {
  56802. _this.start(0);
  56803. }, delay);
  56804. return;
  56805. }
  56806. // Convert the subEmitters field to the constant type field _subEmitters
  56807. this._subEmitters = new Array();
  56808. if (this.subEmitters) {
  56809. this.subEmitters.forEach(function (subEmitter) {
  56810. if (subEmitter instanceof ParticleSystem) {
  56811. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  56812. }
  56813. else if (subEmitter instanceof BABYLON.SubEmitter) {
  56814. _this._subEmitters.push([subEmitter]);
  56815. }
  56816. else if (subEmitter instanceof Array) {
  56817. _this._subEmitters.push(subEmitter);
  56818. }
  56819. _this._subEmitters[_this._subEmitters.length - 1].forEach(function (se) {
  56820. if (!(se.particleSystem.emitter instanceof BABYLON.AbstractMesh) && se.inheritDirection) {
  56821. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  56822. }
  56823. });
  56824. });
  56825. }
  56826. this._started = true;
  56827. this._stopped = false;
  56828. this._actualFrame = 0;
  56829. if (this._subEmitters && this._subEmitters.length != 0) {
  56830. this.activeSubSystems = new Array();
  56831. }
  56832. if (this.preWarmCycles) {
  56833. var noiseTextureAsProcedural_1 = this.noiseTexture;
  56834. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  56835. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  56836. setTimeout(function () {
  56837. for (var index = 0; index < _this.preWarmCycles; index++) {
  56838. _this.animate(true);
  56839. noiseTextureAsProcedural_1.render();
  56840. }
  56841. });
  56842. });
  56843. }
  56844. else {
  56845. for (var index = 0; index < this.preWarmCycles; index++) {
  56846. this.animate(true);
  56847. }
  56848. }
  56849. }
  56850. };
  56851. /**
  56852. * Stops the particle system.
  56853. * @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.
  56854. */
  56855. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56856. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56857. this._stopped = true;
  56858. if (stopSubEmitters) {
  56859. this._stopSubEmitters();
  56860. }
  56861. };
  56862. // animation sheet
  56863. /**
  56864. * Remove all active particles
  56865. */
  56866. ParticleSystem.prototype.reset = function () {
  56867. this._stockParticles = [];
  56868. this._particles = [];
  56869. };
  56870. /**
  56871. * @hidden (for internal use only)
  56872. */
  56873. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56874. var offset = index * this._vertexBufferSize;
  56875. this._vertexData[offset++] = particle.position.x;
  56876. this._vertexData[offset++] = particle.position.y;
  56877. this._vertexData[offset++] = particle.position.z;
  56878. this._vertexData[offset++] = particle.color.r;
  56879. this._vertexData[offset++] = particle.color.g;
  56880. this._vertexData[offset++] = particle.color.b;
  56881. this._vertexData[offset++] = particle.color.a;
  56882. this._vertexData[offset++] = particle.angle;
  56883. this._vertexData[offset++] = particle.scale.x * particle.size;
  56884. this._vertexData[offset++] = particle.scale.y * particle.size;
  56885. if (this._isAnimationSheetEnabled) {
  56886. this._vertexData[offset++] = particle.cellIndex;
  56887. }
  56888. if (!this._isBillboardBased) {
  56889. if (particle._initialDirection) {
  56890. this._vertexData[offset++] = particle._initialDirection.x;
  56891. this._vertexData[offset++] = particle._initialDirection.y;
  56892. this._vertexData[offset++] = particle._initialDirection.z;
  56893. }
  56894. else {
  56895. this._vertexData[offset++] = particle.direction.x;
  56896. this._vertexData[offset++] = particle.direction.y;
  56897. this._vertexData[offset++] = particle.direction.z;
  56898. }
  56899. }
  56900. if (this._useRampGradients) {
  56901. this._vertexData[offset++] = particle.remapData.x;
  56902. this._vertexData[offset++] = particle.remapData.y;
  56903. this._vertexData[offset++] = particle.remapData.z;
  56904. this._vertexData[offset++] = particle.remapData.w;
  56905. }
  56906. if (!this._useInstancing) {
  56907. if (this._isAnimationSheetEnabled) {
  56908. if (offsetX === 0)
  56909. offsetX = this._epsilon;
  56910. else if (offsetX === 1)
  56911. offsetX = 1 - this._epsilon;
  56912. if (offsetY === 0)
  56913. offsetY = this._epsilon;
  56914. else if (offsetY === 1)
  56915. offsetY = 1 - this._epsilon;
  56916. }
  56917. this._vertexData[offset++] = offsetX;
  56918. this._vertexData[offset++] = offsetY;
  56919. }
  56920. };
  56921. ParticleSystem.prototype._stopSubEmitters = function () {
  56922. if (!this.activeSubSystems) {
  56923. return;
  56924. }
  56925. this.activeSubSystems.forEach(function (subSystem) {
  56926. subSystem.stop(true);
  56927. });
  56928. this.activeSubSystems = new Array();
  56929. };
  56930. ParticleSystem.prototype._removeFromRoot = function () {
  56931. if (!this._rootParticleSystem) {
  56932. return;
  56933. }
  56934. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56935. if (index !== -1) {
  56936. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56937. }
  56938. };
  56939. // End of sub system methods
  56940. ParticleSystem.prototype._update = function (newParticles) {
  56941. var _this = this;
  56942. // Update current
  56943. this._alive = this._particles.length > 0;
  56944. if (this.emitter.position) {
  56945. var emitterMesh = this.emitter;
  56946. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56947. }
  56948. else {
  56949. var emitterPosition = this.emitter;
  56950. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56951. }
  56952. this.updateFunction(this._particles);
  56953. // Add new ones
  56954. var particle;
  56955. var _loop_2 = function () {
  56956. if (this_1._particles.length === this_1._capacity) {
  56957. return "break";
  56958. }
  56959. particle = this_1._createParticle();
  56960. this_1._particles.push(particle);
  56961. // Emitter
  56962. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56963. if (this_1.startPositionFunction) {
  56964. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56965. }
  56966. else {
  56967. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56968. }
  56969. if (this_1.startDirectionFunction) {
  56970. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56971. }
  56972. else {
  56973. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56974. }
  56975. if (emitPower === 0) {
  56976. if (!particle._initialDirection) {
  56977. particle._initialDirection = particle.direction.clone();
  56978. }
  56979. else {
  56980. particle._initialDirection.copyFrom(particle.direction);
  56981. }
  56982. }
  56983. else {
  56984. particle._initialDirection = null;
  56985. }
  56986. particle.direction.scaleInPlace(emitPower);
  56987. // Life time
  56988. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56989. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56990. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56991. var factorGradient1 = currentGradient;
  56992. var factorGradient2 = nextGradient;
  56993. var lifeTime1 = factorGradient1.getFactor();
  56994. var lifeTime2 = factorGradient2.getFactor();
  56995. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56996. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56997. });
  56998. }
  56999. else {
  57000. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  57001. }
  57002. // Size
  57003. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  57004. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  57005. }
  57006. else {
  57007. particle._currentSizeGradient = this_1._sizeGradients[0];
  57008. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  57009. particle.size = particle._currentSize1;
  57010. if (this_1._sizeGradients.length > 1) {
  57011. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  57012. }
  57013. else {
  57014. particle._currentSize2 = particle._currentSize1;
  57015. }
  57016. }
  57017. // Size and scale
  57018. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  57019. // Adjust scale by start size
  57020. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  57021. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  57022. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  57023. if (currentGradient !== _this._currentStartSizeGradient) {
  57024. _this._currentStartSize1 = _this._currentStartSize2;
  57025. _this._currentStartSize2 = nextGradient.getFactor();
  57026. _this._currentStartSizeGradient = currentGradient;
  57027. }
  57028. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57029. particle.scale.scaleInPlace(value);
  57030. });
  57031. }
  57032. // Angle
  57033. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57034. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57035. }
  57036. else {
  57037. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57038. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57039. particle._currentAngularSpeed1 = particle.angularSpeed;
  57040. if (this_1._angularSpeedGradients.length > 1) {
  57041. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57042. }
  57043. else {
  57044. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57045. }
  57046. }
  57047. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57048. // Velocity
  57049. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57050. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57051. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57052. if (this_1._velocityGradients.length > 1) {
  57053. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57054. }
  57055. else {
  57056. particle._currentVelocity2 = particle._currentVelocity1;
  57057. }
  57058. }
  57059. // Limit velocity
  57060. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57061. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57062. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57063. if (this_1._limitVelocityGradients.length > 1) {
  57064. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57065. }
  57066. else {
  57067. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57068. }
  57069. }
  57070. // Drag
  57071. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57072. particle._currentDragGradient = this_1._dragGradients[0];
  57073. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57074. if (this_1._dragGradients.length > 1) {
  57075. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57076. }
  57077. else {
  57078. particle._currentDrag2 = particle._currentDrag1;
  57079. }
  57080. }
  57081. // Color
  57082. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57083. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57084. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57085. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57086. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57087. }
  57088. else {
  57089. particle._currentColorGradient = this_1._colorGradients[0];
  57090. particle._currentColorGradient.getColorToRef(particle.color);
  57091. particle._currentColor1.copyFrom(particle.color);
  57092. if (this_1._colorGradients.length > 1) {
  57093. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57094. }
  57095. else {
  57096. particle._currentColor2.copyFrom(particle.color);
  57097. }
  57098. }
  57099. // Sheet
  57100. if (this_1._isAnimationSheetEnabled) {
  57101. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57102. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57103. }
  57104. // Inherited Velocity
  57105. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  57106. // Ramp
  57107. if (this_1._useRampGradients) {
  57108. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  57109. }
  57110. // Noise texture coordinates
  57111. if (this_1.noiseTexture) {
  57112. if (particle._randomNoiseCoordinates1) {
  57113. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  57114. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  57115. }
  57116. else {
  57117. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  57118. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  57119. }
  57120. }
  57121. };
  57122. var this_1 = this, step;
  57123. for (var index = 0; index < newParticles; index++) {
  57124. var state_1 = _loop_2();
  57125. if (state_1 === "break")
  57126. break;
  57127. }
  57128. };
  57129. /** @hidden */
  57130. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  57131. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57132. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57133. if (useRampGradients === void 0) { useRampGradients = false; }
  57134. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57135. if (isAnimationSheetEnabled) {
  57136. attributeNamesOrOptions.push("cellIndex");
  57137. }
  57138. if (!isBillboardBased) {
  57139. attributeNamesOrOptions.push("direction");
  57140. }
  57141. if (useRampGradients) {
  57142. attributeNamesOrOptions.push("remapData");
  57143. }
  57144. return attributeNamesOrOptions;
  57145. };
  57146. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57147. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57148. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57149. if (isAnimationSheetEnabled) {
  57150. effectCreationOption.push("particlesInfos");
  57151. }
  57152. return effectCreationOption;
  57153. };
  57154. ParticleSystem.prototype._getEffect = function (blendMode) {
  57155. if (this._customEffect) {
  57156. return this._customEffect;
  57157. }
  57158. ;
  57159. var defines = [];
  57160. if (this._scene.clipPlane) {
  57161. defines.push("#define CLIPPLANE");
  57162. }
  57163. if (this._scene.clipPlane2) {
  57164. defines.push("#define CLIPPLANE2");
  57165. }
  57166. if (this._scene.clipPlane3) {
  57167. defines.push("#define CLIPPLANE3");
  57168. }
  57169. if (this._scene.clipPlane4) {
  57170. defines.push("#define CLIPPLANE4");
  57171. }
  57172. if (this._isAnimationSheetEnabled) {
  57173. defines.push("#define ANIMATESHEET");
  57174. }
  57175. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57176. defines.push("#define BLENDMULTIPLYMODE");
  57177. }
  57178. if (this._useRampGradients) {
  57179. defines.push("#define RAMPGRADIENT");
  57180. }
  57181. if (this._isBillboardBased) {
  57182. defines.push("#define BILLBOARD");
  57183. switch (this.billboardMode) {
  57184. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57185. defines.push("#define BILLBOARDY");
  57186. break;
  57187. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57188. default:
  57189. break;
  57190. }
  57191. }
  57192. if (this._imageProcessingConfiguration) {
  57193. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57194. defines.push(this._imageProcessingConfigurationDefines.toString());
  57195. }
  57196. // Effect
  57197. var join = defines.join("\n");
  57198. if (this._cachedDefines !== join) {
  57199. this._cachedDefines = join;
  57200. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased, this._useRampGradients);
  57201. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57202. var samplers = ["diffuseSampler", "rampSampler"];
  57203. if (BABYLON.ImageProcessingConfiguration) {
  57204. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57205. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57206. }
  57207. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  57208. }
  57209. return this._effect;
  57210. };
  57211. /**
  57212. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57213. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57214. */
  57215. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57216. var _this = this;
  57217. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57218. if (!this._started)
  57219. return;
  57220. if (!preWarmOnly) {
  57221. // Check
  57222. if (!this.isReady())
  57223. return;
  57224. if (this._currentRenderId === this._scene.getRenderId()) {
  57225. return;
  57226. }
  57227. this._currentRenderId = this._scene.getRenderId();
  57228. }
  57229. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57230. // Determine the number of particles we need to create
  57231. var newParticles;
  57232. if (this.manualEmitCount > -1) {
  57233. newParticles = this.manualEmitCount;
  57234. this._newPartsExcess = 0;
  57235. this.manualEmitCount = 0;
  57236. }
  57237. else {
  57238. var rate_1 = this.emitRate;
  57239. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57240. var ratio = this._actualFrame / this.targetStopDuration;
  57241. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57242. if (currentGradient !== _this._currentEmitRateGradient) {
  57243. _this._currentEmitRate1 = _this._currentEmitRate2;
  57244. _this._currentEmitRate2 = nextGradient.getFactor();
  57245. _this._currentEmitRateGradient = currentGradient;
  57246. }
  57247. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57248. });
  57249. }
  57250. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57251. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57252. }
  57253. if (this._newPartsExcess > 1.0) {
  57254. newParticles += this._newPartsExcess >> 0;
  57255. this._newPartsExcess -= this._newPartsExcess >> 0;
  57256. }
  57257. this._alive = false;
  57258. if (!this._stopped) {
  57259. this._actualFrame += this._scaledUpdateSpeed;
  57260. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57261. this.stop();
  57262. }
  57263. else {
  57264. newParticles = 0;
  57265. }
  57266. this._update(newParticles);
  57267. // Stopped?
  57268. if (this._stopped) {
  57269. if (!this._alive) {
  57270. this._started = false;
  57271. if (this.onAnimationEnd) {
  57272. this.onAnimationEnd();
  57273. }
  57274. if (this.disposeOnStop) {
  57275. this._scene._toBeDisposed.push(this);
  57276. }
  57277. }
  57278. }
  57279. if (!preWarmOnly) {
  57280. // Update VBO
  57281. var offset = 0;
  57282. for (var index = 0; index < this._particles.length; index++) {
  57283. var particle = this._particles[index];
  57284. this._appendParticleVertices(offset, particle);
  57285. offset += this._useInstancing ? 1 : 4;
  57286. }
  57287. if (this._vertexBuffer) {
  57288. this._vertexBuffer.update(this._vertexData);
  57289. }
  57290. }
  57291. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57292. this.stop();
  57293. }
  57294. };
  57295. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57296. this._appendParticleVertex(offset++, particle, 0, 0);
  57297. if (!this._useInstancing) {
  57298. this._appendParticleVertex(offset++, particle, 1, 0);
  57299. this._appendParticleVertex(offset++, particle, 1, 1);
  57300. this._appendParticleVertex(offset++, particle, 0, 1);
  57301. }
  57302. };
  57303. /**
  57304. * Rebuilds the particle system.
  57305. */
  57306. ParticleSystem.prototype.rebuild = function () {
  57307. this._createIndexBuffer();
  57308. if (this._vertexBuffer) {
  57309. this._vertexBuffer._rebuild();
  57310. }
  57311. };
  57312. /**
  57313. * Is this system ready to be used/rendered
  57314. * @return true if the system is ready
  57315. */
  57316. ParticleSystem.prototype.isReady = function () {
  57317. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57318. return false;
  57319. }
  57320. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57321. if (!this._getEffect(this.blendMode).isReady()) {
  57322. return false;
  57323. }
  57324. }
  57325. else {
  57326. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  57327. return false;
  57328. }
  57329. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  57330. return false;
  57331. }
  57332. }
  57333. return true;
  57334. };
  57335. ParticleSystem.prototype._render = function (blendMode) {
  57336. var effect = this._getEffect(blendMode);
  57337. var engine = this._scene.getEngine();
  57338. // Render
  57339. engine.enableEffect(effect);
  57340. var viewMatrix = this._scene.getViewMatrix();
  57341. effect.setTexture("diffuseSampler", this.particleTexture);
  57342. effect.setMatrix("view", viewMatrix);
  57343. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57344. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57345. var baseSize = this.particleTexture.getBaseSize();
  57346. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57347. }
  57348. effect.setVector2("translationPivot", this.translationPivot);
  57349. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57350. if (this._isBillboardBased) {
  57351. var camera = this._scene.activeCamera;
  57352. effect.setVector3("eyePosition", camera.globalPosition);
  57353. }
  57354. if (this._rampGradientsTexture) {
  57355. effect.setTexture("rampSampler", this._rampGradientsTexture);
  57356. }
  57357. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57358. var invView = viewMatrix.clone();
  57359. invView.invert();
  57360. effect.setMatrix("invView", invView);
  57361. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57362. }
  57363. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57364. // image processing
  57365. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57366. this._imageProcessingConfiguration.bind(effect);
  57367. }
  57368. // Draw order
  57369. switch (blendMode) {
  57370. case ParticleSystem.BLENDMODE_ADD:
  57371. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57372. break;
  57373. case ParticleSystem.BLENDMODE_ONEONE:
  57374. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57375. break;
  57376. case ParticleSystem.BLENDMODE_STANDARD:
  57377. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57378. break;
  57379. case ParticleSystem.BLENDMODE_MULTIPLY:
  57380. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57381. break;
  57382. }
  57383. if (this._useInstancing) {
  57384. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57385. }
  57386. else {
  57387. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57388. }
  57389. return this._particles.length;
  57390. };
  57391. /**
  57392. * Renders the particle system in its current state.
  57393. * @returns the current number of particles
  57394. */
  57395. ParticleSystem.prototype.render = function () {
  57396. // Check
  57397. if (!this.isReady() || !this._particles.length) {
  57398. return 0;
  57399. }
  57400. var engine = this._scene.getEngine();
  57401. engine.setState(false);
  57402. if (this.forceDepthWrite) {
  57403. engine.setDepthWrite(true);
  57404. }
  57405. var outparticles = 0;
  57406. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57407. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  57408. }
  57409. outparticles = this._render(this.blendMode);
  57410. engine.unbindInstanceAttributes();
  57411. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57412. return outparticles;
  57413. };
  57414. /**
  57415. * Disposes the particle system and free the associated resources
  57416. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57417. */
  57418. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57419. if (disposeTexture === void 0) { disposeTexture = true; }
  57420. if (this._vertexBuffer) {
  57421. this._vertexBuffer.dispose();
  57422. this._vertexBuffer = null;
  57423. }
  57424. if (this._spriteBuffer) {
  57425. this._spriteBuffer.dispose();
  57426. this._spriteBuffer = null;
  57427. }
  57428. if (this._indexBuffer) {
  57429. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57430. this._indexBuffer = null;
  57431. }
  57432. if (disposeTexture && this.particleTexture) {
  57433. this.particleTexture.dispose();
  57434. this.particleTexture = null;
  57435. }
  57436. if (disposeTexture && this.noiseTexture) {
  57437. this.noiseTexture.dispose();
  57438. this.noiseTexture = null;
  57439. }
  57440. if (this._rampGradientsTexture) {
  57441. this._rampGradientsTexture.dispose();
  57442. this._rampGradientsTexture = null;
  57443. }
  57444. this._removeFromRoot();
  57445. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  57446. this.emitter.dispose(true);
  57447. }
  57448. // Remove from scene
  57449. var index = this._scene.particleSystems.indexOf(this);
  57450. if (index > -1) {
  57451. this._scene.particleSystems.splice(index, 1);
  57452. }
  57453. // Callback
  57454. this.onDisposeObservable.notifyObservers(this);
  57455. this.onDisposeObservable.clear();
  57456. };
  57457. // Clone
  57458. /**
  57459. * Clones the particle system.
  57460. * @param name The name of the cloned object
  57461. * @param newEmitter The new emitter to use
  57462. * @returns the cloned particle system
  57463. */
  57464. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57465. var custom = null;
  57466. var program = null;
  57467. if (this.customShader != null) {
  57468. program = this.customShader;
  57469. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57470. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57471. }
  57472. else if (this._customEffect) {
  57473. custom = this._customEffect;
  57474. }
  57475. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57476. result.customShader = program;
  57477. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  57478. if (newEmitter === undefined) {
  57479. newEmitter = this.emitter;
  57480. }
  57481. result.noiseTexture = this.noiseTexture;
  57482. result.emitter = newEmitter;
  57483. if (this.particleTexture) {
  57484. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57485. }
  57486. // Clone gradients
  57487. if (this._colorGradients) {
  57488. this._colorGradients.forEach(function (v) {
  57489. result.addColorGradient(v.gradient, v.color1, v.color2);
  57490. });
  57491. }
  57492. if (this._dragGradients) {
  57493. this._dragGradients.forEach(function (v) {
  57494. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  57495. });
  57496. }
  57497. if (this._angularSpeedGradients) {
  57498. this._angularSpeedGradients.forEach(function (v) {
  57499. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  57500. });
  57501. }
  57502. if (this._emitRateGradients) {
  57503. this._emitRateGradients.forEach(function (v) {
  57504. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  57505. });
  57506. }
  57507. if (this._lifeTimeGradients) {
  57508. this._lifeTimeGradients.forEach(function (v) {
  57509. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  57510. });
  57511. }
  57512. if (this._limitVelocityGradients) {
  57513. this._limitVelocityGradients.forEach(function (v) {
  57514. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  57515. });
  57516. }
  57517. if (this._sizeGradients) {
  57518. this._sizeGradients.forEach(function (v) {
  57519. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  57520. });
  57521. }
  57522. if (this._startSizeGradients) {
  57523. this._startSizeGradients.forEach(function (v) {
  57524. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  57525. });
  57526. }
  57527. if (this._velocityGradients) {
  57528. this._velocityGradients.forEach(function (v) {
  57529. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  57530. });
  57531. }
  57532. if (this._rampGradients) {
  57533. this._rampGradients.forEach(function (v) {
  57534. result.addRampGradient(v.gradient, v.color);
  57535. });
  57536. }
  57537. if (this._colorRemapGradients) {
  57538. this._colorRemapGradients.forEach(function (v) {
  57539. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  57540. });
  57541. }
  57542. if (this._alphaRemapGradients) {
  57543. this._alphaRemapGradients.forEach(function (v) {
  57544. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  57545. });
  57546. }
  57547. if (!this.preventAutoStart) {
  57548. result.start();
  57549. }
  57550. return result;
  57551. };
  57552. /**
  57553. * Serializes the particle system to a JSON object.
  57554. * @returns the JSON object
  57555. */
  57556. ParticleSystem.prototype.serialize = function () {
  57557. var serializationObject = {};
  57558. ParticleSystem._Serialize(serializationObject, this);
  57559. serializationObject.textureMask = this.textureMask.asArray();
  57560. serializationObject.customShader = this.customShader;
  57561. serializationObject.preventAutoStart = this.preventAutoStart;
  57562. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57563. return serializationObject;
  57564. };
  57565. /** @hidden */
  57566. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57567. serializationObject.name = particleSystem.name;
  57568. serializationObject.id = particleSystem.id;
  57569. serializationObject.capacity = particleSystem.getCapacity();
  57570. // Emitter
  57571. if (particleSystem.emitter.position) {
  57572. var emitterMesh = particleSystem.emitter;
  57573. serializationObject.emitterId = emitterMesh.id;
  57574. }
  57575. else {
  57576. var emitterPosition = particleSystem.emitter;
  57577. serializationObject.emitter = emitterPosition.asArray();
  57578. }
  57579. // Emitter
  57580. if (particleSystem.particleEmitterType) {
  57581. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57582. }
  57583. if (particleSystem.particleTexture) {
  57584. serializationObject.textureName = particleSystem.particleTexture.name;
  57585. }
  57586. // Animations
  57587. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57588. // Particle system
  57589. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57590. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57591. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57592. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57593. serializationObject.minSize = particleSystem.minSize;
  57594. serializationObject.maxSize = particleSystem.maxSize;
  57595. serializationObject.minScaleX = particleSystem.minScaleX;
  57596. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57597. serializationObject.minScaleY = particleSystem.minScaleY;
  57598. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57599. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57600. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57601. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57602. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57603. serializationObject.emitRate = particleSystem.emitRate;
  57604. serializationObject.gravity = particleSystem.gravity.asArray();
  57605. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57606. serializationObject.color1 = particleSystem.color1.asArray();
  57607. serializationObject.color2 = particleSystem.color2.asArray();
  57608. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57609. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57610. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57611. serializationObject.blendMode = particleSystem.blendMode;
  57612. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57613. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57614. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57615. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57616. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57617. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57618. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57619. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57620. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57621. var colorGradients = particleSystem.getColorGradients();
  57622. if (colorGradients) {
  57623. serializationObject.colorGradients = [];
  57624. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57625. var colorGradient = colorGradients_1[_i];
  57626. var serializedGradient = {
  57627. gradient: colorGradient.gradient,
  57628. color1: colorGradient.color1.asArray()
  57629. };
  57630. if (colorGradient.color2) {
  57631. serializedGradient.color2 = colorGradient.color2.asArray();
  57632. }
  57633. serializationObject.colorGradients.push(serializedGradient);
  57634. }
  57635. }
  57636. var rampGradients = particleSystem.getRampGradients();
  57637. if (rampGradients) {
  57638. serializationObject.rampGradients = [];
  57639. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  57640. var rampGradient = rampGradients_1[_a];
  57641. var serializedGradient = {
  57642. gradient: rampGradient.gradient,
  57643. color: rampGradient.color.asArray()
  57644. };
  57645. serializationObject.rampGradients.push(serializedGradient);
  57646. }
  57647. }
  57648. var colorRemapGradients = particleSystem.getColorRemapGradients();
  57649. if (colorRemapGradients) {
  57650. serializationObject.colorRemapGradients = [];
  57651. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  57652. var colorRemapGradient = colorRemapGradients_1[_b];
  57653. var serializedGradient = {
  57654. gradient: colorRemapGradient.gradient,
  57655. factor1: colorRemapGradient.factor1
  57656. };
  57657. if (colorRemapGradient.factor2 !== undefined) {
  57658. serializedGradient.factor2 = colorRemapGradient.factor2;
  57659. }
  57660. serializationObject.colorRemapGradients.push(serializedGradient);
  57661. }
  57662. }
  57663. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  57664. if (alphaRemapGradients) {
  57665. serializationObject.alphaRemapGradients = [];
  57666. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  57667. var alphaRemapGradient = alphaRemapGradients_1[_c];
  57668. var serializedGradient = {
  57669. gradient: alphaRemapGradient.gradient,
  57670. factor1: alphaRemapGradient.factor1
  57671. };
  57672. if (alphaRemapGradient.factor2 !== undefined) {
  57673. serializedGradient.factor2 = alphaRemapGradient.factor2;
  57674. }
  57675. serializationObject.alphaRemapGradients.push(serializedGradient);
  57676. }
  57677. }
  57678. var sizeGradients = particleSystem.getSizeGradients();
  57679. if (sizeGradients) {
  57680. serializationObject.sizeGradients = [];
  57681. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  57682. var sizeGradient = sizeGradients_1[_d];
  57683. var serializedGradient = {
  57684. gradient: sizeGradient.gradient,
  57685. factor1: sizeGradient.factor1
  57686. };
  57687. if (sizeGradient.factor2 !== undefined) {
  57688. serializedGradient.factor2 = sizeGradient.factor2;
  57689. }
  57690. serializationObject.sizeGradients.push(serializedGradient);
  57691. }
  57692. }
  57693. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57694. if (angularSpeedGradients) {
  57695. serializationObject.angularSpeedGradients = [];
  57696. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  57697. var angularSpeedGradient = angularSpeedGradients_1[_e];
  57698. var serializedGradient = {
  57699. gradient: angularSpeedGradient.gradient,
  57700. factor1: angularSpeedGradient.factor1
  57701. };
  57702. if (angularSpeedGradient.factor2 !== undefined) {
  57703. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57704. }
  57705. serializationObject.angularSpeedGradients.push(serializedGradient);
  57706. }
  57707. }
  57708. var velocityGradients = particleSystem.getVelocityGradients();
  57709. if (velocityGradients) {
  57710. serializationObject.velocityGradients = [];
  57711. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  57712. var velocityGradient = velocityGradients_1[_f];
  57713. var serializedGradient = {
  57714. gradient: velocityGradient.gradient,
  57715. factor1: velocityGradient.factor1
  57716. };
  57717. if (velocityGradient.factor2 !== undefined) {
  57718. serializedGradient.factor2 = velocityGradient.factor2;
  57719. }
  57720. serializationObject.velocityGradients.push(serializedGradient);
  57721. }
  57722. }
  57723. var dragGradients = particleSystem.getDragGradients();
  57724. if (dragGradients) {
  57725. serializationObject.dragyGradients = [];
  57726. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  57727. var dragGradient = dragGradients_1[_g];
  57728. var serializedGradient = {
  57729. gradient: dragGradient.gradient,
  57730. factor1: dragGradient.factor1
  57731. };
  57732. if (dragGradient.factor2 !== undefined) {
  57733. serializedGradient.factor2 = dragGradient.factor2;
  57734. }
  57735. serializationObject.dragGradients.push(serializedGradient);
  57736. }
  57737. }
  57738. var emitRateGradients = particleSystem.getEmitRateGradients();
  57739. if (emitRateGradients) {
  57740. serializationObject.emitRateGradients = [];
  57741. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  57742. var emitRateGradient = emitRateGradients_1[_h];
  57743. var serializedGradient = {
  57744. gradient: emitRateGradient.gradient,
  57745. factor1: emitRateGradient.factor1
  57746. };
  57747. if (emitRateGradient.factor2 !== undefined) {
  57748. serializedGradient.factor2 = emitRateGradient.factor2;
  57749. }
  57750. serializationObject.emitRateGradients.push(serializedGradient);
  57751. }
  57752. }
  57753. var startSizeGradients = particleSystem.getStartSizeGradients();
  57754. if (startSizeGradients) {
  57755. serializationObject.startSizeGradients = [];
  57756. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  57757. var startSizeGradient = startSizeGradients_1[_j];
  57758. var serializedGradient = {
  57759. gradient: startSizeGradient.gradient,
  57760. factor1: startSizeGradient.factor1
  57761. };
  57762. if (startSizeGradient.factor2 !== undefined) {
  57763. serializedGradient.factor2 = startSizeGradient.factor2;
  57764. }
  57765. serializationObject.startSizeGradients.push(serializedGradient);
  57766. }
  57767. }
  57768. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57769. if (limitVelocityGradients) {
  57770. serializationObject.limitVelocityGradients = [];
  57771. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  57772. var limitVelocityGradient = limitVelocityGradients_1[_k];
  57773. var serializedGradient = {
  57774. gradient: limitVelocityGradient.gradient,
  57775. factor1: limitVelocityGradient.factor1
  57776. };
  57777. if (limitVelocityGradient.factor2 !== undefined) {
  57778. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57779. }
  57780. serializationObject.limitVelocityGradients.push(serializedGradient);
  57781. }
  57782. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57783. }
  57784. if (particleSystem.noiseTexture) {
  57785. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  57786. }
  57787. };
  57788. /** @hidden */
  57789. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57790. // Texture
  57791. if (parsedParticleSystem.textureName) {
  57792. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57793. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57794. }
  57795. // Emitter
  57796. if (parsedParticleSystem.emitterId === undefined) {
  57797. particleSystem.emitter = BABYLON.Vector3.Zero();
  57798. }
  57799. else if (parsedParticleSystem.emitterId) {
  57800. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57801. }
  57802. else {
  57803. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57804. }
  57805. // Misc.
  57806. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57807. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57808. }
  57809. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57810. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57811. }
  57812. // Animations
  57813. if (parsedParticleSystem.animations) {
  57814. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57815. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57816. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57817. }
  57818. }
  57819. if (parsedParticleSystem.autoAnimate) {
  57820. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57821. }
  57822. // Particle system
  57823. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57824. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57825. particleSystem.minSize = parsedParticleSystem.minSize;
  57826. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57827. if (parsedParticleSystem.minScaleX) {
  57828. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57829. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57830. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57831. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57832. }
  57833. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57834. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57835. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57836. }
  57837. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57838. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57839. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57840. }
  57841. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57842. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57843. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57844. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57845. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57846. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57847. if (parsedParticleSystem.noiseStrength) {
  57848. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57849. }
  57850. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57851. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57852. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57853. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57854. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57855. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57856. if (parsedParticleSystem.colorGradients) {
  57857. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57858. var colorGradient = _a[_i];
  57859. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57860. }
  57861. }
  57862. if (parsedParticleSystem.rampGradients) {
  57863. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  57864. var rampGradient = _c[_b];
  57865. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color1));
  57866. }
  57867. }
  57868. if (parsedParticleSystem.colorRemapGradients) {
  57869. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  57870. var colorRemapGradient = _e[_d];
  57871. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  57872. }
  57873. }
  57874. if (parsedParticleSystem.alphaRemapGradients) {
  57875. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  57876. var alphaRemapGradient = _g[_f];
  57877. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  57878. }
  57879. }
  57880. if (parsedParticleSystem.sizeGradients) {
  57881. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  57882. var sizeGradient = _j[_h];
  57883. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57884. }
  57885. }
  57886. if (parsedParticleSystem.sizeGradients) {
  57887. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  57888. var sizeGradient = _l[_k];
  57889. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57890. }
  57891. }
  57892. if (parsedParticleSystem.angularSpeedGradients) {
  57893. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  57894. var angularSpeedGradient = _o[_m];
  57895. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57896. }
  57897. }
  57898. if (parsedParticleSystem.velocityGradients) {
  57899. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  57900. var velocityGradient = _q[_p];
  57901. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57902. }
  57903. }
  57904. if (parsedParticleSystem.dragGradients) {
  57905. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  57906. var dragGradient = _s[_r];
  57907. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  57908. }
  57909. }
  57910. if (parsedParticleSystem.emitRateGradients) {
  57911. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  57912. var emitRateGradient = _u[_t];
  57913. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  57914. }
  57915. }
  57916. if (parsedParticleSystem.startSizeGradients) {
  57917. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  57918. var startSizeGradient = _w[_v];
  57919. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  57920. }
  57921. }
  57922. if (parsedParticleSystem.limitVelocityGradients) {
  57923. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  57924. var limitVelocityGradient = _y[_x];
  57925. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57926. }
  57927. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57928. }
  57929. if (parsedParticleSystem.noiseTexture) {
  57930. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57931. }
  57932. // Emitter
  57933. var emitterType;
  57934. if (parsedParticleSystem.particleEmitterType) {
  57935. switch (parsedParticleSystem.particleEmitterType.type) {
  57936. case "SphereParticleEmitter":
  57937. emitterType = new BABYLON.SphereParticleEmitter();
  57938. break;
  57939. case "SphereDirectedParticleEmitter":
  57940. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57941. break;
  57942. case "ConeEmitter":
  57943. case "ConeParticleEmitter":
  57944. emitterType = new BABYLON.ConeParticleEmitter();
  57945. break;
  57946. case "BoxEmitter":
  57947. case "BoxParticleEmitter":
  57948. default:
  57949. emitterType = new BABYLON.BoxParticleEmitter();
  57950. break;
  57951. }
  57952. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57953. }
  57954. else {
  57955. emitterType = new BABYLON.BoxParticleEmitter();
  57956. emitterType.parse(parsedParticleSystem);
  57957. }
  57958. particleSystem.particleEmitterType = emitterType;
  57959. // Animation sheet
  57960. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57961. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57962. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57963. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57964. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57965. };
  57966. /**
  57967. * Parses a JSON object to create a particle system.
  57968. * @param parsedParticleSystem The JSON object to parse
  57969. * @param scene The scene to create the particle system in
  57970. * @param rootUrl The root url to use to load external dependencies like texture
  57971. * @returns the Parsed particle system
  57972. */
  57973. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57974. var name = parsedParticleSystem.name;
  57975. var custom = null;
  57976. var program = null;
  57977. if (parsedParticleSystem.customShader) {
  57978. program = parsedParticleSystem.customShader;
  57979. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57980. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57981. }
  57982. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57983. particleSystem.customShader = program;
  57984. if (parsedParticleSystem.id) {
  57985. particleSystem.id = parsedParticleSystem.id;
  57986. }
  57987. // Auto start
  57988. if (parsedParticleSystem.preventAutoStart) {
  57989. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57990. }
  57991. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57992. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57993. if (!particleSystem.preventAutoStart) {
  57994. particleSystem.start();
  57995. }
  57996. return particleSystem;
  57997. };
  57998. return ParticleSystem;
  57999. }(BABYLON.BaseParticleSystem));
  58000. BABYLON.ParticleSystem = ParticleSystem;
  58001. })(BABYLON || (BABYLON = {}));
  58002. //# sourceMappingURL=babylon.particleSystem.js.map
  58003. var BABYLON;
  58004. (function (BABYLON) {
  58005. /**
  58006. * Particle emitter emitting particles from the inside of a box.
  58007. * It emits the particles randomly between 2 given directions.
  58008. */
  58009. var BoxParticleEmitter = /** @class */ (function () {
  58010. /**
  58011. * Creates a new instance BoxParticleEmitter
  58012. */
  58013. function BoxParticleEmitter() {
  58014. /**
  58015. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58016. */
  58017. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58018. /**
  58019. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58020. */
  58021. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58022. /**
  58023. * 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.
  58024. */
  58025. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  58026. /**
  58027. * 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.
  58028. */
  58029. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  58030. }
  58031. /**
  58032. * Called by the particle System when the direction is computed for the created particle.
  58033. * @param worldMatrix is the world matrix of the particle system
  58034. * @param directionToUpdate is the direction vector to update with the result
  58035. * @param particle is the particle we are computed the direction for
  58036. */
  58037. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58038. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58039. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58040. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58041. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58042. };
  58043. /**
  58044. * Called by the particle System when the position is computed for the created particle.
  58045. * @param worldMatrix is the world matrix of the particle system
  58046. * @param positionToUpdate is the position vector to update with the result
  58047. * @param particle is the particle we are computed the position for
  58048. */
  58049. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58050. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  58051. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  58052. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  58053. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58054. };
  58055. /**
  58056. * Clones the current emitter and returns a copy of it
  58057. * @returns the new emitter
  58058. */
  58059. BoxParticleEmitter.prototype.clone = function () {
  58060. var newOne = new BoxParticleEmitter();
  58061. BABYLON.Tools.DeepCopy(this, newOne);
  58062. return newOne;
  58063. };
  58064. /**
  58065. * Called by the GPUParticleSystem to setup the update shader
  58066. * @param effect defines the update shader
  58067. */
  58068. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  58069. effect.setVector3("direction1", this.direction1);
  58070. effect.setVector3("direction2", this.direction2);
  58071. effect.setVector3("minEmitBox", this.minEmitBox);
  58072. effect.setVector3("maxEmitBox", this.maxEmitBox);
  58073. };
  58074. /**
  58075. * Returns a string to use to update the GPU particles update shader
  58076. * @returns a string containng the defines string
  58077. */
  58078. BoxParticleEmitter.prototype.getEffectDefines = function () {
  58079. return "#define BOXEMITTER";
  58080. };
  58081. /**
  58082. * Returns the string "BoxParticleEmitter"
  58083. * @returns a string containing the class name
  58084. */
  58085. BoxParticleEmitter.prototype.getClassName = function () {
  58086. return "BoxParticleEmitter";
  58087. };
  58088. /**
  58089. * Serializes the particle system to a JSON object.
  58090. * @returns the JSON object
  58091. */
  58092. BoxParticleEmitter.prototype.serialize = function () {
  58093. var serializationObject = {};
  58094. serializationObject.type = this.getClassName();
  58095. serializationObject.direction1 = this.direction1.asArray();
  58096. serializationObject.direction2 = this.direction2.asArray();
  58097. serializationObject.minEmitBox = this.minEmitBox.asArray();
  58098. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  58099. return serializationObject;
  58100. };
  58101. /**
  58102. * Parse properties from a JSON object
  58103. * @param serializationObject defines the JSON object
  58104. */
  58105. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  58106. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58107. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58108. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  58109. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  58110. };
  58111. return BoxParticleEmitter;
  58112. }());
  58113. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  58114. })(BABYLON || (BABYLON = {}));
  58115. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  58116. var BABYLON;
  58117. (function (BABYLON) {
  58118. /**
  58119. * Particle emitter emitting particles from the inside of a cylinder.
  58120. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  58121. */
  58122. var CylinderParticleEmitter = /** @class */ (function () {
  58123. /**
  58124. * Creates a new instance CylinderParticleEmitter
  58125. * @param radius the radius of the emission cylinder (1 by default)
  58126. * @param height the height of the emission cylinder (1 by default)
  58127. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58128. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58129. */
  58130. function CylinderParticleEmitter(
  58131. /**
  58132. * The radius of the emission cylinder.
  58133. */
  58134. radius,
  58135. /**
  58136. * The height of the emission cylinder.
  58137. */
  58138. height,
  58139. /**
  58140. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58141. */
  58142. radiusRange,
  58143. /**
  58144. * How much to randomize the particle direction [0-1].
  58145. */
  58146. directionRandomizer) {
  58147. if (radius === void 0) { radius = 1; }
  58148. if (height === void 0) { height = 1; }
  58149. if (radiusRange === void 0) { radiusRange = 1; }
  58150. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58151. this.radius = radius;
  58152. this.height = height;
  58153. this.radiusRange = radiusRange;
  58154. this.directionRandomizer = directionRandomizer;
  58155. }
  58156. /**
  58157. * Called by the particle System when the direction is computed for the created particle.
  58158. * @param worldMatrix is the world matrix of the particle system
  58159. * @param directionToUpdate is the direction vector to update with the result
  58160. * @param particle is the particle we are computed the direction for
  58161. */
  58162. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58163. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58164. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  58165. var angle = Math.atan2(direction.x, direction.z);
  58166. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58167. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58168. direction.x = Math.sin(angle);
  58169. direction.z = Math.cos(angle);
  58170. direction.normalize();
  58171. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58172. };
  58173. /**
  58174. * Called by the particle System when the position is computed for the created particle.
  58175. * @param worldMatrix is the world matrix of the particle system
  58176. * @param positionToUpdate is the position vector to update with the result
  58177. * @param particle is the particle we are computed the position for
  58178. */
  58179. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58180. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58181. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58182. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58183. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58184. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58185. var xPos = positionRadius * Math.cos(angle);
  58186. var zPos = positionRadius * Math.sin(angle);
  58187. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58188. };
  58189. /**
  58190. * Clones the current emitter and returns a copy of it
  58191. * @returns the new emitter
  58192. */
  58193. CylinderParticleEmitter.prototype.clone = function () {
  58194. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58195. BABYLON.Tools.DeepCopy(this, newOne);
  58196. return newOne;
  58197. };
  58198. /**
  58199. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58200. * @param effect defines the update shader
  58201. */
  58202. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58203. effect.setFloat("radius", this.radius);
  58204. effect.setFloat("height", this.height);
  58205. effect.setFloat("radiusRange", this.radiusRange);
  58206. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58207. };
  58208. /**
  58209. * Returns a string to use to update the GPU particles update shader
  58210. * @returns a string containng the defines string
  58211. */
  58212. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58213. return "#define CYLINDEREMITTER";
  58214. };
  58215. /**
  58216. * Returns the string "CylinderParticleEmitter"
  58217. * @returns a string containing the class name
  58218. */
  58219. CylinderParticleEmitter.prototype.getClassName = function () {
  58220. return "CylinderParticleEmitter";
  58221. };
  58222. /**
  58223. * Serializes the particle system to a JSON object.
  58224. * @returns the JSON object
  58225. */
  58226. CylinderParticleEmitter.prototype.serialize = function () {
  58227. var serializationObject = {};
  58228. serializationObject.type = this.getClassName();
  58229. serializationObject.radius = this.radius;
  58230. serializationObject.height = this.height;
  58231. serializationObject.radiusRange = this.radiusRange;
  58232. serializationObject.directionRandomizer = this.directionRandomizer;
  58233. return serializationObject;
  58234. };
  58235. /**
  58236. * Parse properties from a JSON object
  58237. * @param serializationObject defines the JSON object
  58238. */
  58239. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58240. this.radius = serializationObject.radius;
  58241. this.height = serializationObject.height;
  58242. this.radiusRange = serializationObject.radiusRange;
  58243. this.directionRandomizer = serializationObject.directionRandomizer;
  58244. };
  58245. return CylinderParticleEmitter;
  58246. }());
  58247. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58248. /**
  58249. * Particle emitter emitting particles from the inside of a cylinder.
  58250. * It emits the particles randomly between two vectors.
  58251. */
  58252. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58253. __extends(CylinderDirectedParticleEmitter, _super);
  58254. /**
  58255. * Creates a new instance CylinderDirectedParticleEmitter
  58256. * @param radius the radius of the emission cylinder (1 by default)
  58257. * @param height the height of the emission cylinder (1 by default)
  58258. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58259. * @param direction1 the min limit of the emission direction (up vector by default)
  58260. * @param direction2 the max limit of the emission direction (up vector by default)
  58261. */
  58262. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58263. /**
  58264. * The min limit of the emission direction.
  58265. */
  58266. direction1,
  58267. /**
  58268. * The max limit of the emission direction.
  58269. */
  58270. direction2) {
  58271. if (radius === void 0) { radius = 1; }
  58272. if (height === void 0) { height = 1; }
  58273. if (radiusRange === void 0) { radiusRange = 1; }
  58274. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58275. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58276. var _this = _super.call(this, radius, height, radiusRange) || this;
  58277. _this.direction1 = direction1;
  58278. _this.direction2 = direction2;
  58279. return _this;
  58280. }
  58281. /**
  58282. * Called by the particle System when the direction is computed for the created particle.
  58283. * @param worldMatrix is the world matrix of the particle system
  58284. * @param directionToUpdate is the direction vector to update with the result
  58285. * @param particle is the particle we are computed the direction for
  58286. */
  58287. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58288. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58289. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58290. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58291. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58292. };
  58293. /**
  58294. * Clones the current emitter and returns a copy of it
  58295. * @returns the new emitter
  58296. */
  58297. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58298. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58299. BABYLON.Tools.DeepCopy(this, newOne);
  58300. return newOne;
  58301. };
  58302. /**
  58303. * Called by the GPUParticleSystem to setup the update shader
  58304. * @param effect defines the update shader
  58305. */
  58306. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58307. effect.setFloat("radius", this.radius);
  58308. effect.setFloat("height", this.height);
  58309. effect.setFloat("radiusRange", this.radiusRange);
  58310. effect.setVector3("direction1", this.direction1);
  58311. effect.setVector3("direction2", this.direction2);
  58312. };
  58313. /**
  58314. * Returns a string to use to update the GPU particles update shader
  58315. * @returns a string containng the defines string
  58316. */
  58317. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58318. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58319. };
  58320. /**
  58321. * Returns the string "CylinderDirectedParticleEmitter"
  58322. * @returns a string containing the class name
  58323. */
  58324. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58325. return "CylinderDirectedParticleEmitter";
  58326. };
  58327. /**
  58328. * Serializes the particle system to a JSON object.
  58329. * @returns the JSON object
  58330. */
  58331. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58332. var serializationObject = _super.prototype.serialize.call(this);
  58333. serializationObject.direction1 = this.direction1.asArray();
  58334. serializationObject.direction2 = this.direction2.asArray();
  58335. return serializationObject;
  58336. };
  58337. /**
  58338. * Parse properties from a JSON object
  58339. * @param serializationObject defines the JSON object
  58340. */
  58341. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58342. _super.prototype.parse.call(this, serializationObject);
  58343. this.direction1.copyFrom(serializationObject.direction1);
  58344. this.direction2.copyFrom(serializationObject.direction2);
  58345. };
  58346. return CylinderDirectedParticleEmitter;
  58347. }(CylinderParticleEmitter));
  58348. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58349. })(BABYLON || (BABYLON = {}));
  58350. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58351. var BABYLON;
  58352. (function (BABYLON) {
  58353. /**
  58354. * Particle emitter emitting particles from the inside of a cone.
  58355. * It emits the particles alongside the cone volume from the base to the particle.
  58356. * The emission direction might be randomized.
  58357. */
  58358. var ConeParticleEmitter = /** @class */ (function () {
  58359. /**
  58360. * Creates a new instance ConeParticleEmitter
  58361. * @param radius the radius of the emission cone (1 by default)
  58362. * @param angles the cone base angle (PI by default)
  58363. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58364. */
  58365. function ConeParticleEmitter(radius, angle,
  58366. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58367. directionRandomizer) {
  58368. if (radius === void 0) { radius = 1; }
  58369. if (angle === void 0) { angle = Math.PI; }
  58370. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58371. this.directionRandomizer = directionRandomizer;
  58372. /**
  58373. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58374. */
  58375. this.radiusRange = 1;
  58376. /**
  58377. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58378. */
  58379. this.heightRange = 1;
  58380. /**
  58381. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58382. */
  58383. this.emitFromSpawnPointOnly = false;
  58384. this.angle = angle;
  58385. this.radius = radius;
  58386. }
  58387. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58388. /**
  58389. * Gets or sets the radius of the emission cone
  58390. */
  58391. get: function () {
  58392. return this._radius;
  58393. },
  58394. set: function (value) {
  58395. this._radius = value;
  58396. this._buildHeight();
  58397. },
  58398. enumerable: true,
  58399. configurable: true
  58400. });
  58401. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58402. /**
  58403. * Gets or sets the angle of the emission cone
  58404. */
  58405. get: function () {
  58406. return this._angle;
  58407. },
  58408. set: function (value) {
  58409. this._angle = value;
  58410. this._buildHeight();
  58411. },
  58412. enumerable: true,
  58413. configurable: true
  58414. });
  58415. ConeParticleEmitter.prototype._buildHeight = function () {
  58416. if (this._angle !== 0) {
  58417. this._height = this._radius / Math.tan(this._angle / 2);
  58418. }
  58419. else {
  58420. this._height = 1;
  58421. }
  58422. };
  58423. /**
  58424. * Called by the particle System when the direction is computed for the created particle.
  58425. * @param worldMatrix is the world matrix of the particle system
  58426. * @param directionToUpdate is the direction vector to update with the result
  58427. * @param particle is the particle we are computed the direction for
  58428. */
  58429. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58430. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58431. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58432. }
  58433. else {
  58434. // measure the direction Vector from the emitter to the particle.
  58435. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58436. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58437. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58438. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58439. direction.x += randX;
  58440. direction.y += randY;
  58441. direction.z += randZ;
  58442. direction.normalize();
  58443. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58444. }
  58445. };
  58446. /**
  58447. * Called by the particle System when the position is computed for the created particle.
  58448. * @param worldMatrix is the world matrix of the particle system
  58449. * @param positionToUpdate is the position vector to update with the result
  58450. * @param particle is the particle we are computed the position for
  58451. */
  58452. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58453. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58454. var h;
  58455. if (!this.emitFromSpawnPointOnly) {
  58456. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58457. // Better distribution in a cone at normal angles.
  58458. h = 1 - h * h;
  58459. }
  58460. else {
  58461. h = 0.0001;
  58462. }
  58463. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58464. radius = radius * h;
  58465. var randX = radius * Math.sin(s);
  58466. var randZ = radius * Math.cos(s);
  58467. var randY = h * this._height;
  58468. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58469. };
  58470. /**
  58471. * Clones the current emitter and returns a copy of it
  58472. * @returns the new emitter
  58473. */
  58474. ConeParticleEmitter.prototype.clone = function () {
  58475. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58476. BABYLON.Tools.DeepCopy(this, newOne);
  58477. return newOne;
  58478. };
  58479. /**
  58480. * Called by the GPUParticleSystem to setup the update shader
  58481. * @param effect defines the update shader
  58482. */
  58483. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58484. effect.setFloat2("radius", this._radius, this.radiusRange);
  58485. effect.setFloat("coneAngle", this._angle);
  58486. effect.setFloat2("height", this._height, this.heightRange);
  58487. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58488. };
  58489. /**
  58490. * Returns a string to use to update the GPU particles update shader
  58491. * @returns a string containng the defines string
  58492. */
  58493. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58494. var defines = "#define CONEEMITTER";
  58495. if (this.emitFromSpawnPointOnly) {
  58496. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58497. }
  58498. return defines;
  58499. };
  58500. /**
  58501. * Returns the string "ConeParticleEmitter"
  58502. * @returns a string containing the class name
  58503. */
  58504. ConeParticleEmitter.prototype.getClassName = function () {
  58505. return "ConeParticleEmitter";
  58506. };
  58507. /**
  58508. * Serializes the particle system to a JSON object.
  58509. * @returns the JSON object
  58510. */
  58511. ConeParticleEmitter.prototype.serialize = function () {
  58512. var serializationObject = {};
  58513. serializationObject.type = this.getClassName();
  58514. serializationObject.radius = this._radius;
  58515. serializationObject.angle = this._angle;
  58516. serializationObject.directionRandomizer = this.directionRandomizer;
  58517. return serializationObject;
  58518. };
  58519. /**
  58520. * Parse properties from a JSON object
  58521. * @param serializationObject defines the JSON object
  58522. */
  58523. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58524. this.radius = serializationObject.radius;
  58525. this.angle = serializationObject.angle;
  58526. this.directionRandomizer = serializationObject.directionRandomizer;
  58527. };
  58528. return ConeParticleEmitter;
  58529. }());
  58530. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58531. })(BABYLON || (BABYLON = {}));
  58532. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58533. var BABYLON;
  58534. (function (BABYLON) {
  58535. /**
  58536. * Particle emitter emitting particles from the inside of a sphere.
  58537. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58538. */
  58539. var SphereParticleEmitter = /** @class */ (function () {
  58540. /**
  58541. * Creates a new instance SphereParticleEmitter
  58542. * @param radius the radius of the emission sphere (1 by default)
  58543. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58544. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58545. */
  58546. function SphereParticleEmitter(
  58547. /**
  58548. * The radius of the emission sphere.
  58549. */
  58550. radius,
  58551. /**
  58552. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58553. */
  58554. radiusRange,
  58555. /**
  58556. * How much to randomize the particle direction [0-1].
  58557. */
  58558. directionRandomizer) {
  58559. if (radius === void 0) { radius = 1; }
  58560. if (radiusRange === void 0) { radiusRange = 1; }
  58561. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58562. this.radius = radius;
  58563. this.radiusRange = radiusRange;
  58564. this.directionRandomizer = directionRandomizer;
  58565. }
  58566. /**
  58567. * Called by the particle System when the direction is computed for the created particle.
  58568. * @param worldMatrix is the world matrix of the particle system
  58569. * @param directionToUpdate is the direction vector to update with the result
  58570. * @param particle is the particle we are computed the direction for
  58571. */
  58572. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58573. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58574. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58575. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58576. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58577. direction.x += randX;
  58578. direction.y += randY;
  58579. direction.z += randZ;
  58580. direction.normalize();
  58581. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58582. };
  58583. /**
  58584. * Called by the particle System when the position is computed for the created particle.
  58585. * @param worldMatrix is the world matrix of the particle system
  58586. * @param positionToUpdate is the position vector to update with the result
  58587. * @param particle is the particle we are computed the position for
  58588. */
  58589. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58590. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58591. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58592. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58593. var theta = Math.acos(2 * v - 1);
  58594. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58595. var randY = randRadius * Math.cos(theta);
  58596. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58597. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58598. };
  58599. /**
  58600. * Clones the current emitter and returns a copy of it
  58601. * @returns the new emitter
  58602. */
  58603. SphereParticleEmitter.prototype.clone = function () {
  58604. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58605. BABYLON.Tools.DeepCopy(this, newOne);
  58606. return newOne;
  58607. };
  58608. /**
  58609. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58610. * @param effect defines the update shader
  58611. */
  58612. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58613. effect.setFloat("radius", this.radius);
  58614. effect.setFloat("radiusRange", this.radiusRange);
  58615. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58616. };
  58617. /**
  58618. * Returns a string to use to update the GPU particles update shader
  58619. * @returns a string containng the defines string
  58620. */
  58621. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58622. return "#define SPHEREEMITTER";
  58623. };
  58624. /**
  58625. * Returns the string "SphereParticleEmitter"
  58626. * @returns a string containing the class name
  58627. */
  58628. SphereParticleEmitter.prototype.getClassName = function () {
  58629. return "SphereParticleEmitter";
  58630. };
  58631. /**
  58632. * Serializes the particle system to a JSON object.
  58633. * @returns the JSON object
  58634. */
  58635. SphereParticleEmitter.prototype.serialize = function () {
  58636. var serializationObject = {};
  58637. serializationObject.type = this.getClassName();
  58638. serializationObject.radius = this.radius;
  58639. serializationObject.radiusRange = this.radiusRange;
  58640. serializationObject.directionRandomizer = this.directionRandomizer;
  58641. return serializationObject;
  58642. };
  58643. /**
  58644. * Parse properties from a JSON object
  58645. * @param serializationObject defines the JSON object
  58646. */
  58647. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58648. this.radius = serializationObject.radius;
  58649. this.radiusRange = serializationObject.radiusRange;
  58650. this.directionRandomizer = serializationObject.directionRandomizer;
  58651. };
  58652. return SphereParticleEmitter;
  58653. }());
  58654. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58655. /**
  58656. * Particle emitter emitting particles from the inside of a sphere.
  58657. * It emits the particles randomly between two vectors.
  58658. */
  58659. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58660. __extends(SphereDirectedParticleEmitter, _super);
  58661. /**
  58662. * Creates a new instance SphereDirectedParticleEmitter
  58663. * @param radius the radius of the emission sphere (1 by default)
  58664. * @param direction1 the min limit of the emission direction (up vector by default)
  58665. * @param direction2 the max limit of the emission direction (up vector by default)
  58666. */
  58667. function SphereDirectedParticleEmitter(radius,
  58668. /**
  58669. * The min limit of the emission direction.
  58670. */
  58671. direction1,
  58672. /**
  58673. * The max limit of the emission direction.
  58674. */
  58675. direction2) {
  58676. if (radius === void 0) { radius = 1; }
  58677. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58678. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58679. var _this = _super.call(this, radius) || this;
  58680. _this.direction1 = direction1;
  58681. _this.direction2 = direction2;
  58682. return _this;
  58683. }
  58684. /**
  58685. * Called by the particle System when the direction is computed for the created particle.
  58686. * @param worldMatrix is the world matrix of the particle system
  58687. * @param directionToUpdate is the direction vector to update with the result
  58688. * @param particle is the particle we are computed the direction for
  58689. */
  58690. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58691. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58692. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58693. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58694. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58695. };
  58696. /**
  58697. * Clones the current emitter and returns a copy of it
  58698. * @returns the new emitter
  58699. */
  58700. SphereDirectedParticleEmitter.prototype.clone = function () {
  58701. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58702. BABYLON.Tools.DeepCopy(this, newOne);
  58703. return newOne;
  58704. };
  58705. /**
  58706. * Called by the GPUParticleSystem to setup the update shader
  58707. * @param effect defines the update shader
  58708. */
  58709. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58710. effect.setFloat("radius", this.radius);
  58711. effect.setFloat("radiusRange", this.radiusRange);
  58712. effect.setVector3("direction1", this.direction1);
  58713. effect.setVector3("direction2", this.direction2);
  58714. };
  58715. /**
  58716. * Returns a string to use to update the GPU particles update shader
  58717. * @returns a string containng the defines string
  58718. */
  58719. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58720. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58721. };
  58722. /**
  58723. * Returns the string "SphereDirectedParticleEmitter"
  58724. * @returns a string containing the class name
  58725. */
  58726. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58727. return "SphereDirectedParticleEmitter";
  58728. };
  58729. /**
  58730. * Serializes the particle system to a JSON object.
  58731. * @returns the JSON object
  58732. */
  58733. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58734. var serializationObject = _super.prototype.serialize.call(this);
  58735. serializationObject.direction1 = this.direction1.asArray();
  58736. serializationObject.direction2 = this.direction2.asArray();
  58737. return serializationObject;
  58738. };
  58739. /**
  58740. * Parse properties from a JSON object
  58741. * @param serializationObject defines the JSON object
  58742. */
  58743. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58744. _super.prototype.parse.call(this, serializationObject);
  58745. this.direction1.copyFrom(serializationObject.direction1);
  58746. this.direction2.copyFrom(serializationObject.direction2);
  58747. };
  58748. return SphereDirectedParticleEmitter;
  58749. }(SphereParticleEmitter));
  58750. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58751. })(BABYLON || (BABYLON = {}));
  58752. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58753. var BABYLON;
  58754. (function (BABYLON) {
  58755. /**
  58756. * Particle emitter emitting particles from the inside of a hemisphere.
  58757. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58758. */
  58759. var HemisphericParticleEmitter = /** @class */ (function () {
  58760. /**
  58761. * Creates a new instance HemisphericParticleEmitter
  58762. * @param radius the radius of the emission hemisphere (1 by default)
  58763. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58764. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58765. */
  58766. function HemisphericParticleEmitter(
  58767. /**
  58768. * The radius of the emission hemisphere.
  58769. */
  58770. radius,
  58771. /**
  58772. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58773. */
  58774. radiusRange,
  58775. /**
  58776. * How much to randomize the particle direction [0-1].
  58777. */
  58778. directionRandomizer) {
  58779. if (radius === void 0) { radius = 1; }
  58780. if (radiusRange === void 0) { radiusRange = 1; }
  58781. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58782. this.radius = radius;
  58783. this.radiusRange = radiusRange;
  58784. this.directionRandomizer = directionRandomizer;
  58785. }
  58786. /**
  58787. * Called by the particle System when the direction is computed for the created particle.
  58788. * @param worldMatrix is the world matrix of the particle system
  58789. * @param directionToUpdate is the direction vector to update with the result
  58790. * @param particle is the particle we are computed the direction for
  58791. */
  58792. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58793. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58794. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58795. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58796. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58797. direction.x += randX;
  58798. direction.y += randY;
  58799. direction.z += randZ;
  58800. direction.normalize();
  58801. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58802. };
  58803. /**
  58804. * Called by the particle System when the position is computed for the created particle.
  58805. * @param worldMatrix is the world matrix of the particle system
  58806. * @param positionToUpdate is the position vector to update with the result
  58807. * @param particle is the particle we are computed the position for
  58808. */
  58809. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58810. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58811. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58812. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58813. var theta = Math.acos(2 * v - 1);
  58814. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58815. var randY = randRadius * Math.cos(theta);
  58816. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58817. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58818. };
  58819. /**
  58820. * Clones the current emitter and returns a copy of it
  58821. * @returns the new emitter
  58822. */
  58823. HemisphericParticleEmitter.prototype.clone = function () {
  58824. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58825. BABYLON.Tools.DeepCopy(this, newOne);
  58826. return newOne;
  58827. };
  58828. /**
  58829. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58830. * @param effect defines the update shader
  58831. */
  58832. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58833. effect.setFloat("radius", this.radius);
  58834. effect.setFloat("radiusRange", this.radiusRange);
  58835. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58836. };
  58837. /**
  58838. * Returns a string to use to update the GPU particles update shader
  58839. * @returns a string containng the defines string
  58840. */
  58841. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58842. return "#define HEMISPHERICEMITTER";
  58843. };
  58844. /**
  58845. * Returns the string "HemisphericParticleEmitter"
  58846. * @returns a string containing the class name
  58847. */
  58848. HemisphericParticleEmitter.prototype.getClassName = function () {
  58849. return "HemisphericParticleEmitter";
  58850. };
  58851. /**
  58852. * Serializes the particle system to a JSON object.
  58853. * @returns the JSON object
  58854. */
  58855. HemisphericParticleEmitter.prototype.serialize = function () {
  58856. var serializationObject = {};
  58857. serializationObject.type = this.getClassName();
  58858. serializationObject.radius = this.radius;
  58859. serializationObject.radiusRange = this.radiusRange;
  58860. serializationObject.directionRandomizer = this.directionRandomizer;
  58861. return serializationObject;
  58862. };
  58863. /**
  58864. * Parse properties from a JSON object
  58865. * @param serializationObject defines the JSON object
  58866. */
  58867. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58868. this.radius = serializationObject.radius;
  58869. this.radiusRange = serializationObject.radiusRange;
  58870. this.directionRandomizer = serializationObject.directionRandomizer;
  58871. };
  58872. return HemisphericParticleEmitter;
  58873. }());
  58874. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58875. })(BABYLON || (BABYLON = {}));
  58876. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58877. var BABYLON;
  58878. (function (BABYLON) {
  58879. /**
  58880. * Particle emitter emitting particles from a point.
  58881. * It emits the particles randomly between 2 given directions.
  58882. */
  58883. var PointParticleEmitter = /** @class */ (function () {
  58884. /**
  58885. * Creates a new instance PointParticleEmitter
  58886. */
  58887. function PointParticleEmitter() {
  58888. /**
  58889. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58890. */
  58891. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58892. /**
  58893. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58894. */
  58895. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58896. }
  58897. /**
  58898. * Called by the particle System when the direction is computed for the created particle.
  58899. * @param worldMatrix is the world matrix of the particle system
  58900. * @param directionToUpdate is the direction vector to update with the result
  58901. * @param particle is the particle we are computed the direction for
  58902. */
  58903. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58904. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58905. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58906. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58907. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58908. };
  58909. /**
  58910. * Called by the particle System when the position is computed for the created particle.
  58911. * @param worldMatrix is the world matrix of the particle system
  58912. * @param positionToUpdate is the position vector to update with the result
  58913. * @param particle is the particle we are computed the position for
  58914. */
  58915. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58916. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58917. };
  58918. /**
  58919. * Clones the current emitter and returns a copy of it
  58920. * @returns the new emitter
  58921. */
  58922. PointParticleEmitter.prototype.clone = function () {
  58923. var newOne = new PointParticleEmitter();
  58924. BABYLON.Tools.DeepCopy(this, newOne);
  58925. return newOne;
  58926. };
  58927. /**
  58928. * Called by the GPUParticleSystem to setup the update shader
  58929. * @param effect defines the update shader
  58930. */
  58931. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58932. effect.setVector3("direction1", this.direction1);
  58933. effect.setVector3("direction2", this.direction2);
  58934. };
  58935. /**
  58936. * Returns a string to use to update the GPU particles update shader
  58937. * @returns a string containng the defines string
  58938. */
  58939. PointParticleEmitter.prototype.getEffectDefines = function () {
  58940. return "#define POINTEMITTER";
  58941. };
  58942. /**
  58943. * Returns the string "PointParticleEmitter"
  58944. * @returns a string containing the class name
  58945. */
  58946. PointParticleEmitter.prototype.getClassName = function () {
  58947. return "PointParticleEmitter";
  58948. };
  58949. /**
  58950. * Serializes the particle system to a JSON object.
  58951. * @returns the JSON object
  58952. */
  58953. PointParticleEmitter.prototype.serialize = function () {
  58954. var serializationObject = {};
  58955. serializationObject.type = this.getClassName();
  58956. serializationObject.direction1 = this.direction1.asArray();
  58957. serializationObject.direction2 = this.direction2.asArray();
  58958. return serializationObject;
  58959. };
  58960. /**
  58961. * Parse properties from a JSON object
  58962. * @param serializationObject defines the JSON object
  58963. */
  58964. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58965. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58966. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58967. };
  58968. return PointParticleEmitter;
  58969. }());
  58970. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58971. })(BABYLON || (BABYLON = {}));
  58972. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58973. var BABYLON;
  58974. (function (BABYLON) {
  58975. // Adds the parsers to the scene parsers.
  58976. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58977. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58978. if (!individualParser) {
  58979. return;
  58980. }
  58981. // Particles Systems
  58982. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58983. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58984. var parsedParticleSystem = parsedData.particleSystems[index];
  58985. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58986. }
  58987. }
  58988. });
  58989. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58990. if (parsedParticleSystem.activeParticleCount) {
  58991. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58992. return ps;
  58993. }
  58994. else {
  58995. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58996. return ps;
  58997. }
  58998. });
  58999. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  59000. if (uniformsNames === void 0) { uniformsNames = []; }
  59001. if (samplers === void 0) { samplers = []; }
  59002. if (defines === void 0) { defines = ""; }
  59003. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  59004. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  59005. if (defines.indexOf(" BILLBOARD") === -1) {
  59006. defines += "\n#define BILLBOARD\n";
  59007. }
  59008. if (samplers.indexOf("diffuseSampler") === -1) {
  59009. samplers.push("diffuseSampler");
  59010. }
  59011. return this.createEffect({
  59012. vertex: "particles",
  59013. fragmentElement: fragmentName
  59014. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  59015. };
  59016. })(BABYLON || (BABYLON = {}));
  59017. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  59018. var BABYLON;
  59019. (function (BABYLON) {
  59020. /**
  59021. * Type of sub emitter
  59022. */
  59023. var SubEmitterType;
  59024. (function (SubEmitterType) {
  59025. /**
  59026. * Attached to the particle over it's lifetime
  59027. */
  59028. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  59029. /**
  59030. * Created when the particle dies
  59031. */
  59032. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  59033. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  59034. /**
  59035. * Sub emitter class used to emit particles from an existing particle
  59036. */
  59037. var SubEmitter = /** @class */ (function () {
  59038. /**
  59039. * Creates a sub emitter
  59040. * @param particleSystem the particle system to be used by the sub emitter
  59041. */
  59042. function SubEmitter(
  59043. /**
  59044. * the particle system to be used by the sub emitter
  59045. */
  59046. particleSystem) {
  59047. this.particleSystem = particleSystem;
  59048. /**
  59049. * Type of the submitter (Default: END)
  59050. */
  59051. this.type = SubEmitterType.END;
  59052. /**
  59053. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  59054. * Note: This only is supported when using an emitter of type Mesh
  59055. */
  59056. this.inheritDirection = false;
  59057. /**
  59058. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  59059. */
  59060. this.inheritedVelocityAmount = 0;
  59061. }
  59062. /**
  59063. * Clones the sub emitter
  59064. * @returns the cloned sub emitter
  59065. */
  59066. SubEmitter.prototype.clone = function () {
  59067. // Clone particle system
  59068. var emitter = this.particleSystem.emitter;
  59069. if (!emitter) {
  59070. emitter = new BABYLON.Vector3();
  59071. }
  59072. else if (emitter instanceof BABYLON.Vector3) {
  59073. emitter = emitter.clone();
  59074. }
  59075. else if (emitter instanceof BABYLON.AbstractMesh) {
  59076. emitter = new BABYLON.Mesh("", emitter._scene);
  59077. }
  59078. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  59079. // Clone properties
  59080. clone.type = this.type;
  59081. clone.inheritDirection = this.inheritDirection;
  59082. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  59083. clone.particleSystem._disposeEmitterOnDispose = true;
  59084. return clone;
  59085. };
  59086. return SubEmitter;
  59087. }());
  59088. BABYLON.SubEmitter = SubEmitter;
  59089. })(BABYLON || (BABYLON = {}));
  59090. //# sourceMappingURL=babylon.subEmitter.js.map
  59091. var BABYLON;
  59092. (function (BABYLON) {
  59093. var ShaderMaterial = /** @class */ (function (_super) {
  59094. __extends(ShaderMaterial, _super);
  59095. function ShaderMaterial(name, scene, shaderPath, options) {
  59096. var _this = _super.call(this, name, scene) || this;
  59097. _this._textures = {};
  59098. _this._textureArrays = {};
  59099. _this._floats = {};
  59100. _this._ints = {};
  59101. _this._floatsArrays = {};
  59102. _this._colors3 = {};
  59103. _this._colors3Arrays = {};
  59104. _this._colors4 = {};
  59105. _this._vectors2 = {};
  59106. _this._vectors3 = {};
  59107. _this._vectors4 = {};
  59108. _this._matrices = {};
  59109. _this._matrices3x3 = {};
  59110. _this._matrices2x2 = {};
  59111. _this._vectors2Arrays = {};
  59112. _this._vectors3Arrays = {};
  59113. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59114. _this._shaderPath = shaderPath;
  59115. options.needAlphaBlending = options.needAlphaBlending || false;
  59116. options.needAlphaTesting = options.needAlphaTesting || false;
  59117. options.attributes = options.attributes || ["position", "normal", "uv"];
  59118. options.uniforms = options.uniforms || ["worldViewProjection"];
  59119. options.uniformBuffers = options.uniformBuffers || [];
  59120. options.samplers = options.samplers || [];
  59121. options.defines = options.defines || [];
  59122. _this._options = options;
  59123. return _this;
  59124. }
  59125. ShaderMaterial.prototype.getClassName = function () {
  59126. return "ShaderMaterial";
  59127. };
  59128. ShaderMaterial.prototype.needAlphaBlending = function () {
  59129. return this._options.needAlphaBlending;
  59130. };
  59131. ShaderMaterial.prototype.needAlphaTesting = function () {
  59132. return this._options.needAlphaTesting;
  59133. };
  59134. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59135. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59136. this._options.uniforms.push(uniformName);
  59137. }
  59138. };
  59139. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59140. if (this._options.samplers.indexOf(name) === -1) {
  59141. this._options.samplers.push(name);
  59142. }
  59143. this._textures[name] = texture;
  59144. return this;
  59145. };
  59146. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59147. if (this._options.samplers.indexOf(name) === -1) {
  59148. this._options.samplers.push(name);
  59149. }
  59150. this._checkUniform(name);
  59151. this._textureArrays[name] = textures;
  59152. return this;
  59153. };
  59154. ShaderMaterial.prototype.setFloat = function (name, value) {
  59155. this._checkUniform(name);
  59156. this._floats[name] = value;
  59157. return this;
  59158. };
  59159. ShaderMaterial.prototype.setInt = function (name, value) {
  59160. this._checkUniform(name);
  59161. this._ints[name] = value;
  59162. return this;
  59163. };
  59164. ShaderMaterial.prototype.setFloats = function (name, value) {
  59165. this._checkUniform(name);
  59166. this._floatsArrays[name] = value;
  59167. return this;
  59168. };
  59169. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59170. this._checkUniform(name);
  59171. this._colors3[name] = value;
  59172. return this;
  59173. };
  59174. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59175. this._checkUniform(name);
  59176. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59177. color.toArray(arr, arr.length);
  59178. return arr;
  59179. }, []);
  59180. return this;
  59181. };
  59182. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59183. this._checkUniform(name);
  59184. this._colors4[name] = value;
  59185. return this;
  59186. };
  59187. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59188. this._checkUniform(name);
  59189. this._vectors2[name] = value;
  59190. return this;
  59191. };
  59192. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59193. this._checkUniform(name);
  59194. this._vectors3[name] = value;
  59195. return this;
  59196. };
  59197. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59198. this._checkUniform(name);
  59199. this._vectors4[name] = value;
  59200. return this;
  59201. };
  59202. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59203. this._checkUniform(name);
  59204. this._matrices[name] = value;
  59205. return this;
  59206. };
  59207. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59208. this._checkUniform(name);
  59209. this._matrices3x3[name] = value;
  59210. return this;
  59211. };
  59212. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59213. this._checkUniform(name);
  59214. this._matrices2x2[name] = value;
  59215. return this;
  59216. };
  59217. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59218. this._checkUniform(name);
  59219. this._vectors2Arrays[name] = value;
  59220. return this;
  59221. };
  59222. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59223. this._checkUniform(name);
  59224. this._vectors3Arrays[name] = value;
  59225. return this;
  59226. };
  59227. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59228. if (!mesh) {
  59229. return true;
  59230. }
  59231. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59232. return false;
  59233. }
  59234. return false;
  59235. };
  59236. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59237. var scene = this.getScene();
  59238. var engine = scene.getEngine();
  59239. if (!this.checkReadyOnEveryCall) {
  59240. if (this._renderId === scene.getRenderId()) {
  59241. if (this._checkCache(scene, mesh, useInstances)) {
  59242. return true;
  59243. }
  59244. }
  59245. }
  59246. // Instances
  59247. var defines = [];
  59248. var attribs = [];
  59249. var fallbacks = new BABYLON.EffectFallbacks();
  59250. if (useInstances) {
  59251. defines.push("#define INSTANCES");
  59252. }
  59253. for (var index = 0; index < this._options.defines.length; index++) {
  59254. defines.push(this._options.defines[index]);
  59255. }
  59256. for (var index = 0; index < this._options.attributes.length; index++) {
  59257. attribs.push(this._options.attributes[index]);
  59258. }
  59259. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59260. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59261. defines.push("#define VERTEXCOLOR");
  59262. }
  59263. // Bones
  59264. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59265. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59266. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59267. if (mesh.numBoneInfluencers > 4) {
  59268. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59269. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59270. }
  59271. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59272. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59273. fallbacks.addCPUSkinningFallback(0, mesh);
  59274. if (this._options.uniforms.indexOf("mBones") === -1) {
  59275. this._options.uniforms.push("mBones");
  59276. }
  59277. }
  59278. else {
  59279. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59280. }
  59281. // Textures
  59282. for (var name in this._textures) {
  59283. if (!this._textures[name].isReady()) {
  59284. return false;
  59285. }
  59286. }
  59287. // Alpha test
  59288. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59289. defines.push("#define ALPHATEST");
  59290. }
  59291. var previousEffect = this._effect;
  59292. var join = defines.join("\n");
  59293. this._effect = engine.createEffect(this._shaderPath, {
  59294. attributes: attribs,
  59295. uniformsNames: this._options.uniforms,
  59296. uniformBuffersNames: this._options.uniformBuffers,
  59297. samplers: this._options.samplers,
  59298. defines: join,
  59299. fallbacks: fallbacks,
  59300. onCompiled: this.onCompiled,
  59301. onError: this.onError
  59302. }, engine);
  59303. if (!this._effect.isReady()) {
  59304. return false;
  59305. }
  59306. if (previousEffect !== this._effect) {
  59307. scene.resetCachedMaterial();
  59308. }
  59309. this._renderId = scene.getRenderId();
  59310. return true;
  59311. };
  59312. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59313. var scene = this.getScene();
  59314. if (!this._effect) {
  59315. return;
  59316. }
  59317. if (this._options.uniforms.indexOf("world") !== -1) {
  59318. this._effect.setMatrix("world", world);
  59319. }
  59320. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59321. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59322. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59323. }
  59324. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59325. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59326. }
  59327. };
  59328. ShaderMaterial.prototype.bind = function (world, mesh) {
  59329. // Std values
  59330. this.bindOnlyWorldMatrix(world);
  59331. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59332. if (this._options.uniforms.indexOf("view") !== -1) {
  59333. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59334. }
  59335. if (this._options.uniforms.indexOf("projection") !== -1) {
  59336. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59337. }
  59338. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59339. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59340. }
  59341. // Bones
  59342. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59343. var name;
  59344. // Texture
  59345. for (name in this._textures) {
  59346. this._effect.setTexture(name, this._textures[name]);
  59347. }
  59348. // Texture arrays
  59349. for (name in this._textureArrays) {
  59350. this._effect.setTextureArray(name, this._textureArrays[name]);
  59351. }
  59352. // Int
  59353. for (name in this._ints) {
  59354. this._effect.setInt(name, this._ints[name]);
  59355. }
  59356. // Float
  59357. for (name in this._floats) {
  59358. this._effect.setFloat(name, this._floats[name]);
  59359. }
  59360. // Floats
  59361. for (name in this._floatsArrays) {
  59362. this._effect.setArray(name, this._floatsArrays[name]);
  59363. }
  59364. // Color3
  59365. for (name in this._colors3) {
  59366. this._effect.setColor3(name, this._colors3[name]);
  59367. }
  59368. for (name in this._colors3Arrays) {
  59369. this._effect.setArray3(name, this._colors3Arrays[name]);
  59370. }
  59371. // Color4
  59372. for (name in this._colors4) {
  59373. var color = this._colors4[name];
  59374. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59375. }
  59376. // Vector2
  59377. for (name in this._vectors2) {
  59378. this._effect.setVector2(name, this._vectors2[name]);
  59379. }
  59380. // Vector3
  59381. for (name in this._vectors3) {
  59382. this._effect.setVector3(name, this._vectors3[name]);
  59383. }
  59384. // Vector4
  59385. for (name in this._vectors4) {
  59386. this._effect.setVector4(name, this._vectors4[name]);
  59387. }
  59388. // Matrix
  59389. for (name in this._matrices) {
  59390. this._effect.setMatrix(name, this._matrices[name]);
  59391. }
  59392. // Matrix 3x3
  59393. for (name in this._matrices3x3) {
  59394. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59395. }
  59396. // Matrix 2x2
  59397. for (name in this._matrices2x2) {
  59398. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59399. }
  59400. // Vector2Array
  59401. for (name in this._vectors2Arrays) {
  59402. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59403. }
  59404. // Vector3Array
  59405. for (name in this._vectors3Arrays) {
  59406. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59407. }
  59408. }
  59409. this._afterBind(mesh);
  59410. };
  59411. ShaderMaterial.prototype.getActiveTextures = function () {
  59412. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59413. for (var name in this._textures) {
  59414. activeTextures.push(this._textures[name]);
  59415. }
  59416. for (var name in this._textureArrays) {
  59417. var array = this._textureArrays[name];
  59418. for (var index = 0; index < array.length; index++) {
  59419. activeTextures.push(array[index]);
  59420. }
  59421. }
  59422. return activeTextures;
  59423. };
  59424. ShaderMaterial.prototype.hasTexture = function (texture) {
  59425. if (_super.prototype.hasTexture.call(this, texture)) {
  59426. return true;
  59427. }
  59428. for (var name in this._textures) {
  59429. if (this._textures[name] === texture) {
  59430. return true;
  59431. }
  59432. }
  59433. for (var name in this._textureArrays) {
  59434. var array = this._textureArrays[name];
  59435. for (var index = 0; index < array.length; index++) {
  59436. if (array[index] === texture) {
  59437. return true;
  59438. }
  59439. }
  59440. }
  59441. return false;
  59442. };
  59443. ShaderMaterial.prototype.clone = function (name) {
  59444. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59445. return newShaderMaterial;
  59446. };
  59447. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59448. if (forceDisposeTextures) {
  59449. var name;
  59450. for (name in this._textures) {
  59451. this._textures[name].dispose();
  59452. }
  59453. for (name in this._textureArrays) {
  59454. var array = this._textureArrays[name];
  59455. for (var index = 0; index < array.length; index++) {
  59456. array[index].dispose();
  59457. }
  59458. }
  59459. }
  59460. this._textures = {};
  59461. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59462. };
  59463. ShaderMaterial.prototype.serialize = function () {
  59464. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59465. serializationObject.customType = "BABYLON.ShaderMaterial";
  59466. serializationObject.options = this._options;
  59467. serializationObject.shaderPath = this._shaderPath;
  59468. var name;
  59469. // Texture
  59470. serializationObject.textures = {};
  59471. for (name in this._textures) {
  59472. serializationObject.textures[name] = this._textures[name].serialize();
  59473. }
  59474. // Texture arrays
  59475. serializationObject.textureArrays = {};
  59476. for (name in this._textureArrays) {
  59477. serializationObject.textureArrays[name] = [];
  59478. var array = this._textureArrays[name];
  59479. for (var index = 0; index < array.length; index++) {
  59480. serializationObject.textureArrays[name].push(array[index].serialize());
  59481. }
  59482. }
  59483. // Float
  59484. serializationObject.floats = {};
  59485. for (name in this._floats) {
  59486. serializationObject.floats[name] = this._floats[name];
  59487. }
  59488. // Float s
  59489. serializationObject.FloatArrays = {};
  59490. for (name in this._floatsArrays) {
  59491. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59492. }
  59493. // Color3
  59494. serializationObject.colors3 = {};
  59495. for (name in this._colors3) {
  59496. serializationObject.colors3[name] = this._colors3[name].asArray();
  59497. }
  59498. // Color3 array
  59499. serializationObject.colors3Arrays = {};
  59500. for (name in this._colors3Arrays) {
  59501. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59502. }
  59503. // Color4
  59504. serializationObject.colors4 = {};
  59505. for (name in this._colors4) {
  59506. serializationObject.colors4[name] = this._colors4[name].asArray();
  59507. }
  59508. // Vector2
  59509. serializationObject.vectors2 = {};
  59510. for (name in this._vectors2) {
  59511. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59512. }
  59513. // Vector3
  59514. serializationObject.vectors3 = {};
  59515. for (name in this._vectors3) {
  59516. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59517. }
  59518. // Vector4
  59519. serializationObject.vectors4 = {};
  59520. for (name in this._vectors4) {
  59521. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59522. }
  59523. // Matrix
  59524. serializationObject.matrices = {};
  59525. for (name in this._matrices) {
  59526. serializationObject.matrices[name] = this._matrices[name].asArray();
  59527. }
  59528. // Matrix 3x3
  59529. serializationObject.matrices3x3 = {};
  59530. for (name in this._matrices3x3) {
  59531. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59532. }
  59533. // Matrix 2x2
  59534. serializationObject.matrices2x2 = {};
  59535. for (name in this._matrices2x2) {
  59536. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59537. }
  59538. // Vector2Array
  59539. serializationObject.vectors2Arrays = {};
  59540. for (name in this._vectors2Arrays) {
  59541. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59542. }
  59543. // Vector3Array
  59544. serializationObject.vectors3Arrays = {};
  59545. for (name in this._vectors3Arrays) {
  59546. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59547. }
  59548. return serializationObject;
  59549. };
  59550. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59551. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59552. var name;
  59553. // Texture
  59554. for (name in source.textures) {
  59555. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59556. }
  59557. // Texture arrays
  59558. for (name in source.textureArrays) {
  59559. var array = source.textureArrays[name];
  59560. var textureArray = new Array();
  59561. for (var index = 0; index < array.length; index++) {
  59562. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59563. }
  59564. material.setTextureArray(name, textureArray);
  59565. }
  59566. // Float
  59567. for (name in source.floats) {
  59568. material.setFloat(name, source.floats[name]);
  59569. }
  59570. // Float s
  59571. for (name in source.floatsArrays) {
  59572. material.setFloats(name, source.floatsArrays[name]);
  59573. }
  59574. // Color3
  59575. for (name in source.colors3) {
  59576. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59577. }
  59578. // Color3 arrays
  59579. for (name in source.colors3Arrays) {
  59580. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59581. if (i % 3 === 0) {
  59582. arr.push([num]);
  59583. }
  59584. else {
  59585. arr[arr.length - 1].push(num);
  59586. }
  59587. return arr;
  59588. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59589. material.setColor3Array(name, colors);
  59590. }
  59591. // Color4
  59592. for (name in source.colors4) {
  59593. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59594. }
  59595. // Vector2
  59596. for (name in source.vectors2) {
  59597. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59598. }
  59599. // Vector3
  59600. for (name in source.vectors3) {
  59601. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59602. }
  59603. // Vector4
  59604. for (name in source.vectors4) {
  59605. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59606. }
  59607. // Matrix
  59608. for (name in source.matrices) {
  59609. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59610. }
  59611. // Matrix 3x3
  59612. for (name in source.matrices3x3) {
  59613. material.setMatrix3x3(name, source.matrices3x3[name]);
  59614. }
  59615. // Matrix 2x2
  59616. for (name in source.matrices2x2) {
  59617. material.setMatrix2x2(name, source.matrices2x2[name]);
  59618. }
  59619. // Vector2Array
  59620. for (name in source.vectors2Arrays) {
  59621. material.setArray2(name, source.vectors2Arrays[name]);
  59622. }
  59623. // Vector3Array
  59624. for (name in source.vectors3Arrays) {
  59625. material.setArray3(name, source.vectors3Arrays[name]);
  59626. }
  59627. return material;
  59628. };
  59629. return ShaderMaterial;
  59630. }(BABYLON.Material));
  59631. BABYLON.ShaderMaterial = ShaderMaterial;
  59632. })(BABYLON || (BABYLON = {}));
  59633. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59634. var BABYLON;
  59635. (function (BABYLON) {
  59636. var GroundMesh = /** @class */ (function (_super) {
  59637. __extends(GroundMesh, _super);
  59638. function GroundMesh(name, scene) {
  59639. var _this = _super.call(this, name, scene) || this;
  59640. _this.generateOctree = false;
  59641. return _this;
  59642. }
  59643. GroundMesh.prototype.getClassName = function () {
  59644. return "GroundMesh";
  59645. };
  59646. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59647. get: function () {
  59648. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59649. },
  59650. enumerable: true,
  59651. configurable: true
  59652. });
  59653. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59654. get: function () {
  59655. return this._subdivisionsX;
  59656. },
  59657. enumerable: true,
  59658. configurable: true
  59659. });
  59660. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59661. get: function () {
  59662. return this._subdivisionsY;
  59663. },
  59664. enumerable: true,
  59665. configurable: true
  59666. });
  59667. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59668. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59669. this._subdivisionsX = chunksCount;
  59670. this._subdivisionsY = chunksCount;
  59671. this.subdivide(chunksCount);
  59672. // Call the octree system optimization if it is defined.
  59673. var thisAsAny = this;
  59674. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  59675. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59676. }
  59677. };
  59678. /**
  59679. * Returns a height (y) value in the Worl system :
  59680. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59681. * Returns the ground y position if (x, z) are outside the ground surface.
  59682. */
  59683. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59684. var world = this.getWorldMatrix();
  59685. var invMat = BABYLON.Tmp.Matrix[5];
  59686. world.invertToRef(invMat);
  59687. var tmpVect = BABYLON.Tmp.Vector3[8];
  59688. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59689. x = tmpVect.x;
  59690. z = tmpVect.z;
  59691. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59692. return this.position.y;
  59693. }
  59694. if (!this._heightQuads || this._heightQuads.length == 0) {
  59695. this._initHeightQuads();
  59696. this._computeHeightQuads();
  59697. }
  59698. var facet = this._getFacetAt(x, z);
  59699. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59700. // return y in the World system
  59701. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59702. return tmpVect.y;
  59703. };
  59704. /**
  59705. * Returns a normalized vector (Vector3) orthogonal to the ground
  59706. * at the ground coordinates (x, z) expressed in the World system.
  59707. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59708. */
  59709. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59710. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59711. this.getNormalAtCoordinatesToRef(x, z, normal);
  59712. return normal;
  59713. };
  59714. /**
  59715. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59716. * at the ground coordinates (x, z) expressed in the World system.
  59717. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59718. * Returns the GroundMesh.
  59719. */
  59720. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59721. var world = this.getWorldMatrix();
  59722. var tmpMat = BABYLON.Tmp.Matrix[5];
  59723. world.invertToRef(tmpMat);
  59724. var tmpVect = BABYLON.Tmp.Vector3[8];
  59725. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59726. x = tmpVect.x;
  59727. z = tmpVect.z;
  59728. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59729. return this;
  59730. }
  59731. if (!this._heightQuads || this._heightQuads.length == 0) {
  59732. this._initHeightQuads();
  59733. this._computeHeightQuads();
  59734. }
  59735. var facet = this._getFacetAt(x, z);
  59736. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59737. return this;
  59738. };
  59739. /**
  59740. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59741. * if the ground has been updated.
  59742. * This can be used in the render loop.
  59743. * Returns the GroundMesh.
  59744. */
  59745. GroundMesh.prototype.updateCoordinateHeights = function () {
  59746. if (!this._heightQuads || this._heightQuads.length == 0) {
  59747. this._initHeightQuads();
  59748. }
  59749. this._computeHeightQuads();
  59750. return this;
  59751. };
  59752. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59753. GroundMesh.prototype._getFacetAt = function (x, z) {
  59754. // retrieve col and row from x, z coordinates in the ground local system
  59755. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59756. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59757. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59758. var facet;
  59759. if (z < quad.slope.x * x + quad.slope.y) {
  59760. facet = quad.facet1;
  59761. }
  59762. else {
  59763. facet = quad.facet2;
  59764. }
  59765. return facet;
  59766. };
  59767. // Creates and populates the heightMap array with "facet" elements :
  59768. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59769. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59770. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59771. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59772. // Returns the GroundMesh.
  59773. GroundMesh.prototype._initHeightQuads = function () {
  59774. var subdivisionsX = this._subdivisionsX;
  59775. var subdivisionsY = this._subdivisionsY;
  59776. this._heightQuads = new Array();
  59777. for (var row = 0; row < subdivisionsY; row++) {
  59778. for (var col = 0; col < subdivisionsX; col++) {
  59779. 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) };
  59780. this._heightQuads[row * subdivisionsX + col] = quad;
  59781. }
  59782. }
  59783. return this;
  59784. };
  59785. // Compute each quad element values and update the the heightMap array :
  59786. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59787. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59788. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59789. // Returns the GroundMesh.
  59790. GroundMesh.prototype._computeHeightQuads = function () {
  59791. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59792. if (!positions) {
  59793. return this;
  59794. }
  59795. var v1 = BABYLON.Tmp.Vector3[3];
  59796. var v2 = BABYLON.Tmp.Vector3[2];
  59797. var v3 = BABYLON.Tmp.Vector3[1];
  59798. var v4 = BABYLON.Tmp.Vector3[0];
  59799. var v1v2 = BABYLON.Tmp.Vector3[4];
  59800. var v1v3 = BABYLON.Tmp.Vector3[5];
  59801. var v1v4 = BABYLON.Tmp.Vector3[6];
  59802. var norm1 = BABYLON.Tmp.Vector3[7];
  59803. var norm2 = BABYLON.Tmp.Vector3[8];
  59804. var i = 0;
  59805. var j = 0;
  59806. var k = 0;
  59807. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59808. var h = 0;
  59809. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59810. var d2 = 0;
  59811. var subdivisionsX = this._subdivisionsX;
  59812. var subdivisionsY = this._subdivisionsY;
  59813. for (var row = 0; row < subdivisionsY; row++) {
  59814. for (var col = 0; col < subdivisionsX; col++) {
  59815. i = col * 3;
  59816. j = row * (subdivisionsX + 1) * 3;
  59817. k = (row + 1) * (subdivisionsX + 1) * 3;
  59818. v1.x = positions[j + i];
  59819. v1.y = positions[j + i + 1];
  59820. v1.z = positions[j + i + 2];
  59821. v2.x = positions[j + i + 3];
  59822. v2.y = positions[j + i + 4];
  59823. v2.z = positions[j + i + 5];
  59824. v3.x = positions[k + i];
  59825. v3.y = positions[k + i + 1];
  59826. v3.z = positions[k + i + 2];
  59827. v4.x = positions[k + i + 3];
  59828. v4.y = positions[k + i + 4];
  59829. v4.z = positions[k + i + 5];
  59830. // 2D slope V1V4
  59831. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59832. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59833. // facet equations :
  59834. // we compute each facet normal vector
  59835. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59836. // we compute the value d by applying the equation to v1 which belongs to the plane
  59837. // then we store the facet equation in a Vector4
  59838. v2.subtractToRef(v1, v1v2);
  59839. v3.subtractToRef(v1, v1v3);
  59840. v4.subtractToRef(v1, v1v4);
  59841. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59842. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59843. norm1.normalize();
  59844. norm2.normalize();
  59845. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59846. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59847. var quad = this._heightQuads[row * subdivisionsX + col];
  59848. quad.slope.copyFromFloats(cd, h);
  59849. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59850. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59851. }
  59852. }
  59853. return this;
  59854. };
  59855. GroundMesh.prototype.serialize = function (serializationObject) {
  59856. _super.prototype.serialize.call(this, serializationObject);
  59857. serializationObject.subdivisionsX = this._subdivisionsX;
  59858. serializationObject.subdivisionsY = this._subdivisionsY;
  59859. serializationObject.minX = this._minX;
  59860. serializationObject.maxX = this._maxX;
  59861. serializationObject.minZ = this._minZ;
  59862. serializationObject.maxZ = this._maxZ;
  59863. serializationObject.width = this._width;
  59864. serializationObject.height = this._height;
  59865. };
  59866. GroundMesh.Parse = function (parsedMesh, scene) {
  59867. var result = new GroundMesh(parsedMesh.name, scene);
  59868. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59869. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59870. result._minX = parsedMesh.minX;
  59871. result._maxX = parsedMesh.maxX;
  59872. result._minZ = parsedMesh.minZ;
  59873. result._maxZ = parsedMesh.maxZ;
  59874. result._width = parsedMesh.width;
  59875. result._height = parsedMesh.height;
  59876. return result;
  59877. };
  59878. return GroundMesh;
  59879. }(BABYLON.Mesh));
  59880. BABYLON.GroundMesh = GroundMesh;
  59881. })(BABYLON || (BABYLON = {}));
  59882. //# sourceMappingURL=babylon.groundMesh.js.map
  59883. var BABYLON;
  59884. (function (BABYLON) {
  59885. /**
  59886. * Creates an instance based on a source mesh.
  59887. */
  59888. var InstancedMesh = /** @class */ (function (_super) {
  59889. __extends(InstancedMesh, _super);
  59890. function InstancedMesh(name, source) {
  59891. var _this = _super.call(this, name, source.getScene()) || this;
  59892. source.instances.push(_this);
  59893. _this._sourceMesh = source;
  59894. _this.position.copyFrom(source.position);
  59895. _this.rotation.copyFrom(source.rotation);
  59896. _this.scaling.copyFrom(source.scaling);
  59897. if (source.rotationQuaternion) {
  59898. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59899. }
  59900. _this.infiniteDistance = source.infiniteDistance;
  59901. _this.setPivotMatrix(source.getPivotMatrix());
  59902. _this.refreshBoundingInfo();
  59903. _this._syncSubMeshes();
  59904. return _this;
  59905. }
  59906. /**
  59907. * Returns the string "InstancedMesh".
  59908. */
  59909. InstancedMesh.prototype.getClassName = function () {
  59910. return "InstancedMesh";
  59911. };
  59912. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59913. // Methods
  59914. get: function () {
  59915. return this._sourceMesh.receiveShadows;
  59916. },
  59917. enumerable: true,
  59918. configurable: true
  59919. });
  59920. Object.defineProperty(InstancedMesh.prototype, "material", {
  59921. get: function () {
  59922. return this._sourceMesh.material;
  59923. },
  59924. enumerable: true,
  59925. configurable: true
  59926. });
  59927. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59928. get: function () {
  59929. return this._sourceMesh.visibility;
  59930. },
  59931. enumerable: true,
  59932. configurable: true
  59933. });
  59934. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59935. get: function () {
  59936. return this._sourceMesh.skeleton;
  59937. },
  59938. enumerable: true,
  59939. configurable: true
  59940. });
  59941. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59942. get: function () {
  59943. return this._sourceMesh.renderingGroupId;
  59944. },
  59945. set: function (value) {
  59946. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59947. return;
  59948. }
  59949. //no-op with warning
  59950. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59951. },
  59952. enumerable: true,
  59953. configurable: true
  59954. });
  59955. /**
  59956. * Returns the total number of vertices (integer).
  59957. */
  59958. InstancedMesh.prototype.getTotalVertices = function () {
  59959. return this._sourceMesh.getTotalVertices();
  59960. };
  59961. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59962. get: function () {
  59963. return this._sourceMesh;
  59964. },
  59965. enumerable: true,
  59966. configurable: true
  59967. });
  59968. /**
  59969. * Is this node ready to be used/rendered
  59970. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59971. * @return {boolean} is it ready
  59972. */
  59973. InstancedMesh.prototype.isReady = function (completeCheck) {
  59974. if (completeCheck === void 0) { completeCheck = false; }
  59975. return this._sourceMesh.isReady(completeCheck, true);
  59976. };
  59977. /**
  59978. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59979. */
  59980. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59981. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59982. };
  59983. /**
  59984. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59985. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59986. * The `data` are either a numeric array either a Float32Array.
  59987. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59988. * 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).
  59989. * Note that a new underlying VertexBuffer object is created each call.
  59990. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59991. *
  59992. * Possible `kind` values :
  59993. * - BABYLON.VertexBuffer.PositionKind
  59994. * - BABYLON.VertexBuffer.UVKind
  59995. * - BABYLON.VertexBuffer.UV2Kind
  59996. * - BABYLON.VertexBuffer.UV3Kind
  59997. * - BABYLON.VertexBuffer.UV4Kind
  59998. * - BABYLON.VertexBuffer.UV5Kind
  59999. * - BABYLON.VertexBuffer.UV6Kind
  60000. * - BABYLON.VertexBuffer.ColorKind
  60001. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60002. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60003. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60004. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60005. *
  60006. * Returns the Mesh.
  60007. */
  60008. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60009. if (this.sourceMesh) {
  60010. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60011. }
  60012. return this.sourceMesh;
  60013. };
  60014. /**
  60015. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60016. * If the mesh has no geometry, it is simply returned as it is.
  60017. * The `data` are either a numeric array either a Float32Array.
  60018. * No new underlying VertexBuffer object is created.
  60019. * 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.
  60020. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60021. *
  60022. * Possible `kind` values :
  60023. * - BABYLON.VertexBuffer.PositionKind
  60024. * - BABYLON.VertexBuffer.UVKind
  60025. * - BABYLON.VertexBuffer.UV2Kind
  60026. * - BABYLON.VertexBuffer.UV3Kind
  60027. * - BABYLON.VertexBuffer.UV4Kind
  60028. * - BABYLON.VertexBuffer.UV5Kind
  60029. * - BABYLON.VertexBuffer.UV6Kind
  60030. * - BABYLON.VertexBuffer.ColorKind
  60031. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60032. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60033. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60034. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60035. *
  60036. * Returns the Mesh.
  60037. */
  60038. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60039. if (this.sourceMesh) {
  60040. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60041. }
  60042. return this.sourceMesh;
  60043. };
  60044. /**
  60045. * Sets the mesh indices.
  60046. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60047. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60048. * This method creates a new index buffer each call.
  60049. * Returns the Mesh.
  60050. */
  60051. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60052. if (totalVertices === void 0) { totalVertices = null; }
  60053. if (this.sourceMesh) {
  60054. this.sourceMesh.setIndices(indices, totalVertices);
  60055. }
  60056. return this.sourceMesh;
  60057. };
  60058. /**
  60059. * Boolean : True if the mesh owns the requested kind of data.
  60060. */
  60061. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60062. return this._sourceMesh.isVerticesDataPresent(kind);
  60063. };
  60064. /**
  60065. * Returns an array of indices (IndicesArray).
  60066. */
  60067. InstancedMesh.prototype.getIndices = function () {
  60068. return this._sourceMesh.getIndices();
  60069. };
  60070. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60071. get: function () {
  60072. return this._sourceMesh._positions;
  60073. },
  60074. enumerable: true,
  60075. configurable: true
  60076. });
  60077. /**
  60078. * Sets a new updated BoundingInfo to the mesh.
  60079. * Returns the mesh.
  60080. */
  60081. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60082. var meshBB = this._sourceMesh.getBoundingInfo();
  60083. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60084. this._updateBoundingInfo();
  60085. return this;
  60086. };
  60087. /** @hidden */
  60088. InstancedMesh.prototype._preActivate = function () {
  60089. if (this._currentLOD) {
  60090. this._currentLOD._preActivate();
  60091. }
  60092. return this;
  60093. };
  60094. /** @hidden */
  60095. InstancedMesh.prototype._activate = function (renderId) {
  60096. if (this._currentLOD) {
  60097. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60098. }
  60099. return this;
  60100. };
  60101. /**
  60102. * Returns the current associated LOD AbstractMesh.
  60103. */
  60104. InstancedMesh.prototype.getLOD = function (camera) {
  60105. if (!camera) {
  60106. return this;
  60107. }
  60108. var boundingInfo = this.getBoundingInfo();
  60109. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60110. if (this._currentLOD === this.sourceMesh) {
  60111. return this;
  60112. }
  60113. return this._currentLOD;
  60114. };
  60115. /** @hidden */
  60116. InstancedMesh.prototype._syncSubMeshes = function () {
  60117. this.releaseSubMeshes();
  60118. if (this._sourceMesh.subMeshes) {
  60119. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60120. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60121. }
  60122. }
  60123. return this;
  60124. };
  60125. /** @hidden */
  60126. InstancedMesh.prototype._generatePointsArray = function () {
  60127. return this._sourceMesh._generatePointsArray();
  60128. };
  60129. /**
  60130. * Creates a new InstancedMesh from the current mesh.
  60131. * - name (string) : the cloned mesh name
  60132. * - newParent (optional Node) : the optional Node to parent the clone to.
  60133. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60134. *
  60135. * Returns the clone.
  60136. */
  60137. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60138. var result = this._sourceMesh.createInstance(name);
  60139. // Deep copy
  60140. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60141. // Bounding info
  60142. this.refreshBoundingInfo();
  60143. // Parent
  60144. if (newParent) {
  60145. result.parent = newParent;
  60146. }
  60147. if (!doNotCloneChildren) {
  60148. // Children
  60149. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60150. var mesh = this.getScene().meshes[index];
  60151. if (mesh.parent === this) {
  60152. mesh.clone(mesh.name, result);
  60153. }
  60154. }
  60155. }
  60156. result.computeWorldMatrix(true);
  60157. return result;
  60158. };
  60159. /**
  60160. * Disposes the InstancedMesh.
  60161. * Returns nothing.
  60162. */
  60163. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60164. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60165. // Remove from mesh
  60166. var index = this._sourceMesh.instances.indexOf(this);
  60167. this._sourceMesh.instances.splice(index, 1);
  60168. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60169. };
  60170. return InstancedMesh;
  60171. }(BABYLON.AbstractMesh));
  60172. BABYLON.InstancedMesh = InstancedMesh;
  60173. })(BABYLON || (BABYLON = {}));
  60174. //# sourceMappingURL=babylon.instancedMesh.js.map
  60175. var BABYLON;
  60176. (function (BABYLON) {
  60177. var LinesMesh = /** @class */ (function (_super) {
  60178. __extends(LinesMesh, _super);
  60179. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60180. if (scene === void 0) { scene = null; }
  60181. if (parent === void 0) { parent = null; }
  60182. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60183. _this.useVertexColor = useVertexColor;
  60184. _this.useVertexAlpha = useVertexAlpha;
  60185. _this.color = new BABYLON.Color3(1, 1, 1);
  60186. _this.alpha = 1;
  60187. if (source) {
  60188. _this.color = source.color.clone();
  60189. _this.alpha = source.alpha;
  60190. _this.useVertexColor = source.useVertexColor;
  60191. _this.useVertexAlpha = source.useVertexAlpha;
  60192. }
  60193. _this._intersectionThreshold = 0.1;
  60194. var defines = [];
  60195. var options = {
  60196. attributes: [BABYLON.VertexBuffer.PositionKind],
  60197. uniforms: ["world", "viewProjection"],
  60198. needAlphaBlending: true,
  60199. defines: defines
  60200. };
  60201. if (useVertexAlpha === false) {
  60202. options.needAlphaBlending = false;
  60203. }
  60204. if (!useVertexColor) {
  60205. options.uniforms.push("color");
  60206. }
  60207. else {
  60208. options.defines.push("#define VERTEXCOLOR");
  60209. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60210. }
  60211. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60212. return _this;
  60213. }
  60214. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60215. /**
  60216. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60217. * This margin is expressed in world space coordinates, so its value may vary.
  60218. * Default value is 0.1
  60219. * @returns the intersection Threshold value.
  60220. */
  60221. get: function () {
  60222. return this._intersectionThreshold;
  60223. },
  60224. /**
  60225. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60226. * This margin is expressed in world space coordinates, so its value may vary.
  60227. * @param value the new threshold to apply
  60228. */
  60229. set: function (value) {
  60230. if (this._intersectionThreshold === value) {
  60231. return;
  60232. }
  60233. this._intersectionThreshold = value;
  60234. if (this.geometry) {
  60235. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60236. }
  60237. },
  60238. enumerable: true,
  60239. configurable: true
  60240. });
  60241. /**
  60242. * Returns the string "LineMesh"
  60243. */
  60244. LinesMesh.prototype.getClassName = function () {
  60245. return "LinesMesh";
  60246. };
  60247. Object.defineProperty(LinesMesh.prototype, "material", {
  60248. /**
  60249. * @hidden
  60250. */
  60251. get: function () {
  60252. return this._colorShader;
  60253. },
  60254. /**
  60255. * @hidden
  60256. */
  60257. set: function (value) {
  60258. // Do nothing
  60259. },
  60260. enumerable: true,
  60261. configurable: true
  60262. });
  60263. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60264. /**
  60265. * @hidden
  60266. */
  60267. get: function () {
  60268. return false;
  60269. },
  60270. enumerable: true,
  60271. configurable: true
  60272. });
  60273. LinesMesh.prototype.createInstance = function (name) {
  60274. throw new Error("LinesMeshes do not support createInstance.");
  60275. };
  60276. /** @hidden */
  60277. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60278. if (!this._geometry) {
  60279. return this;
  60280. }
  60281. // VBOs
  60282. this._geometry._bind(this._colorShader.getEffect());
  60283. // Color
  60284. if (!this.useVertexColor) {
  60285. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60286. }
  60287. return this;
  60288. };
  60289. /** @hidden */
  60290. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60291. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60292. return this;
  60293. }
  60294. var engine = this.getScene().getEngine();
  60295. // Draw order
  60296. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60297. return this;
  60298. };
  60299. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60300. this._colorShader.dispose();
  60301. _super.prototype.dispose.call(this, doNotRecurse);
  60302. };
  60303. /**
  60304. * Returns a new LineMesh object cloned from the current one.
  60305. */
  60306. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60307. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60308. };
  60309. return LinesMesh;
  60310. }(BABYLON.Mesh));
  60311. BABYLON.LinesMesh = LinesMesh;
  60312. })(BABYLON || (BABYLON = {}));
  60313. //# sourceMappingURL=babylon.linesMesh.js.map
  60314. var BABYLON;
  60315. (function (BABYLON) {
  60316. /**
  60317. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60318. * The underlying implementation relies on an associative array to ensure the best performances.
  60319. * The value can be anything including 'null' but except 'undefined'
  60320. */
  60321. var StringDictionary = /** @class */ (function () {
  60322. function StringDictionary() {
  60323. this._count = 0;
  60324. this._data = {};
  60325. }
  60326. /**
  60327. * This will clear this dictionary and copy the content from the 'source' one.
  60328. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60329. * @param source the dictionary to take the content from and copy to this dictionary
  60330. */
  60331. StringDictionary.prototype.copyFrom = function (source) {
  60332. var _this = this;
  60333. this.clear();
  60334. source.forEach(function (t, v) { return _this.add(t, v); });
  60335. };
  60336. /**
  60337. * Get a value based from its key
  60338. * @param key the given key to get the matching value from
  60339. * @return the value if found, otherwise undefined is returned
  60340. */
  60341. StringDictionary.prototype.get = function (key) {
  60342. var val = this._data[key];
  60343. if (val !== undefined) {
  60344. return val;
  60345. }
  60346. return undefined;
  60347. };
  60348. /**
  60349. * Get a value from its key or add it if it doesn't exist.
  60350. * This method will ensure you that a given key/data will be present in the dictionary.
  60351. * @param key the given key to get the matching value from
  60352. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60353. * The factory will only be invoked if there's no data for the given key.
  60354. * @return the value corresponding to the key.
  60355. */
  60356. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60357. var val = this.get(key);
  60358. if (val !== undefined) {
  60359. return val;
  60360. }
  60361. val = factory(key);
  60362. if (val) {
  60363. this.add(key, val);
  60364. }
  60365. return val;
  60366. };
  60367. /**
  60368. * Get a value from its key if present in the dictionary otherwise add it
  60369. * @param key the key to get the value from
  60370. * @param val if there's no such key/value pair in the dictionary add it with this value
  60371. * @return the value corresponding to the key
  60372. */
  60373. StringDictionary.prototype.getOrAdd = function (key, val) {
  60374. var curVal = this.get(key);
  60375. if (curVal !== undefined) {
  60376. return curVal;
  60377. }
  60378. this.add(key, val);
  60379. return val;
  60380. };
  60381. /**
  60382. * Check if there's a given key in the dictionary
  60383. * @param key the key to check for
  60384. * @return true if the key is present, false otherwise
  60385. */
  60386. StringDictionary.prototype.contains = function (key) {
  60387. return this._data[key] !== undefined;
  60388. };
  60389. /**
  60390. * Add a new key and its corresponding value
  60391. * @param key the key to add
  60392. * @param value the value corresponding to the key
  60393. * @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
  60394. */
  60395. StringDictionary.prototype.add = function (key, value) {
  60396. if (this._data[key] !== undefined) {
  60397. return false;
  60398. }
  60399. this._data[key] = value;
  60400. ++this._count;
  60401. return true;
  60402. };
  60403. StringDictionary.prototype.set = function (key, value) {
  60404. if (this._data[key] === undefined) {
  60405. return false;
  60406. }
  60407. this._data[key] = value;
  60408. return true;
  60409. };
  60410. /**
  60411. * Get the element of the given key and remove it from the dictionary
  60412. * @param key
  60413. */
  60414. StringDictionary.prototype.getAndRemove = function (key) {
  60415. var val = this.get(key);
  60416. if (val !== undefined) {
  60417. delete this._data[key];
  60418. --this._count;
  60419. return val;
  60420. }
  60421. return null;
  60422. };
  60423. /**
  60424. * Remove a key/value from the dictionary.
  60425. * @param key the key to remove
  60426. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60427. */
  60428. StringDictionary.prototype.remove = function (key) {
  60429. if (this.contains(key)) {
  60430. delete this._data[key];
  60431. --this._count;
  60432. return true;
  60433. }
  60434. return false;
  60435. };
  60436. /**
  60437. * Clear the whole content of the dictionary
  60438. */
  60439. StringDictionary.prototype.clear = function () {
  60440. this._data = {};
  60441. this._count = 0;
  60442. };
  60443. Object.defineProperty(StringDictionary.prototype, "count", {
  60444. get: function () {
  60445. return this._count;
  60446. },
  60447. enumerable: true,
  60448. configurable: true
  60449. });
  60450. /**
  60451. * Execute a callback on each key/val of the dictionary.
  60452. * Note that you can remove any element in this dictionary in the callback implementation
  60453. * @param callback the callback to execute on a given key/value pair
  60454. */
  60455. StringDictionary.prototype.forEach = function (callback) {
  60456. for (var cur in this._data) {
  60457. var val = this._data[cur];
  60458. callback(cur, val);
  60459. }
  60460. };
  60461. /**
  60462. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60463. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60464. * Note that you can remove any element in this dictionary in the callback implementation
  60465. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60466. */
  60467. StringDictionary.prototype.first = function (callback) {
  60468. for (var cur in this._data) {
  60469. var val = this._data[cur];
  60470. var res = callback(cur, val);
  60471. if (res) {
  60472. return res;
  60473. }
  60474. }
  60475. return null;
  60476. };
  60477. return StringDictionary;
  60478. }());
  60479. BABYLON.StringDictionary = StringDictionary;
  60480. })(BABYLON || (BABYLON = {}));
  60481. //# sourceMappingURL=babylon.stringDictionary.js.map
  60482. var BABYLON;
  60483. (function (BABYLON) {
  60484. var Debug;
  60485. (function (Debug) {
  60486. /**
  60487. * Class used to render a debug view of a given skeleton
  60488. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60489. */
  60490. var SkeletonViewer = /** @class */ (function () {
  60491. /**
  60492. * Creates a new SkeletonViewer
  60493. * @param skeleton defines the skeleton to render
  60494. * @param mesh defines the mesh attached to the skeleton
  60495. * @param scene defines the hosting scene
  60496. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60497. * @param renderingGroupId defines the rendering group id to use with the viewer
  60498. */
  60499. function SkeletonViewer(
  60500. /** defines the skeleton to render */
  60501. skeleton,
  60502. /** defines the mesh attached to the skeleton */
  60503. mesh, scene,
  60504. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60505. autoUpdateBonesMatrices,
  60506. /** defines the rendering group id to use with the viewer */
  60507. renderingGroupId) {
  60508. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60509. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60510. this.skeleton = skeleton;
  60511. this.mesh = mesh;
  60512. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60513. this.renderingGroupId = renderingGroupId;
  60514. /** Gets or sets the color used to render the skeleton */
  60515. this.color = BABYLON.Color3.White();
  60516. this._debugLines = new Array();
  60517. this._isEnabled = false;
  60518. this._scene = scene;
  60519. this.update();
  60520. this._renderFunction = this.update.bind(this);
  60521. }
  60522. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60523. get: function () {
  60524. return this._isEnabled;
  60525. },
  60526. /** Gets or sets a boolean indicating if the viewer is enabled */
  60527. set: function (value) {
  60528. if (this._isEnabled === value) {
  60529. return;
  60530. }
  60531. this._isEnabled = value;
  60532. if (value) {
  60533. this._scene.registerBeforeRender(this._renderFunction);
  60534. }
  60535. else {
  60536. this._scene.unregisterBeforeRender(this._renderFunction);
  60537. }
  60538. },
  60539. enumerable: true,
  60540. configurable: true
  60541. });
  60542. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60543. if (x === void 0) { x = 0; }
  60544. if (y === void 0) { y = 0; }
  60545. if (z === void 0) { z = 0; }
  60546. var tmat = BABYLON.Tmp.Matrix[0];
  60547. var parentBone = bone.getParent();
  60548. tmat.copyFrom(bone.getLocalMatrix());
  60549. if (x !== 0 || y !== 0 || z !== 0) {
  60550. var tmat2 = BABYLON.Tmp.Matrix[1];
  60551. BABYLON.Matrix.IdentityToRef(tmat2);
  60552. tmat2.m[12] = x;
  60553. tmat2.m[13] = y;
  60554. tmat2.m[14] = z;
  60555. tmat2.multiplyToRef(tmat, tmat);
  60556. }
  60557. if (parentBone) {
  60558. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60559. }
  60560. tmat.multiplyToRef(meshMat, tmat);
  60561. position.x = tmat.m[12];
  60562. position.y = tmat.m[13];
  60563. position.z = tmat.m[14];
  60564. };
  60565. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60566. var len = bones.length;
  60567. var meshPos = this.mesh.position;
  60568. for (var i = 0; i < len; i++) {
  60569. var bone = bones[i];
  60570. var points = this._debugLines[i];
  60571. if (!points) {
  60572. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60573. this._debugLines[i] = points;
  60574. }
  60575. this._getBonePosition(points[0], bone, meshMat);
  60576. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60577. points[0].subtractInPlace(meshPos);
  60578. points[1].subtractInPlace(meshPos);
  60579. }
  60580. };
  60581. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60582. var len = bones.length;
  60583. var boneNum = 0;
  60584. var meshPos = this.mesh.position;
  60585. for (var i = len - 1; i >= 0; i--) {
  60586. var childBone = bones[i];
  60587. var parentBone = childBone.getParent();
  60588. if (!parentBone) {
  60589. continue;
  60590. }
  60591. var points = this._debugLines[boneNum];
  60592. if (!points) {
  60593. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60594. this._debugLines[boneNum] = points;
  60595. }
  60596. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60597. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60598. points[0].subtractInPlace(meshPos);
  60599. points[1].subtractInPlace(meshPos);
  60600. boneNum++;
  60601. }
  60602. };
  60603. /** Update the viewer to sync with current skeleton state */
  60604. SkeletonViewer.prototype.update = function () {
  60605. if (this.autoUpdateBonesMatrices) {
  60606. this.skeleton.computeAbsoluteTransforms();
  60607. }
  60608. if (this.skeleton.bones[0].length === undefined) {
  60609. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60610. }
  60611. else {
  60612. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60613. }
  60614. if (!this._debugMesh) {
  60615. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60616. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60617. }
  60618. else {
  60619. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60620. }
  60621. this._debugMesh.position.copyFrom(this.mesh.position);
  60622. this._debugMesh.color = this.color;
  60623. };
  60624. /** Release associated resources */
  60625. SkeletonViewer.prototype.dispose = function () {
  60626. if (this._debugMesh) {
  60627. this.isEnabled = false;
  60628. this._debugMesh.dispose();
  60629. this._debugMesh = null;
  60630. }
  60631. };
  60632. return SkeletonViewer;
  60633. }());
  60634. Debug.SkeletonViewer = SkeletonViewer;
  60635. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60636. })(BABYLON || (BABYLON = {}));
  60637. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60638. /**
  60639. * Module Debug contains the (visual) components to debug a scene correctly
  60640. */
  60641. var BABYLON;
  60642. (function (BABYLON) {
  60643. var Debug;
  60644. (function (Debug) {
  60645. /**
  60646. * The Axes viewer will show 3 axes in a specific point in space
  60647. */
  60648. var AxesViewer = /** @class */ (function () {
  60649. /**
  60650. * Creates a new AxesViewer
  60651. * @param scene defines the hosting scene
  60652. * @param scaleLines defines a number used to scale line length (1 by default)
  60653. */
  60654. function AxesViewer(scene, scaleLines) {
  60655. if (scaleLines === void 0) { scaleLines = 1; }
  60656. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60657. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60658. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60659. /**
  60660. * Gets or sets a number used to scale line length
  60661. */
  60662. this.scaleLines = 1;
  60663. this.scaleLines = scaleLines;
  60664. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60665. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60666. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60667. this._xmesh.renderingGroupId = 2;
  60668. this._ymesh.renderingGroupId = 2;
  60669. this._zmesh.renderingGroupId = 2;
  60670. this._xmesh.material.checkReadyOnlyOnce = true;
  60671. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60672. this._ymesh.material.checkReadyOnlyOnce = true;
  60673. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60674. this._zmesh.material.checkReadyOnlyOnce = true;
  60675. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60676. this.scene = scene;
  60677. }
  60678. /**
  60679. * Force the viewer to update
  60680. * @param position defines the position of the viewer
  60681. * @param xaxis defines the x axis of the viewer
  60682. * @param yaxis defines the y axis of the viewer
  60683. * @param zaxis defines the z axis of the viewer
  60684. */
  60685. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60686. var scaleLines = this.scaleLines;
  60687. if (this._xmesh) {
  60688. this._xmesh.position.copyFrom(position);
  60689. }
  60690. if (this._ymesh) {
  60691. this._ymesh.position.copyFrom(position);
  60692. }
  60693. if (this._zmesh) {
  60694. this._zmesh.position.copyFrom(position);
  60695. }
  60696. var point2 = this._xline[1];
  60697. point2.x = xaxis.x * scaleLines;
  60698. point2.y = xaxis.y * scaleLines;
  60699. point2.z = xaxis.z * scaleLines;
  60700. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60701. point2 = this._yline[1];
  60702. point2.x = yaxis.x * scaleLines;
  60703. point2.y = yaxis.y * scaleLines;
  60704. point2.z = yaxis.z * scaleLines;
  60705. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60706. point2 = this._zline[1];
  60707. point2.x = zaxis.x * scaleLines;
  60708. point2.y = zaxis.y * scaleLines;
  60709. point2.z = zaxis.z * scaleLines;
  60710. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60711. };
  60712. /** Releases resources */
  60713. AxesViewer.prototype.dispose = function () {
  60714. if (this._xmesh) {
  60715. this._xmesh.dispose();
  60716. }
  60717. if (this._ymesh) {
  60718. this._ymesh.dispose();
  60719. }
  60720. if (this._zmesh) {
  60721. this._zmesh.dispose();
  60722. }
  60723. this._xmesh = null;
  60724. this._ymesh = null;
  60725. this._zmesh = null;
  60726. this.scene = null;
  60727. };
  60728. return AxesViewer;
  60729. }());
  60730. Debug.AxesViewer = AxesViewer;
  60731. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60732. })(BABYLON || (BABYLON = {}));
  60733. //# sourceMappingURL=babylon.axesViewer.js.map
  60734. var BABYLON;
  60735. (function (BABYLON) {
  60736. var Debug;
  60737. (function (Debug) {
  60738. /**
  60739. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60740. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60741. */
  60742. var BoneAxesViewer = /** @class */ (function (_super) {
  60743. __extends(BoneAxesViewer, _super);
  60744. /**
  60745. * Creates a new BoneAxesViewer
  60746. * @param scene defines the hosting scene
  60747. * @param bone defines the target bone
  60748. * @param mesh defines the target mesh
  60749. * @param scaleLines defines a scaling factor for line length (1 by default)
  60750. */
  60751. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60752. if (scaleLines === void 0) { scaleLines = 1; }
  60753. var _this = _super.call(this, scene, scaleLines) || this;
  60754. /** Gets current position */
  60755. _this.pos = BABYLON.Vector3.Zero();
  60756. /** Gets direction of X axis */
  60757. _this.xaxis = BABYLON.Vector3.Zero();
  60758. /** Gets direction of Y axis */
  60759. _this.yaxis = BABYLON.Vector3.Zero();
  60760. /** Gets direction of Z axis */
  60761. _this.zaxis = BABYLON.Vector3.Zero();
  60762. _this.mesh = mesh;
  60763. _this.bone = bone;
  60764. return _this;
  60765. }
  60766. /**
  60767. * Force the viewer to update
  60768. */
  60769. BoneAxesViewer.prototype.update = function () {
  60770. if (!this.mesh || !this.bone) {
  60771. return;
  60772. }
  60773. var bone = this.bone;
  60774. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60775. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60776. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60777. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60778. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60779. };
  60780. /** Releases resources */
  60781. BoneAxesViewer.prototype.dispose = function () {
  60782. if (this.mesh) {
  60783. this.mesh = null;
  60784. this.bone = null;
  60785. _super.prototype.dispose.call(this);
  60786. }
  60787. };
  60788. return BoneAxesViewer;
  60789. }(Debug.AxesViewer));
  60790. Debug.BoneAxesViewer = BoneAxesViewer;
  60791. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60792. })(BABYLON || (BABYLON = {}));
  60793. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60794. var BABYLON;
  60795. (function (BABYLON) {
  60796. var RayHelper = /** @class */ (function () {
  60797. function RayHelper(ray) {
  60798. this.ray = ray;
  60799. }
  60800. RayHelper.CreateAndShow = function (ray, scene, color) {
  60801. var helper = new RayHelper(ray);
  60802. helper.show(scene, color);
  60803. return helper;
  60804. };
  60805. RayHelper.prototype.show = function (scene, color) {
  60806. if (!this._renderFunction && this.ray) {
  60807. var ray = this.ray;
  60808. this._renderFunction = this._render.bind(this);
  60809. this._scene = scene;
  60810. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60811. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60812. if (this._renderFunction) {
  60813. this._scene.registerBeforeRender(this._renderFunction);
  60814. }
  60815. }
  60816. if (color && this._renderLine) {
  60817. this._renderLine.color.copyFrom(color);
  60818. }
  60819. };
  60820. RayHelper.prototype.hide = function () {
  60821. if (this._renderFunction && this._scene) {
  60822. this._scene.unregisterBeforeRender(this._renderFunction);
  60823. this._scene = null;
  60824. this._renderFunction = null;
  60825. if (this._renderLine) {
  60826. this._renderLine.dispose();
  60827. this._renderLine = null;
  60828. }
  60829. this._renderPoints = [];
  60830. }
  60831. };
  60832. RayHelper.prototype._render = function () {
  60833. var ray = this.ray;
  60834. if (!ray) {
  60835. return;
  60836. }
  60837. var point = this._renderPoints[1];
  60838. var len = Math.min(ray.length, 1000000);
  60839. point.copyFrom(ray.direction);
  60840. point.scaleInPlace(len);
  60841. point.addInPlace(ray.origin);
  60842. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60843. };
  60844. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60845. this._attachedToMesh = mesh;
  60846. var ray = this.ray;
  60847. if (!ray) {
  60848. return;
  60849. }
  60850. if (!ray.direction) {
  60851. ray.direction = BABYLON.Vector3.Zero();
  60852. }
  60853. if (!ray.origin) {
  60854. ray.origin = BABYLON.Vector3.Zero();
  60855. }
  60856. if (length) {
  60857. ray.length = length;
  60858. }
  60859. if (!meshSpaceOrigin) {
  60860. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60861. }
  60862. if (!meshSpaceDirection) {
  60863. // -1 so that this will work with Mesh.lookAt
  60864. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60865. }
  60866. if (!this._meshSpaceDirection) {
  60867. this._meshSpaceDirection = meshSpaceDirection.clone();
  60868. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60869. }
  60870. else {
  60871. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60872. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60873. }
  60874. if (!this._updateToMeshFunction) {
  60875. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60876. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60877. }
  60878. this._updateToMesh();
  60879. };
  60880. RayHelper.prototype.detachFromMesh = function () {
  60881. if (this._attachedToMesh) {
  60882. if (this._updateToMeshFunction) {
  60883. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60884. }
  60885. this._attachedToMesh = null;
  60886. this._updateToMeshFunction = null;
  60887. }
  60888. };
  60889. RayHelper.prototype._updateToMesh = function () {
  60890. var ray = this.ray;
  60891. if (!this._attachedToMesh || !ray) {
  60892. return;
  60893. }
  60894. if (this._attachedToMesh._isDisposed) {
  60895. this.detachFromMesh();
  60896. return;
  60897. }
  60898. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60899. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60900. };
  60901. RayHelper.prototype.dispose = function () {
  60902. this.hide();
  60903. this.detachFromMesh();
  60904. this.ray = null;
  60905. };
  60906. return RayHelper;
  60907. }());
  60908. BABYLON.RayHelper = RayHelper;
  60909. })(BABYLON || (BABYLON = {}));
  60910. //# sourceMappingURL=babylon.rayHelper.js.map
  60911. var BABYLON;
  60912. (function (BABYLON) {
  60913. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  60914. get: function () {
  60915. if (!this._debugLayer) {
  60916. this._debugLayer = new DebugLayer(this);
  60917. }
  60918. return this._debugLayer;
  60919. },
  60920. enumerable: true,
  60921. configurable: true
  60922. });
  60923. var DebugLayer = /** @class */ (function () {
  60924. function DebugLayer(scene) {
  60925. var _this = this;
  60926. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60927. this.onPropertyChangedObservable = new BABYLON.Observable();
  60928. this._scene = scene;
  60929. this._scene.onDisposeObservable.add(function () {
  60930. // Debug layer
  60931. if (_this._scene._debugLayer) {
  60932. _this._scene._debugLayer.hide();
  60933. }
  60934. });
  60935. }
  60936. /** Creates the inspector window. */
  60937. DebugLayer.prototype._createInspector = function (config) {
  60938. if (config === void 0) { config = {}; }
  60939. var popup = config.popup || false;
  60940. var initialTab = config.initialTab || 0;
  60941. var parentElement = config.parentElement || null;
  60942. if (!this._inspector) {
  60943. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60944. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60945. } // else nothing to do as instance is already created
  60946. };
  60947. DebugLayer.prototype.isVisible = function () {
  60948. if (!this._inspector) {
  60949. return false;
  60950. }
  60951. return true;
  60952. };
  60953. DebugLayer.prototype.hide = function () {
  60954. if (this._inspector) {
  60955. try {
  60956. this._inspector.dispose();
  60957. }
  60958. catch (e) {
  60959. // If the inspector has been removed directly from the inspector tool
  60960. }
  60961. this.onPropertyChangedObservable.clear();
  60962. this._inspector = null;
  60963. }
  60964. };
  60965. /**
  60966. *
  60967. * Launch the debugLayer.
  60968. *
  60969. * initialTab:
  60970. * | Value | Tab Name |
  60971. * | --- | --- |
  60972. * | 0 | Scene |
  60973. * | 1 | Console |
  60974. * | 2 | Stats |
  60975. * | 3 | Textures |
  60976. * | 4 | Mesh |
  60977. * | 5 | Light |
  60978. * | 6 | Material |
  60979. * | 7 | GLTF |
  60980. * | 8 | GUI |
  60981. * | 9 | Physics |
  60982. * | 10 | Camera |
  60983. * | 11 | Audio |
  60984. *
  60985. */
  60986. DebugLayer.prototype.show = function (config) {
  60987. if (config === void 0) { config = {}; }
  60988. if (typeof this.BJSINSPECTOR == 'undefined') {
  60989. // Load inspector and add it to the DOM
  60990. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60991. }
  60992. else {
  60993. // Otherwise creates the inspector
  60994. this._createInspector(config);
  60995. }
  60996. };
  60997. /**
  60998. * Gets the active tab
  60999. * @return the index of the active tab or -1 if the inspector is hidden
  61000. */
  61001. DebugLayer.prototype.getActiveTab = function () {
  61002. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  61003. };
  61004. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61005. return DebugLayer;
  61006. }());
  61007. BABYLON.DebugLayer = DebugLayer;
  61008. })(BABYLON || (BABYLON = {}));
  61009. //# sourceMappingURL=babylon.debugLayer.js.map
  61010. var BABYLON;
  61011. (function (BABYLON) {
  61012. var Debug;
  61013. (function (Debug) {
  61014. /**
  61015. * Used to show the physics impostor around the specific mesh
  61016. */
  61017. var PhysicsViewer = /** @class */ (function () {
  61018. /**
  61019. * Creates a new PhysicsViewer
  61020. * @param scene defines the hosting scene
  61021. */
  61022. function PhysicsViewer(scene) {
  61023. /** @hidden */
  61024. this._impostors = [];
  61025. /** @hidden */
  61026. this._meshes = [];
  61027. /** @hidden */
  61028. this._numMeshes = 0;
  61029. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61030. var physicEngine = this._scene.getPhysicsEngine();
  61031. if (physicEngine) {
  61032. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  61033. }
  61034. }
  61035. /** @hidden */
  61036. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61037. var plugin = this._physicsEnginePlugin;
  61038. for (var i = 0; i < this._numMeshes; i++) {
  61039. var impostor = this._impostors[i];
  61040. if (!impostor) {
  61041. continue;
  61042. }
  61043. if (impostor.isDisposed) {
  61044. this.hideImpostor(this._impostors[i--]);
  61045. }
  61046. else {
  61047. var mesh = this._meshes[i];
  61048. if (mesh && plugin) {
  61049. plugin.syncMeshWithImpostor(mesh, impostor);
  61050. }
  61051. }
  61052. }
  61053. };
  61054. /**
  61055. * Renders a specified physic impostor
  61056. * @param impostor defines the impostor to render
  61057. */
  61058. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61059. if (!this._scene) {
  61060. return;
  61061. }
  61062. for (var i = 0; i < this._numMeshes; i++) {
  61063. if (this._impostors[i] == impostor) {
  61064. return;
  61065. }
  61066. }
  61067. var debugMesh = this._getDebugMesh(impostor, this._scene);
  61068. if (debugMesh) {
  61069. this._impostors[this._numMeshes] = impostor;
  61070. this._meshes[this._numMeshes] = debugMesh;
  61071. if (this._numMeshes === 0) {
  61072. this._renderFunction = this._updateDebugMeshes.bind(this);
  61073. this._scene.registerBeforeRender(this._renderFunction);
  61074. }
  61075. this._numMeshes++;
  61076. }
  61077. };
  61078. /**
  61079. * Hides a specified physic impostor
  61080. * @param impostor defines the impostor to hide
  61081. */
  61082. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61083. if (!impostor || !this._scene) {
  61084. return;
  61085. }
  61086. var removed = false;
  61087. for (var i = 0; i < this._numMeshes; i++) {
  61088. if (this._impostors[i] == impostor) {
  61089. var mesh = this._meshes[i];
  61090. if (!mesh) {
  61091. continue;
  61092. }
  61093. this._scene.removeMesh(mesh);
  61094. mesh.dispose();
  61095. this._numMeshes--;
  61096. if (this._numMeshes > 0) {
  61097. this._meshes[i] = this._meshes[this._numMeshes];
  61098. this._impostors[i] = this._impostors[this._numMeshes];
  61099. this._meshes[this._numMeshes] = null;
  61100. this._impostors[this._numMeshes] = null;
  61101. }
  61102. else {
  61103. this._meshes[0] = null;
  61104. this._impostors[0] = null;
  61105. }
  61106. removed = true;
  61107. break;
  61108. }
  61109. }
  61110. if (removed && this._numMeshes === 0) {
  61111. this._scene.unregisterBeforeRender(this._renderFunction);
  61112. }
  61113. };
  61114. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  61115. if (!this._debugMaterial) {
  61116. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  61117. this._debugMaterial.wireframe = true;
  61118. }
  61119. return this._debugMaterial;
  61120. };
  61121. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  61122. if (!this._debugBoxMesh) {
  61123. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  61124. this._debugBoxMesh.renderingGroupId = 1;
  61125. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61126. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  61127. scene.removeMesh(this._debugBoxMesh);
  61128. }
  61129. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  61130. };
  61131. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  61132. if (!this._debugSphereMesh) {
  61133. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  61134. this._debugSphereMesh.renderingGroupId = 1;
  61135. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61136. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  61137. scene.removeMesh(this._debugSphereMesh);
  61138. }
  61139. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  61140. };
  61141. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  61142. var mesh = null;
  61143. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  61144. mesh = this._getDebugBoxMesh(scene);
  61145. impostor.getBoxSizeToRef(mesh.scaling);
  61146. }
  61147. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  61148. mesh = this._getDebugSphereMesh(scene);
  61149. var radius = impostor.getRadius();
  61150. mesh.scaling.x = radius * 2;
  61151. mesh.scaling.y = radius * 2;
  61152. mesh.scaling.z = radius * 2;
  61153. }
  61154. return mesh;
  61155. };
  61156. /** Releases all resources */
  61157. PhysicsViewer.prototype.dispose = function () {
  61158. for (var i = 0; i < this._numMeshes; i++) {
  61159. this.hideImpostor(this._impostors[i]);
  61160. }
  61161. if (this._debugBoxMesh) {
  61162. this._debugBoxMesh.dispose();
  61163. }
  61164. if (this._debugSphereMesh) {
  61165. this._debugSphereMesh.dispose();
  61166. }
  61167. if (this._debugMaterial) {
  61168. this._debugMaterial.dispose();
  61169. }
  61170. this._impostors.length = 0;
  61171. this._scene = null;
  61172. this._physicsEnginePlugin = null;
  61173. };
  61174. return PhysicsViewer;
  61175. }());
  61176. Debug.PhysicsViewer = PhysicsViewer;
  61177. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61178. })(BABYLON || (BABYLON = {}));
  61179. //# sourceMappingURL=babylon.physicsViewer.js.map
  61180. var BABYLON;
  61181. (function (BABYLON) {
  61182. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  61183. get: function () {
  61184. return this._forceShowBoundingBoxes || false;
  61185. },
  61186. set: function (value) {
  61187. this._forceShowBoundingBoxes = value;
  61188. // Lazyly creates a BB renderer if needed.
  61189. if (value) {
  61190. this.getBoundingBoxRenderer();
  61191. }
  61192. },
  61193. enumerable: true,
  61194. configurable: true
  61195. });
  61196. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  61197. if (!this._boundingBoxRenderer) {
  61198. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  61199. }
  61200. return this._boundingBoxRenderer;
  61201. };
  61202. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  61203. get: function () {
  61204. return this._showBoundingBox || false;
  61205. },
  61206. set: function (value) {
  61207. this._showBoundingBox = value;
  61208. // Lazyly creates a BB renderer if needed.
  61209. if (value) {
  61210. this.getScene().getBoundingBoxRenderer();
  61211. }
  61212. },
  61213. enumerable: true,
  61214. configurable: true
  61215. });
  61216. var BoundingBoxRenderer = /** @class */ (function () {
  61217. function BoundingBoxRenderer(scene) {
  61218. /**
  61219. * The component name helpfull to identify the component in the list of scene components.
  61220. */
  61221. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  61222. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61223. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61224. this.showBackLines = true;
  61225. this.renderList = new BABYLON.SmartArray(32);
  61226. this._vertexBuffers = {};
  61227. this.scene = scene;
  61228. scene._addComponent(this);
  61229. }
  61230. /**
  61231. * Registers the component in a given scene
  61232. */
  61233. BoundingBoxRenderer.prototype.register = function () {
  61234. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  61235. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  61236. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  61237. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  61238. };
  61239. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  61240. if (mesh.showSubMeshesBoundingBox) {
  61241. var boundingInfo = subMesh.getBoundingInfo();
  61242. if (boundingInfo !== null && boundingInfo !== undefined) {
  61243. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  61244. this.renderList.push(boundingInfo.boundingBox);
  61245. }
  61246. }
  61247. };
  61248. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  61249. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  61250. var boundingInfo = sourceMesh.getBoundingInfo();
  61251. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  61252. this.renderList.push(boundingInfo.boundingBox);
  61253. }
  61254. };
  61255. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61256. if (this._colorShader) {
  61257. return;
  61258. }
  61259. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  61260. attributes: [BABYLON.VertexBuffer.PositionKind],
  61261. uniforms: ["world", "viewProjection", "color"]
  61262. });
  61263. var engine = this.scene.getEngine();
  61264. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61265. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61266. this._createIndexBuffer();
  61267. };
  61268. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61269. var engine = this.scene.getEngine();
  61270. 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]);
  61271. };
  61272. /**
  61273. * Rebuilds the elements related to this component in case of
  61274. * context lost for instance.
  61275. */
  61276. BoundingBoxRenderer.prototype.rebuild = function () {
  61277. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61278. if (vb) {
  61279. vb._rebuild();
  61280. }
  61281. this._createIndexBuffer();
  61282. };
  61283. BoundingBoxRenderer.prototype.reset = function () {
  61284. this.renderList.reset();
  61285. };
  61286. /**
  61287. * Render the bounding boxes of a specific rendering group
  61288. * @param renderingGroupId defines the rendering group to render
  61289. */
  61290. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  61291. if (this.renderList.length === 0) {
  61292. return;
  61293. }
  61294. this._prepareRessources();
  61295. if (!this._colorShader.isReady()) {
  61296. return;
  61297. }
  61298. var engine = this.scene.getEngine();
  61299. engine.setDepthWrite(false);
  61300. this._colorShader._preBind();
  61301. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61302. var boundingBox = this.renderList.data[boundingBoxIndex];
  61303. if (boundingBox._tag !== renderingGroupId) {
  61304. continue;
  61305. }
  61306. var min = boundingBox.minimum;
  61307. var max = boundingBox.maximum;
  61308. var diff = max.subtract(min);
  61309. var median = min.add(diff.scale(0.5));
  61310. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61311. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61312. .multiply(boundingBox.getWorldMatrix());
  61313. // VBOs
  61314. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61315. if (this.showBackLines) {
  61316. // Back
  61317. engine.setDepthFunctionToGreaterOrEqual();
  61318. this.scene.resetCachedMaterial();
  61319. this._colorShader.setColor4("color", this.backColor.toColor4());
  61320. this._colorShader.bind(worldMatrix);
  61321. // Draw order
  61322. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61323. }
  61324. // Front
  61325. engine.setDepthFunctionToLess();
  61326. this.scene.resetCachedMaterial();
  61327. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61328. this._colorShader.bind(worldMatrix);
  61329. // Draw order
  61330. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61331. }
  61332. this._colorShader.unbind();
  61333. engine.setDepthFunctionToLessOrEqual();
  61334. engine.setDepthWrite(true);
  61335. };
  61336. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61337. this._prepareRessources();
  61338. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61339. return;
  61340. }
  61341. var engine = this.scene.getEngine();
  61342. engine.setDepthWrite(false);
  61343. engine.setColorWrite(false);
  61344. this._colorShader._preBind();
  61345. var boundingBox = mesh._boundingInfo.boundingBox;
  61346. var min = boundingBox.minimum;
  61347. var max = boundingBox.maximum;
  61348. var diff = max.subtract(min);
  61349. var median = min.add(diff.scale(0.5));
  61350. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61351. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61352. .multiply(boundingBox.getWorldMatrix());
  61353. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61354. engine.setDepthFunctionToLess();
  61355. this.scene.resetCachedMaterial();
  61356. this._colorShader.bind(worldMatrix);
  61357. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61358. this._colorShader.unbind();
  61359. engine.setDepthFunctionToLessOrEqual();
  61360. engine.setDepthWrite(true);
  61361. engine.setColorWrite(true);
  61362. };
  61363. BoundingBoxRenderer.prototype.dispose = function () {
  61364. if (!this._colorShader) {
  61365. return;
  61366. }
  61367. this.renderList.dispose();
  61368. this._colorShader.dispose();
  61369. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61370. if (buffer) {
  61371. buffer.dispose();
  61372. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61373. }
  61374. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61375. };
  61376. return BoundingBoxRenderer;
  61377. }());
  61378. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61379. })(BABYLON || (BABYLON = {}));
  61380. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61381. var BABYLON;
  61382. (function (BABYLON) {
  61383. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61384. return this._gl.createTransformFeedback();
  61385. };
  61386. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61387. this._gl.deleteTransformFeedback(value);
  61388. };
  61389. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61390. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61391. };
  61392. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61393. if (usePoints === void 0) { usePoints = true; }
  61394. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61395. };
  61396. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61397. this._gl.endTransformFeedback();
  61398. };
  61399. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61400. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61401. };
  61402. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61403. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61404. };
  61405. })(BABYLON || (BABYLON = {}));
  61406. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61407. var BABYLON;
  61408. (function (BABYLON) {
  61409. /**
  61410. * This represents a GPU particle system in Babylon
  61411. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61412. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61413. */
  61414. var GPUParticleSystem = /** @class */ (function (_super) {
  61415. __extends(GPUParticleSystem, _super);
  61416. /**
  61417. * Instantiates a GPU particle system.
  61418. * 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.
  61419. * @param name The name of the particle system
  61420. * @param options The options used to create the system
  61421. * @param scene The scene the particle system belongs to
  61422. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61423. */
  61424. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61425. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61426. var _this = _super.call(this, name) || this;
  61427. /**
  61428. * The layer mask we are rendering the particles through.
  61429. */
  61430. _this.layerMask = 0x0FFFFFFF;
  61431. _this._accumulatedCount = 0;
  61432. _this._targetIndex = 0;
  61433. _this._currentRenderId = -1;
  61434. _this._started = false;
  61435. _this._stopped = false;
  61436. _this._timeDelta = 0;
  61437. _this._attributesStrideSize = 21;
  61438. _this._actualFrame = 0;
  61439. _this._rawTextureWidth = 256;
  61440. /**
  61441. * An event triggered when the system is disposed.
  61442. */
  61443. _this.onDisposeObservable = new BABYLON.Observable();
  61444. /**
  61445. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61446. * to override the particles.
  61447. */
  61448. _this.forceDepthWrite = false;
  61449. _this._preWarmDone = false;
  61450. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61451. // Setup the default processing configuration to the scene.
  61452. _this._attachImageProcessingConfiguration(null);
  61453. _this._engine = _this._scene.getEngine();
  61454. if (!options.randomTextureSize) {
  61455. delete options.randomTextureSize;
  61456. }
  61457. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61458. var optionsAsNumber = options;
  61459. if (isFinite(optionsAsNumber)) {
  61460. fullOptions.capacity = optionsAsNumber;
  61461. }
  61462. _this._capacity = fullOptions.capacity;
  61463. _this._activeCount = fullOptions.capacity;
  61464. _this._currentActiveCount = 0;
  61465. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61466. _this._scene.particleSystems.push(_this);
  61467. _this._updateEffectOptions = {
  61468. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  61469. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61470. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61471. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61472. uniformBuffersNames: [],
  61473. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61474. defines: "",
  61475. fallbacks: null,
  61476. onCompiled: null,
  61477. onError: null,
  61478. indexParameters: null,
  61479. maxSimultaneousLights: 0,
  61480. transformFeedbackVaryings: []
  61481. };
  61482. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61483. // Random data
  61484. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61485. var d = [];
  61486. for (var i = 0; i < maxTextureSize; ++i) {
  61487. d.push(Math.random());
  61488. d.push(Math.random());
  61489. d.push(Math.random());
  61490. d.push(Math.random());
  61491. }
  61492. _this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  61493. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61494. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61495. d = [];
  61496. for (var i = 0; i < maxTextureSize; ++i) {
  61497. d.push(Math.random());
  61498. d.push(Math.random());
  61499. d.push(Math.random());
  61500. d.push(Math.random());
  61501. }
  61502. _this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  61503. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61504. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61505. _this._randomTextureSize = maxTextureSize;
  61506. return _this;
  61507. }
  61508. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61509. /**
  61510. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61511. */
  61512. get: function () {
  61513. if (!BABYLON.Engine.LastCreatedEngine) {
  61514. return false;
  61515. }
  61516. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61517. },
  61518. enumerable: true,
  61519. configurable: true
  61520. });
  61521. /**
  61522. * Gets the maximum number of particles active at the same time.
  61523. * @returns The max number of active particles.
  61524. */
  61525. GPUParticleSystem.prototype.getCapacity = function () {
  61526. return this._capacity;
  61527. };
  61528. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61529. /**
  61530. * Gets or set the number of active particles
  61531. */
  61532. get: function () {
  61533. return this._activeCount;
  61534. },
  61535. set: function (value) {
  61536. this._activeCount = Math.min(value, this._capacity);
  61537. },
  61538. enumerable: true,
  61539. configurable: true
  61540. });
  61541. /**
  61542. * Is this system ready to be used/rendered
  61543. * @return true if the system is ready
  61544. */
  61545. GPUParticleSystem.prototype.isReady = function () {
  61546. if (!this._updateEffect) {
  61547. this._recreateUpdateEffect();
  61548. this._recreateRenderEffect();
  61549. return false;
  61550. }
  61551. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61552. return false;
  61553. }
  61554. return true;
  61555. };
  61556. /**
  61557. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61558. * @returns True if it has been started, otherwise false.
  61559. */
  61560. GPUParticleSystem.prototype.isStarted = function () {
  61561. return this._started;
  61562. };
  61563. /**
  61564. * Starts the particle system and begins to emit
  61565. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61566. */
  61567. GPUParticleSystem.prototype.start = function (delay) {
  61568. var _this = this;
  61569. if (delay === void 0) { delay = this.startDelay; }
  61570. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61571. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61572. }
  61573. if (delay) {
  61574. setTimeout(function () {
  61575. _this.start(0);
  61576. }, delay);
  61577. return;
  61578. }
  61579. this._started = true;
  61580. this._stopped = false;
  61581. this._preWarmDone = false;
  61582. };
  61583. /**
  61584. * Stops the particle system.
  61585. */
  61586. GPUParticleSystem.prototype.stop = function () {
  61587. this._stopped = true;
  61588. };
  61589. /**
  61590. * Remove all active particles
  61591. */
  61592. GPUParticleSystem.prototype.reset = function () {
  61593. this._releaseBuffers();
  61594. this._releaseVAOs();
  61595. this._currentActiveCount = 0;
  61596. this._targetIndex = 0;
  61597. };
  61598. /**
  61599. * Returns the string "GPUParticleSystem"
  61600. * @returns a string containing the class name
  61601. */
  61602. GPUParticleSystem.prototype.getClassName = function () {
  61603. return "GPUParticleSystem";
  61604. };
  61605. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  61606. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  61607. this._releaseBuffers();
  61608. return this;
  61609. };
  61610. /**
  61611. * Adds a new color gradient
  61612. * @param gradient defines the gradient to use (between 0 and 1)
  61613. * @param color defines the color to affect to the specified gradient
  61614. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61615. * @returns the current particle system
  61616. */
  61617. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61618. if (!this._colorGradients) {
  61619. this._colorGradients = [];
  61620. }
  61621. var colorGradient = new BABYLON.ColorGradient();
  61622. colorGradient.gradient = gradient;
  61623. colorGradient.color1 = color1;
  61624. this._colorGradients.push(colorGradient);
  61625. this._colorGradients.sort(function (a, b) {
  61626. if (a.gradient < b.gradient) {
  61627. return -1;
  61628. }
  61629. else if (a.gradient > b.gradient) {
  61630. return 1;
  61631. }
  61632. return 0;
  61633. });
  61634. if (this._colorGradientsTexture) {
  61635. this._colorGradientsTexture.dispose();
  61636. this._colorGradientsTexture = null;
  61637. }
  61638. this._releaseBuffers();
  61639. return this;
  61640. };
  61641. /**
  61642. * Remove a specific color gradient
  61643. * @param gradient defines the gradient to remove
  61644. * @returns the current particle system
  61645. */
  61646. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61647. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  61648. this._colorGradientsTexture = null;
  61649. return this;
  61650. };
  61651. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61652. var valueGradient = new BABYLON.FactorGradient();
  61653. valueGradient.gradient = gradient;
  61654. valueGradient.factor1 = factor;
  61655. factorGradients.push(valueGradient);
  61656. factorGradients.sort(function (a, b) {
  61657. if (a.gradient < b.gradient) {
  61658. return -1;
  61659. }
  61660. else if (a.gradient > b.gradient) {
  61661. return 1;
  61662. }
  61663. return 0;
  61664. });
  61665. this._releaseBuffers();
  61666. };
  61667. /**
  61668. * Adds a new size gradient
  61669. * @param gradient defines the gradient to use (between 0 and 1)
  61670. * @param factor defines the size factor to affect to the specified gradient
  61671. * @returns the current particle system
  61672. */
  61673. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61674. if (!this._sizeGradients) {
  61675. this._sizeGradients = [];
  61676. }
  61677. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61678. if (this._sizeGradientsTexture) {
  61679. this._sizeGradientsTexture.dispose();
  61680. this._sizeGradientsTexture = null;
  61681. }
  61682. this._releaseBuffers();
  61683. return this;
  61684. };
  61685. /**
  61686. * Remove a specific size gradient
  61687. * @param gradient defines the gradient to remove
  61688. * @returns the current particle system
  61689. */
  61690. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61691. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61692. this._sizeGradientsTexture = null;
  61693. return this;
  61694. };
  61695. /**
  61696. * Adds a new angular speed gradient
  61697. * @param gradient defines the gradient to use (between 0 and 1)
  61698. * @param factor defines the angular speed to affect to the specified gradient
  61699. * @returns the current particle system
  61700. */
  61701. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61702. if (!this._angularSpeedGradients) {
  61703. this._angularSpeedGradients = [];
  61704. }
  61705. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61706. if (this._angularSpeedGradientsTexture) {
  61707. this._angularSpeedGradientsTexture.dispose();
  61708. this._angularSpeedGradientsTexture = null;
  61709. }
  61710. this._releaseBuffers();
  61711. return this;
  61712. };
  61713. /**
  61714. * Remove a specific angular speed gradient
  61715. * @param gradient defines the gradient to remove
  61716. * @returns the current particle system
  61717. */
  61718. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61719. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61720. this._angularSpeedGradientsTexture = null;
  61721. return this;
  61722. };
  61723. /**
  61724. * Adds a new velocity gradient
  61725. * @param gradient defines the gradient to use (between 0 and 1)
  61726. * @param factor defines the velocity to affect to the specified gradient
  61727. * @returns the current particle system
  61728. */
  61729. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61730. if (!this._velocityGradients) {
  61731. this._velocityGradients = [];
  61732. }
  61733. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61734. if (this._velocityGradientsTexture) {
  61735. this._velocityGradientsTexture.dispose();
  61736. this._velocityGradientsTexture = null;
  61737. }
  61738. this._releaseBuffers();
  61739. return this;
  61740. };
  61741. /**
  61742. * Remove a specific velocity gradient
  61743. * @param gradient defines the gradient to remove
  61744. * @returns the current particle system
  61745. */
  61746. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61747. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61748. this._velocityGradientsTexture = null;
  61749. return this;
  61750. };
  61751. /**
  61752. * Adds a new limit velocity gradient
  61753. * @param gradient defines the gradient to use (between 0 and 1)
  61754. * @param factor defines the limit velocity value to affect to the specified gradient
  61755. * @returns the current particle system
  61756. */
  61757. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61758. if (!this._limitVelocityGradients) {
  61759. this._limitVelocityGradients = [];
  61760. }
  61761. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61762. if (this._limitVelocityGradientsTexture) {
  61763. this._limitVelocityGradientsTexture.dispose();
  61764. this._limitVelocityGradientsTexture = null;
  61765. }
  61766. this._releaseBuffers();
  61767. return this;
  61768. };
  61769. /**
  61770. * Remove a specific limit velocity gradient
  61771. * @param gradient defines the gradient to remove
  61772. * @returns the current particle system
  61773. */
  61774. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61775. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61776. this._limitVelocityGradientsTexture = null;
  61777. return this;
  61778. };
  61779. /**
  61780. * Adds a new drag gradient
  61781. * @param gradient defines the gradient to use (between 0 and 1)
  61782. * @param factor defines the drag value to affect to the specified gradient
  61783. * @returns the current particle system
  61784. */
  61785. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61786. if (!this._dragGradients) {
  61787. this._dragGradients = [];
  61788. }
  61789. this._addFactorGradient(this._dragGradients, gradient, factor);
  61790. if (this._dragGradientsTexture) {
  61791. this._dragGradientsTexture.dispose();
  61792. this._dragGradientsTexture = null;
  61793. }
  61794. this._releaseBuffers();
  61795. return this;
  61796. };
  61797. /**
  61798. * Remove a specific drag gradient
  61799. * @param gradient defines the gradient to remove
  61800. * @returns the current particle system
  61801. */
  61802. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61803. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  61804. this._dragGradientsTexture = null;
  61805. return this;
  61806. };
  61807. /**
  61808. * Not supported by GPUParticleSystem
  61809. * @param gradient defines the gradient to use (between 0 and 1)
  61810. * @param factor defines the emit rate value to affect to the specified gradient
  61811. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61812. * @returns the current particle system
  61813. */
  61814. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61815. // Do nothing as emit rate is not supported by GPUParticleSystem
  61816. return this;
  61817. };
  61818. /**
  61819. * Not supported by GPUParticleSystem
  61820. * @param gradient defines the gradient to remove
  61821. * @returns the current particle system
  61822. */
  61823. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61824. // Do nothing as emit rate is not supported by GPUParticleSystem
  61825. return this;
  61826. };
  61827. /**
  61828. * Not supported by GPUParticleSystem
  61829. * @param gradient defines the gradient to use (between 0 and 1)
  61830. * @param factor defines the start size value to affect to the specified gradient
  61831. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61832. * @returns the current particle system
  61833. */
  61834. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61835. // Do nothing as start size is not supported by GPUParticleSystem
  61836. return this;
  61837. };
  61838. /**
  61839. * Not supported by GPUParticleSystem
  61840. * @param gradient defines the gradient to remove
  61841. * @returns the current particle system
  61842. */
  61843. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61844. // Do nothing as start size is not supported by GPUParticleSystem
  61845. return this;
  61846. };
  61847. /**
  61848. * Not supported by GPUParticleSystem
  61849. * @param gradient defines the gradient to use (between 0 and 1)
  61850. * @param min defines the color remap minimal range
  61851. * @param max defines the color remap maximal range
  61852. * @returns the current particle system
  61853. */
  61854. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  61855. // Do nothing as start size is not supported by GPUParticleSystem
  61856. return this;
  61857. };
  61858. /**
  61859. * Not supported by GPUParticleSystem
  61860. * @param gradient defines the gradient to remove
  61861. * @returns the current particle system
  61862. */
  61863. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  61864. // Do nothing as start size is not supported by GPUParticleSystem
  61865. return this;
  61866. };
  61867. /**
  61868. * Not supported by GPUParticleSystem
  61869. * @param gradient defines the gradient to use (between 0 and 1)
  61870. * @param min defines the alpha remap minimal range
  61871. * @param max defines the alpha remap maximal range
  61872. * @returns the current particle system
  61873. */
  61874. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  61875. // Do nothing as start size is not supported by GPUParticleSystem
  61876. return this;
  61877. };
  61878. /**
  61879. * Not supported by GPUParticleSystem
  61880. * @param gradient defines the gradient to remove
  61881. * @returns the current particle system
  61882. */
  61883. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  61884. // Do nothing as start size is not supported by GPUParticleSystem
  61885. return this;
  61886. };
  61887. /**
  61888. * Not supported by GPUParticleSystem
  61889. * @param gradient defines the gradient to use (between 0 and 1)
  61890. * @param color defines the color to affect to the specified gradient
  61891. * @returns the current particle system
  61892. */
  61893. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  61894. //Not supported by GPUParticleSystem
  61895. return this;
  61896. };
  61897. /**
  61898. * Not supported by GPUParticleSystem
  61899. * @param gradient defines the gradient to remove
  61900. * @returns the current particle system
  61901. */
  61902. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  61903. //Not supported by GPUParticleSystem
  61904. return this;
  61905. };
  61906. /**
  61907. * Not supported by GPUParticleSystem
  61908. * @returns the list of ramp gradients
  61909. */
  61910. GPUParticleSystem.prototype.getRampGradients = function () {
  61911. return null;
  61912. };
  61913. GPUParticleSystem.prototype._reset = function () {
  61914. this._releaseBuffers();
  61915. };
  61916. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  61917. var updateVertexBuffers = {};
  61918. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  61919. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  61920. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  61921. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  61922. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  61923. var offset = 12;
  61924. if (!this._colorGradientsTexture) {
  61925. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  61926. offset += 4;
  61927. }
  61928. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  61929. offset += 3;
  61930. if (!this._isBillboardBased) {
  61931. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  61932. offset += 3;
  61933. }
  61934. if (this._angularSpeedGradientsTexture) {
  61935. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  61936. offset += 1;
  61937. }
  61938. else {
  61939. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  61940. offset += 2;
  61941. }
  61942. if (this._isAnimationSheetEnabled) {
  61943. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  61944. offset += 1;
  61945. if (this.spriteRandomStartCell) {
  61946. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  61947. offset += 1;
  61948. }
  61949. }
  61950. if (this.noiseTexture) {
  61951. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  61952. offset += 3;
  61953. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  61954. offset += 3;
  61955. }
  61956. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  61957. this._engine.bindArrayBuffer(null);
  61958. return vao;
  61959. };
  61960. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  61961. var renderVertexBuffers = {};
  61962. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61963. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61964. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61965. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61966. var offset = 12;
  61967. if (!this._colorGradientsTexture) {
  61968. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61969. offset += 4;
  61970. }
  61971. offset += 3; // Direction
  61972. if (!this._isBillboardBased) {
  61973. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61974. offset += 3;
  61975. }
  61976. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61977. if (this._angularSpeedGradientsTexture) {
  61978. offset++;
  61979. }
  61980. else {
  61981. offset += 2;
  61982. }
  61983. if (this._isAnimationSheetEnabled) {
  61984. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61985. offset += 1;
  61986. if (this.spriteRandomStartCell) {
  61987. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  61988. offset += 1;
  61989. }
  61990. }
  61991. if (this.noiseTexture) {
  61992. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  61993. offset += 3;
  61994. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  61995. offset += 3;
  61996. }
  61997. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61998. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61999. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  62000. this._engine.bindArrayBuffer(null);
  62001. return vao;
  62002. };
  62003. GPUParticleSystem.prototype._initialize = function (force) {
  62004. if (force === void 0) { force = false; }
  62005. if (this._buffer0 && !force) {
  62006. return;
  62007. }
  62008. var engine = this._scene.getEngine();
  62009. var data = new Array();
  62010. if (!this.isBillboardBased) {
  62011. this._attributesStrideSize += 3;
  62012. }
  62013. if (this._colorGradientsTexture) {
  62014. this._attributesStrideSize -= 4;
  62015. }
  62016. if (this._angularSpeedGradientsTexture) {
  62017. this._attributesStrideSize -= 1;
  62018. }
  62019. if (this._isAnimationSheetEnabled) {
  62020. this._attributesStrideSize += 1;
  62021. if (this.spriteRandomStartCell) {
  62022. this._attributesStrideSize += 1;
  62023. }
  62024. }
  62025. if (this.noiseTexture) {
  62026. this._attributesStrideSize += 6;
  62027. }
  62028. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  62029. // position
  62030. data.push(0.0);
  62031. data.push(0.0);
  62032. data.push(0.0);
  62033. // Age and life
  62034. data.push(0.0); // create the particle as a dead one to create a new one at start
  62035. data.push(0.0);
  62036. // Seed
  62037. data.push(Math.random());
  62038. data.push(Math.random());
  62039. data.push(Math.random());
  62040. data.push(Math.random());
  62041. // Size
  62042. data.push(0.0);
  62043. data.push(0.0);
  62044. data.push(0.0);
  62045. if (!this._colorGradientsTexture) {
  62046. // color
  62047. data.push(0.0);
  62048. data.push(0.0);
  62049. data.push(0.0);
  62050. data.push(0.0);
  62051. }
  62052. // direction
  62053. data.push(0.0);
  62054. data.push(0.0);
  62055. data.push(0.0);
  62056. if (!this.isBillboardBased) {
  62057. // initialDirection
  62058. data.push(0.0);
  62059. data.push(0.0);
  62060. data.push(0.0);
  62061. }
  62062. // angle
  62063. data.push(0.0);
  62064. if (!this._angularSpeedGradientsTexture) {
  62065. data.push(0.0);
  62066. }
  62067. if (this._isAnimationSheetEnabled) {
  62068. data.push(0.0);
  62069. if (this.spriteRandomStartCell) {
  62070. data.push(0.0);
  62071. }
  62072. }
  62073. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  62074. data.push(Math.random());
  62075. data.push(Math.random());
  62076. data.push(Math.random());
  62077. data.push(Math.random());
  62078. data.push(Math.random());
  62079. data.push(Math.random());
  62080. }
  62081. }
  62082. // Sprite data
  62083. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  62084. -0.5, 0.5, 0, 1,
  62085. -0.5, -0.5, 0, 0,
  62086. 0.5, -0.5, 1, 0]);
  62087. // Buffers
  62088. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62089. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62090. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  62091. // Update VAO
  62092. this._updateVAO = [];
  62093. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  62094. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  62095. // Render VAO
  62096. this._renderVAO = [];
  62097. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  62098. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  62099. // Links
  62100. this._sourceBuffer = this._buffer0;
  62101. this._targetBuffer = this._buffer1;
  62102. };
  62103. /** @hidden */
  62104. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  62105. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  62106. if (this._isBillboardBased) {
  62107. defines += "\n#define BILLBOARD";
  62108. }
  62109. if (this._colorGradientsTexture) {
  62110. defines += "\n#define COLORGRADIENTS";
  62111. }
  62112. if (this._sizeGradientsTexture) {
  62113. defines += "\n#define SIZEGRADIENTS";
  62114. }
  62115. if (this._angularSpeedGradientsTexture) {
  62116. defines += "\n#define ANGULARSPEEDGRADIENTS";
  62117. }
  62118. if (this._velocityGradientsTexture) {
  62119. defines += "\n#define VELOCITYGRADIENTS";
  62120. }
  62121. if (this._limitVelocityGradientsTexture) {
  62122. defines += "\n#define LIMITVELOCITYGRADIENTS";
  62123. }
  62124. if (this._dragGradientsTexture) {
  62125. defines += "\n#define DRAGGRADIENTS";
  62126. }
  62127. if (this.isAnimationSheetEnabled) {
  62128. defines += "\n#define ANIMATESHEET";
  62129. if (this.spriteRandomStartCell) {
  62130. defines += "\n#define ANIMATESHEETRANDOMSTART";
  62131. }
  62132. }
  62133. if (this.noiseTexture) {
  62134. defines += "\n#define NOISE";
  62135. }
  62136. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  62137. return;
  62138. }
  62139. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  62140. if (!this._colorGradientsTexture) {
  62141. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  62142. }
  62143. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  62144. if (!this._isBillboardBased) {
  62145. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  62146. }
  62147. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  62148. if (this.isAnimationSheetEnabled) {
  62149. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  62150. if (this.spriteRandomStartCell) {
  62151. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  62152. }
  62153. }
  62154. if (this.noiseTexture) {
  62155. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  62156. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  62157. }
  62158. this._updateEffectOptions.defines = defines;
  62159. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  62160. };
  62161. /** @hidden */
  62162. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  62163. var defines = "";
  62164. if (this._scene.clipPlane) {
  62165. defines = "\n#define CLIPPLANE";
  62166. }
  62167. if (this._scene.clipPlane2) {
  62168. defines = "\n#define CLIPPLANE2";
  62169. }
  62170. if (this._scene.clipPlane3) {
  62171. defines = "\n#define CLIPPLANE3";
  62172. }
  62173. if (this._scene.clipPlane4) {
  62174. defines = "\n#define CLIPPLANE4";
  62175. }
  62176. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  62177. defines = "\n#define BLENDMULTIPLYMODE";
  62178. }
  62179. if (this._isBillboardBased) {
  62180. defines += "\n#define BILLBOARD";
  62181. switch (this.billboardMode) {
  62182. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  62183. defines += "\n#define BILLBOARDY";
  62184. break;
  62185. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  62186. default:
  62187. break;
  62188. }
  62189. }
  62190. if (this._colorGradientsTexture) {
  62191. defines += "\n#define COLORGRADIENTS";
  62192. }
  62193. if (this.isAnimationSheetEnabled) {
  62194. defines += "\n#define ANIMATESHEET";
  62195. }
  62196. if (this._imageProcessingConfiguration) {
  62197. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62198. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  62199. }
  62200. if (this._renderEffect && this._renderEffect.defines === defines) {
  62201. return;
  62202. }
  62203. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  62204. var samplers = ["textureSampler", "colorGradientSampler"];
  62205. if (BABYLON.ImageProcessingConfiguration) {
  62206. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  62207. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62208. }
  62209. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  62210. };
  62211. /**
  62212. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62213. * @param preWarm defines if we are in the pre-warmimg phase
  62214. */
  62215. GPUParticleSystem.prototype.animate = function (preWarm) {
  62216. if (preWarm === void 0) { preWarm = false; }
  62217. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62218. this._actualFrame += this._timeDelta;
  62219. if (!this._stopped) {
  62220. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62221. this.stop();
  62222. }
  62223. }
  62224. };
  62225. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  62226. var texture = this[textureName];
  62227. if (!factorGradients || !factorGradients.length || texture) {
  62228. return;
  62229. }
  62230. var data = new Float32Array(this._rawTextureWidth);
  62231. for (var x = 0; x < this._rawTextureWidth; x++) {
  62232. var ratio = x / this._rawTextureWidth;
  62233. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  62234. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  62235. });
  62236. }
  62237. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62238. };
  62239. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  62240. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  62241. };
  62242. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  62243. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  62244. };
  62245. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  62246. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  62247. };
  62248. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  62249. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  62250. };
  62251. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  62252. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  62253. };
  62254. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  62255. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  62256. return;
  62257. }
  62258. var data = new Uint8Array(this._rawTextureWidth * 4);
  62259. var tmpColor = BABYLON.Tmp.Color4[0];
  62260. for (var x = 0; x < this._rawTextureWidth; x++) {
  62261. var ratio = x / this._rawTextureWidth;
  62262. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  62263. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  62264. data[x * 4] = tmpColor.r * 255;
  62265. data[x * 4 + 1] = tmpColor.g * 255;
  62266. data[x * 4 + 2] = tmpColor.b * 255;
  62267. data[x * 4 + 3] = tmpColor.a * 255;
  62268. });
  62269. }
  62270. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62271. };
  62272. /**
  62273. * Renders the particle system in its current state
  62274. * @param preWarm defines if the system should only update the particles but not render them
  62275. * @returns the current number of particles
  62276. */
  62277. GPUParticleSystem.prototype.render = function (preWarm) {
  62278. if (preWarm === void 0) { preWarm = false; }
  62279. if (!this._started) {
  62280. return 0;
  62281. }
  62282. this._createColorGradientTexture();
  62283. this._createSizeGradientTexture();
  62284. this._createAngularSpeedGradientTexture();
  62285. this._createVelocityGradientTexture();
  62286. this._createLimitVelocityGradientTexture();
  62287. this._createDragGradientTexture();
  62288. this._recreateUpdateEffect();
  62289. this._recreateRenderEffect();
  62290. if (!this.isReady()) {
  62291. return 0;
  62292. }
  62293. if (!preWarm) {
  62294. if (!this._preWarmDone && this.preWarmCycles) {
  62295. for (var index = 0; index < this.preWarmCycles; index++) {
  62296. this.animate(true);
  62297. this.render(true);
  62298. }
  62299. this._preWarmDone = true;
  62300. }
  62301. if (this._currentRenderId === this._scene.getRenderId()) {
  62302. return 0;
  62303. }
  62304. this._currentRenderId = this._scene.getRenderId();
  62305. }
  62306. // Get everything ready to render
  62307. this._initialize();
  62308. this._accumulatedCount += this.emitRate * this._timeDelta;
  62309. if (this._accumulatedCount > 1) {
  62310. var intPart = this._accumulatedCount | 0;
  62311. this._accumulatedCount -= intPart;
  62312. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  62313. }
  62314. if (!this._currentActiveCount) {
  62315. return 0;
  62316. }
  62317. // Enable update effect
  62318. this._engine.enableEffect(this._updateEffect);
  62319. this._engine.setState(false);
  62320. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  62321. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  62322. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  62323. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  62324. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  62325. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  62326. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  62327. if (!this._colorGradientsTexture) {
  62328. this._updateEffect.setDirectColor4("color1", this.color1);
  62329. this._updateEffect.setDirectColor4("color2", this.color2);
  62330. }
  62331. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  62332. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  62333. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  62334. this._updateEffect.setVector3("gravity", this.gravity);
  62335. if (this._sizeGradientsTexture) {
  62336. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  62337. }
  62338. if (this._angularSpeedGradientsTexture) {
  62339. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  62340. }
  62341. if (this._velocityGradientsTexture) {
  62342. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  62343. }
  62344. if (this._limitVelocityGradientsTexture) {
  62345. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  62346. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  62347. }
  62348. if (this._dragGradientsTexture) {
  62349. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  62350. }
  62351. if (this.particleEmitterType) {
  62352. this.particleEmitterType.applyToShader(this._updateEffect);
  62353. }
  62354. if (this._isAnimationSheetEnabled) {
  62355. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62356. }
  62357. if (this.noiseTexture) {
  62358. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62359. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62360. }
  62361. var emitterWM;
  62362. if (this.emitter.position) {
  62363. var emitterMesh = this.emitter;
  62364. emitterWM = emitterMesh.getWorldMatrix();
  62365. }
  62366. else {
  62367. var emitterPosition = this.emitter;
  62368. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62369. }
  62370. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62371. // Bind source VAO
  62372. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62373. // Update
  62374. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62375. this._engine.setRasterizerState(false);
  62376. this._engine.beginTransformFeedback(true);
  62377. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62378. this._engine.endTransformFeedback();
  62379. this._engine.setRasterizerState(true);
  62380. this._engine.bindTransformFeedbackBuffer(null);
  62381. if (!preWarm) {
  62382. // Enable render effect
  62383. this._engine.enableEffect(this._renderEffect);
  62384. var viewMatrix = this._scene.getViewMatrix();
  62385. this._renderEffect.setMatrix("view", viewMatrix);
  62386. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62387. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62388. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62389. if (this._colorGradientsTexture) {
  62390. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62391. }
  62392. else {
  62393. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62394. }
  62395. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62396. var baseSize = this.particleTexture.getBaseSize();
  62397. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62398. }
  62399. if (this._isBillboardBased) {
  62400. var camera = this._scene.activeCamera;
  62401. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62402. }
  62403. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62404. var invView = viewMatrix.clone();
  62405. invView.invert();
  62406. this._renderEffect.setMatrix("invView", invView);
  62407. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62408. }
  62409. // image processing
  62410. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62411. this._imageProcessingConfiguration.bind(this._renderEffect);
  62412. }
  62413. // Draw order
  62414. switch (this.blendMode) {
  62415. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62416. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62417. break;
  62418. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62419. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62420. break;
  62421. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62422. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62423. break;
  62424. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62425. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62426. break;
  62427. }
  62428. if (this.forceDepthWrite) {
  62429. this._engine.setDepthWrite(true);
  62430. }
  62431. // Bind source VAO
  62432. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62433. // Render
  62434. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62435. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62436. }
  62437. // Switch VAOs
  62438. this._targetIndex++;
  62439. if (this._targetIndex === 2) {
  62440. this._targetIndex = 0;
  62441. }
  62442. // Switch buffers
  62443. var tmpBuffer = this._sourceBuffer;
  62444. this._sourceBuffer = this._targetBuffer;
  62445. this._targetBuffer = tmpBuffer;
  62446. return this._currentActiveCount;
  62447. };
  62448. /**
  62449. * Rebuilds the particle system
  62450. */
  62451. GPUParticleSystem.prototype.rebuild = function () {
  62452. this._initialize(true);
  62453. };
  62454. GPUParticleSystem.prototype._releaseBuffers = function () {
  62455. if (this._buffer0) {
  62456. this._buffer0.dispose();
  62457. this._buffer0 = null;
  62458. }
  62459. if (this._buffer1) {
  62460. this._buffer1.dispose();
  62461. this._buffer1 = null;
  62462. }
  62463. if (this._spriteBuffer) {
  62464. this._spriteBuffer.dispose();
  62465. this._spriteBuffer = null;
  62466. }
  62467. };
  62468. GPUParticleSystem.prototype._releaseVAOs = function () {
  62469. if (!this._updateVAO) {
  62470. return;
  62471. }
  62472. for (var index = 0; index < this._updateVAO.length; index++) {
  62473. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62474. }
  62475. this._updateVAO = [];
  62476. for (var index = 0; index < this._renderVAO.length; index++) {
  62477. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62478. }
  62479. this._renderVAO = [];
  62480. };
  62481. /**
  62482. * Disposes the particle system and free the associated resources
  62483. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62484. */
  62485. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62486. if (disposeTexture === void 0) { disposeTexture = true; }
  62487. var index = this._scene.particleSystems.indexOf(this);
  62488. if (index > -1) {
  62489. this._scene.particleSystems.splice(index, 1);
  62490. }
  62491. this._releaseBuffers();
  62492. this._releaseVAOs();
  62493. if (this._colorGradientsTexture) {
  62494. this._colorGradientsTexture.dispose();
  62495. this._colorGradientsTexture = null;
  62496. }
  62497. if (this._sizeGradientsTexture) {
  62498. this._sizeGradientsTexture.dispose();
  62499. this._sizeGradientsTexture = null;
  62500. }
  62501. if (this._angularSpeedGradientsTexture) {
  62502. this._angularSpeedGradientsTexture.dispose();
  62503. this._angularSpeedGradientsTexture = null;
  62504. }
  62505. if (this._velocityGradientsTexture) {
  62506. this._velocityGradientsTexture.dispose();
  62507. this._velocityGradientsTexture = null;
  62508. }
  62509. if (this._limitVelocityGradientsTexture) {
  62510. this._limitVelocityGradientsTexture.dispose();
  62511. this._limitVelocityGradientsTexture = null;
  62512. }
  62513. if (this._dragGradientsTexture) {
  62514. this._dragGradientsTexture.dispose();
  62515. this._dragGradientsTexture = null;
  62516. }
  62517. if (this._randomTexture) {
  62518. this._randomTexture.dispose();
  62519. this._randomTexture = null;
  62520. }
  62521. if (this._randomTexture2) {
  62522. this._randomTexture2.dispose();
  62523. this._randomTexture2 = null;
  62524. }
  62525. if (disposeTexture && this.particleTexture) {
  62526. this.particleTexture.dispose();
  62527. this.particleTexture = null;
  62528. }
  62529. if (disposeTexture && this.noiseTexture) {
  62530. this.noiseTexture.dispose();
  62531. this.noiseTexture = null;
  62532. }
  62533. // Callback
  62534. this.onDisposeObservable.notifyObservers(this);
  62535. this.onDisposeObservable.clear();
  62536. };
  62537. /**
  62538. * Clones the particle system.
  62539. * @param name The name of the cloned object
  62540. * @param newEmitter The new emitter to use
  62541. * @returns the cloned particle system
  62542. */
  62543. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62544. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62545. BABYLON.Tools.DeepCopy(this, result);
  62546. if (newEmitter === undefined) {
  62547. newEmitter = this.emitter;
  62548. }
  62549. result.emitter = newEmitter;
  62550. if (this.particleTexture) {
  62551. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62552. }
  62553. return result;
  62554. };
  62555. /**
  62556. * Serializes the particle system to a JSON object.
  62557. * @returns the JSON object
  62558. */
  62559. GPUParticleSystem.prototype.serialize = function () {
  62560. var serializationObject = {};
  62561. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62562. serializationObject.activeParticleCount = this.activeParticleCount;
  62563. return serializationObject;
  62564. };
  62565. /**
  62566. * Parses a JSON object to create a GPU particle system.
  62567. * @param parsedParticleSystem The JSON object to parse
  62568. * @param scene The scene to create the particle system in
  62569. * @param rootUrl The root url to use to load external dependencies like texture
  62570. * @returns the parsed GPU particle system
  62571. */
  62572. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62573. var name = parsedParticleSystem.name;
  62574. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62575. if (parsedParticleSystem.activeParticleCount) {
  62576. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62577. }
  62578. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62579. return particleSystem;
  62580. };
  62581. return GPUParticleSystem;
  62582. }(BABYLON.BaseParticleSystem));
  62583. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62584. })(BABYLON || (BABYLON = {}));
  62585. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62586. var BABYLON;
  62587. (function (BABYLON) {
  62588. /**
  62589. * Represents one particle of a solid particle system.
  62590. */
  62591. var SolidParticle = /** @class */ (function () {
  62592. /**
  62593. * Creates a Solid Particle object.
  62594. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62595. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62596. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62597. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62598. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62599. * @param shapeId (integer) is the model shape identifier in the SPS.
  62600. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62601. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62602. */
  62603. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62604. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62605. /**
  62606. * particle global index
  62607. */
  62608. this.idx = 0;
  62609. /**
  62610. * The color of the particle
  62611. */
  62612. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62613. /**
  62614. * The world space position of the particle.
  62615. */
  62616. this.position = BABYLON.Vector3.Zero();
  62617. /**
  62618. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62619. */
  62620. this.rotation = BABYLON.Vector3.Zero();
  62621. /**
  62622. * The scaling of the particle.
  62623. */
  62624. this.scaling = BABYLON.Vector3.One();
  62625. /**
  62626. * The uvs of the particle.
  62627. */
  62628. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62629. /**
  62630. * The current speed of the particle.
  62631. */
  62632. this.velocity = BABYLON.Vector3.Zero();
  62633. /**
  62634. * The pivot point in the particle local space.
  62635. */
  62636. this.pivot = BABYLON.Vector3.Zero();
  62637. /**
  62638. * Must the particle be translated from its pivot point in its local space ?
  62639. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62640. * Default : false
  62641. */
  62642. this.translateFromPivot = false;
  62643. /**
  62644. * Is the particle active or not ?
  62645. */
  62646. this.alive = true;
  62647. /**
  62648. * Is the particle visible or not ?
  62649. */
  62650. this.isVisible = true;
  62651. /**
  62652. * Index of this particle in the global "positions" array (Internal use)
  62653. * @hidden
  62654. */
  62655. this._pos = 0;
  62656. /**
  62657. * @hidden Index of this particle in the global "indices" array (Internal use)
  62658. */
  62659. this._ind = 0;
  62660. /**
  62661. * ModelShape id of this particle
  62662. */
  62663. this.shapeId = 0;
  62664. /**
  62665. * Index of the particle in its shape id (Internal use)
  62666. */
  62667. this.idxInShape = 0;
  62668. /**
  62669. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62670. */
  62671. this._stillInvisible = false;
  62672. /**
  62673. * @hidden Last computed particle rotation matrix
  62674. */
  62675. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62676. /**
  62677. * Parent particle Id, if any.
  62678. * Default null.
  62679. */
  62680. this.parentId = null;
  62681. /**
  62682. * @hidden Internal global position in the SPS.
  62683. */
  62684. this._globalPosition = BABYLON.Vector3.Zero();
  62685. this.idx = particleIndex;
  62686. this._pos = positionIndex;
  62687. this._ind = indiceIndex;
  62688. this._model = model;
  62689. this.shapeId = shapeId;
  62690. this.idxInShape = idxInShape;
  62691. this._sps = sps;
  62692. if (modelBoundingInfo) {
  62693. this._modelBoundingInfo = modelBoundingInfo;
  62694. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62695. }
  62696. }
  62697. Object.defineProperty(SolidParticle.prototype, "scale", {
  62698. /**
  62699. * Legacy support, changed scale to scaling
  62700. */
  62701. get: function () {
  62702. return this.scaling;
  62703. },
  62704. /**
  62705. * Legacy support, changed scale to scaling
  62706. */
  62707. set: function (scale) {
  62708. this.scaling = scale;
  62709. },
  62710. enumerable: true,
  62711. configurable: true
  62712. });
  62713. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62714. /**
  62715. * Legacy support, changed quaternion to rotationQuaternion
  62716. */
  62717. get: function () {
  62718. return this.rotationQuaternion;
  62719. },
  62720. /**
  62721. * Legacy support, changed quaternion to rotationQuaternion
  62722. */
  62723. set: function (q) {
  62724. this.rotationQuaternion = q;
  62725. },
  62726. enumerable: true,
  62727. configurable: true
  62728. });
  62729. /**
  62730. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62731. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62732. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62733. * @returns true if it intersects
  62734. */
  62735. SolidParticle.prototype.intersectsMesh = function (target) {
  62736. if (!this._boundingInfo || !target._boundingInfo) {
  62737. return false;
  62738. }
  62739. if (this._sps._bSphereOnly) {
  62740. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62741. }
  62742. return this._boundingInfo.intersects(target._boundingInfo, false);
  62743. };
  62744. return SolidParticle;
  62745. }());
  62746. BABYLON.SolidParticle = SolidParticle;
  62747. /**
  62748. * Represents the shape of the model used by one particle of a solid particle system.
  62749. * SPS internal tool, don't use it manually.
  62750. */
  62751. var ModelShape = /** @class */ (function () {
  62752. /**
  62753. * 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.
  62754. * SPS internal tool, don't use it manually.
  62755. * @hidden
  62756. */
  62757. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62758. /**
  62759. * length of the shape in the model indices array (internal use)
  62760. * @hidden
  62761. */
  62762. this._indicesLength = 0;
  62763. this.shapeID = id;
  62764. this._shape = shape;
  62765. this._indicesLength = indicesLength;
  62766. this._shapeUV = shapeUV;
  62767. this._positionFunction = posFunction;
  62768. this._vertexFunction = vtxFunction;
  62769. }
  62770. return ModelShape;
  62771. }());
  62772. BABYLON.ModelShape = ModelShape;
  62773. /**
  62774. * Represents a Depth Sorted Particle in the solid particle system.
  62775. */
  62776. var DepthSortedParticle = /** @class */ (function () {
  62777. function DepthSortedParticle() {
  62778. /**
  62779. * Index of the particle in the "indices" array
  62780. */
  62781. this.ind = 0;
  62782. /**
  62783. * Length of the particle shape in the "indices" array
  62784. */
  62785. this.indicesLength = 0;
  62786. /**
  62787. * Squared distance from the particle to the camera
  62788. */
  62789. this.sqDistance = 0.0;
  62790. }
  62791. return DepthSortedParticle;
  62792. }());
  62793. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62794. })(BABYLON || (BABYLON = {}));
  62795. //# sourceMappingURL=babylon.solidParticle.js.map
  62796. var BABYLON;
  62797. (function (BABYLON) {
  62798. /**
  62799. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62800. *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.
  62801. * The SPS is also a particle system. It provides some methods to manage the particles.
  62802. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62803. *
  62804. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62805. */
  62806. var SolidParticleSystem = /** @class */ (function () {
  62807. /**
  62808. * Creates a SPS (Solid Particle System) object.
  62809. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62810. * @param scene (Scene) is the scene in which the SPS is added.
  62811. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62812. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62813. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62814. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62815. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62816. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62817. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62818. */
  62819. function SolidParticleSystem(name, scene, options) {
  62820. /**
  62821. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62822. * Example : var p = SPS.particles[i];
  62823. */
  62824. this.particles = new Array();
  62825. /**
  62826. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62827. */
  62828. this.nbParticles = 0;
  62829. /**
  62830. * If the particles must ever face the camera (default false). Useful for planar particles.
  62831. */
  62832. this.billboard = false;
  62833. /**
  62834. * Recompute normals when adding a shape
  62835. */
  62836. this.recomputeNormals = true;
  62837. /**
  62838. * This a counter ofr your own usage. It's not set by any SPS functions.
  62839. */
  62840. this.counter = 0;
  62841. /**
  62842. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62843. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62844. */
  62845. this.vars = {};
  62846. /**
  62847. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62848. * @hidden
  62849. */
  62850. this._bSphereOnly = false;
  62851. /**
  62852. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62853. * @hidden
  62854. */
  62855. this._bSphereRadiusFactor = 1.0;
  62856. this._positions = new Array();
  62857. this._indices = new Array();
  62858. this._normals = new Array();
  62859. this._colors = new Array();
  62860. this._uvs = new Array();
  62861. this._index = 0; // indices index
  62862. this._updatable = true;
  62863. this._pickable = false;
  62864. this._isVisibilityBoxLocked = false;
  62865. this._alwaysVisible = false;
  62866. this._depthSort = false;
  62867. this._shapeCounter = 0;
  62868. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62869. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62870. this._computeParticleColor = true;
  62871. this._computeParticleTexture = true;
  62872. this._computeParticleRotation = true;
  62873. this._computeParticleVertex = false;
  62874. this._computeBoundingBox = false;
  62875. this._depthSortParticles = true;
  62876. this._cam_axisZ = BABYLON.Vector3.Zero();
  62877. this._cam_axisY = BABYLON.Vector3.Zero();
  62878. this._cam_axisX = BABYLON.Vector3.Zero();
  62879. this._axisZ = BABYLON.Axis.Z;
  62880. this._camDir = BABYLON.Vector3.Zero();
  62881. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62882. this._rotMatrix = new BABYLON.Matrix();
  62883. this._invertMatrix = new BABYLON.Matrix();
  62884. this._rotated = BABYLON.Vector3.Zero();
  62885. this._quaternion = new BABYLON.Quaternion();
  62886. this._vertex = BABYLON.Vector3.Zero();
  62887. this._normal = BABYLON.Vector3.Zero();
  62888. this._yaw = 0.0;
  62889. this._pitch = 0.0;
  62890. this._roll = 0.0;
  62891. this._halfroll = 0.0;
  62892. this._halfpitch = 0.0;
  62893. this._halfyaw = 0.0;
  62894. this._sinRoll = 0.0;
  62895. this._cosRoll = 0.0;
  62896. this._sinPitch = 0.0;
  62897. this._cosPitch = 0.0;
  62898. this._sinYaw = 0.0;
  62899. this._cosYaw = 0.0;
  62900. this._mustUnrotateFixedNormals = false;
  62901. this._minimum = BABYLON.Vector3.Zero();
  62902. this._maximum = BABYLON.Vector3.Zero();
  62903. this._minBbox = BABYLON.Vector3.Zero();
  62904. this._maxBbox = BABYLON.Vector3.Zero();
  62905. this._particlesIntersect = false;
  62906. this._depthSortFunction = function (p1, p2) {
  62907. return (p2.sqDistance - p1.sqDistance);
  62908. };
  62909. this._needs32Bits = false;
  62910. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62911. this._scaledPivot = BABYLON.Vector3.Zero();
  62912. this._particleHasParent = false;
  62913. this.name = name;
  62914. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62915. this._camera = scene.activeCamera;
  62916. this._pickable = options ? options.isPickable : false;
  62917. this._depthSort = options ? options.enableDepthSort : false;
  62918. this._particlesIntersect = options ? options.particleIntersection : false;
  62919. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62920. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62921. if (options && options.updatable !== undefined) {
  62922. this._updatable = options.updatable;
  62923. }
  62924. else {
  62925. this._updatable = true;
  62926. }
  62927. if (this._pickable) {
  62928. this.pickedParticles = [];
  62929. }
  62930. if (this._depthSort) {
  62931. this.depthSortedParticles = [];
  62932. }
  62933. }
  62934. /**
  62935. * Builds the SPS underlying mesh. Returns a standard Mesh.
  62936. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  62937. * @returns the created mesh
  62938. */
  62939. SolidParticleSystem.prototype.buildMesh = function () {
  62940. if (this.nbParticles === 0) {
  62941. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  62942. this.addShape(triangle, 1);
  62943. triangle.dispose();
  62944. }
  62945. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  62946. this._positions32 = new Float32Array(this._positions);
  62947. this._uvs32 = new Float32Array(this._uvs);
  62948. this._colors32 = new Float32Array(this._colors);
  62949. if (this.recomputeNormals) {
  62950. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  62951. }
  62952. this._normals32 = new Float32Array(this._normals);
  62953. this._fixedNormal32 = new Float32Array(this._normals);
  62954. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  62955. this._unrotateFixedNormals();
  62956. }
  62957. var vertexData = new BABYLON.VertexData();
  62958. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  62959. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  62960. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  62961. if (this._uvs32.length > 0) {
  62962. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  62963. }
  62964. if (this._colors32.length > 0) {
  62965. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  62966. }
  62967. var mesh = new BABYLON.Mesh(this.name, this._scene);
  62968. vertexData.applyToMesh(mesh, this._updatable);
  62969. this.mesh = mesh;
  62970. this.mesh.isPickable = this._pickable;
  62971. // free memory
  62972. if (!this._depthSort) {
  62973. this._indices = null;
  62974. }
  62975. this._positions = null;
  62976. this._normals = null;
  62977. this._uvs = null;
  62978. this._colors = null;
  62979. if (!this._updatable) {
  62980. this.particles.length = 0;
  62981. }
  62982. return mesh;
  62983. };
  62984. /**
  62985. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  62986. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  62987. * Thus the particles generated from `digest()` have their property `position` set yet.
  62988. * @param mesh ( Mesh ) is the mesh to be digested
  62989. * @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
  62990. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  62991. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  62992. * @returns the current SPS
  62993. */
  62994. SolidParticleSystem.prototype.digest = function (mesh, options) {
  62995. var size = (options && options.facetNb) || 1;
  62996. var number = (options && options.number) || 0;
  62997. var delta = (options && options.delta) || 0;
  62998. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62999. var meshInd = mesh.getIndices();
  63000. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63001. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63002. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63003. var f = 0; // facet counter
  63004. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  63005. // compute size from number
  63006. if (number) {
  63007. number = (number > totalFacets) ? totalFacets : number;
  63008. size = Math.round(totalFacets / number);
  63009. delta = 0;
  63010. }
  63011. else {
  63012. size = (size > totalFacets) ? totalFacets : size;
  63013. }
  63014. var facetPos = []; // submesh positions
  63015. var facetInd = []; // submesh indices
  63016. var facetUV = []; // submesh UV
  63017. var facetCol = []; // submesh colors
  63018. var barycenter = BABYLON.Vector3.Zero();
  63019. var sizeO = size;
  63020. while (f < totalFacets) {
  63021. size = sizeO + Math.floor((1 + delta) * Math.random());
  63022. if (f > totalFacets - size) {
  63023. size = totalFacets - f;
  63024. }
  63025. // reset temp arrays
  63026. facetPos.length = 0;
  63027. facetInd.length = 0;
  63028. facetUV.length = 0;
  63029. facetCol.length = 0;
  63030. // iterate over "size" facets
  63031. var fi = 0;
  63032. for (var j = f * 3; j < (f + size) * 3; j++) {
  63033. facetInd.push(fi);
  63034. var i = meshInd[j];
  63035. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  63036. if (meshUV) {
  63037. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  63038. }
  63039. if (meshCol) {
  63040. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  63041. }
  63042. fi++;
  63043. }
  63044. // create a model shape for each single particle
  63045. var idx = this.nbParticles;
  63046. var shape = this._posToShape(facetPos);
  63047. var shapeUV = this._uvsToShapeUV(facetUV);
  63048. // compute the barycenter of the shape
  63049. var v;
  63050. for (v = 0; v < shape.length; v++) {
  63051. barycenter.addInPlace(shape[v]);
  63052. }
  63053. barycenter.scaleInPlace(1 / shape.length);
  63054. // shift the shape from its barycenter to the origin
  63055. for (v = 0; v < shape.length; v++) {
  63056. shape[v].subtractInPlace(barycenter);
  63057. }
  63058. var bInfo;
  63059. if (this._particlesIntersect) {
  63060. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  63061. }
  63062. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  63063. // add the particle in the SPS
  63064. var currentPos = this._positions.length;
  63065. var currentInd = this._indices.length;
  63066. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  63067. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  63068. // initialize the particle position
  63069. this.particles[this.nbParticles].position.addInPlace(barycenter);
  63070. this._index += shape.length;
  63071. idx++;
  63072. this.nbParticles++;
  63073. this._shapeCounter++;
  63074. f += size;
  63075. }
  63076. return this;
  63077. };
  63078. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  63079. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  63080. var index = 0;
  63081. var idx = 0;
  63082. for (var p = 0; p < this.particles.length; p++) {
  63083. this._particle = this.particles[p];
  63084. this._shape = this._particle._model._shape;
  63085. if (this._particle.rotationQuaternion) {
  63086. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63087. }
  63088. else {
  63089. this._yaw = this._particle.rotation.y;
  63090. this._pitch = this._particle.rotation.x;
  63091. this._roll = this._particle.rotation.z;
  63092. this._quaternionRotationYPR();
  63093. }
  63094. this._quaternionToRotationMatrix();
  63095. this._rotMatrix.invertToRef(this._invertMatrix);
  63096. for (var pt = 0; pt < this._shape.length; pt++) {
  63097. idx = index + pt * 3;
  63098. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  63099. this._fixedNormal32[idx] = this._normal.x;
  63100. this._fixedNormal32[idx + 1] = this._normal.y;
  63101. this._fixedNormal32[idx + 2] = this._normal.z;
  63102. }
  63103. index = idx + 3;
  63104. }
  63105. };
  63106. //reset copy
  63107. SolidParticleSystem.prototype._resetCopy = function () {
  63108. this._copy.position.x = 0;
  63109. this._copy.position.y = 0;
  63110. this._copy.position.z = 0;
  63111. this._copy.rotation.x = 0;
  63112. this._copy.rotation.y = 0;
  63113. this._copy.rotation.z = 0;
  63114. this._copy.rotationQuaternion = null;
  63115. this._copy.scaling.x = 1.0;
  63116. this._copy.scaling.y = 1.0;
  63117. this._copy.scaling.z = 1.0;
  63118. this._copy.uvs.x = 0;
  63119. this._copy.uvs.y = 0;
  63120. this._copy.uvs.z = 1.0;
  63121. this._copy.uvs.w = 1.0;
  63122. this._copy.color = null;
  63123. this._copy.translateFromPivot = false;
  63124. };
  63125. // _meshBuilder : inserts the shape model in the global SPS mesh
  63126. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  63127. var i;
  63128. var u = 0;
  63129. var c = 0;
  63130. var n = 0;
  63131. this._resetCopy();
  63132. if (options && options.positionFunction) { // call to custom positionFunction
  63133. options.positionFunction(this._copy, idx, idxInShape);
  63134. this._mustUnrotateFixedNormals = true;
  63135. }
  63136. if (this._copy.rotationQuaternion) {
  63137. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63138. }
  63139. else {
  63140. this._yaw = this._copy.rotation.y;
  63141. this._pitch = this._copy.rotation.x;
  63142. this._roll = this._copy.rotation.z;
  63143. this._quaternionRotationYPR();
  63144. }
  63145. this._quaternionToRotationMatrix();
  63146. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  63147. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  63148. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  63149. if (this._copy.translateFromPivot) {
  63150. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63151. }
  63152. else {
  63153. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63154. }
  63155. for (i = 0; i < shape.length; i++) {
  63156. this._vertex.x = shape[i].x;
  63157. this._vertex.y = shape[i].y;
  63158. this._vertex.z = shape[i].z;
  63159. if (options && options.vertexFunction) {
  63160. options.vertexFunction(this._copy, this._vertex, i);
  63161. }
  63162. this._vertex.x *= this._copy.scaling.x;
  63163. this._vertex.y *= this._copy.scaling.y;
  63164. this._vertex.z *= this._copy.scaling.z;
  63165. this._vertex.x -= this._scaledPivot.x;
  63166. this._vertex.y -= this._scaledPivot.y;
  63167. this._vertex.z -= this._scaledPivot.z;
  63168. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63169. this._rotated.addInPlace(this._pivotBackTranslation);
  63170. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  63171. if (meshUV) {
  63172. 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);
  63173. u += 2;
  63174. }
  63175. if (this._copy.color) {
  63176. this._color = this._copy.color;
  63177. }
  63178. else if (meshCol && meshCol[c] !== undefined) {
  63179. this._color.r = meshCol[c];
  63180. this._color.g = meshCol[c + 1];
  63181. this._color.b = meshCol[c + 2];
  63182. this._color.a = meshCol[c + 3];
  63183. }
  63184. else {
  63185. this._color.r = 1.0;
  63186. this._color.g = 1.0;
  63187. this._color.b = 1.0;
  63188. this._color.a = 1.0;
  63189. }
  63190. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  63191. c += 4;
  63192. if (!this.recomputeNormals && meshNor) {
  63193. this._normal.x = meshNor[n];
  63194. this._normal.y = meshNor[n + 1];
  63195. this._normal.z = meshNor[n + 2];
  63196. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  63197. normals.push(this._normal.x, this._normal.y, this._normal.z);
  63198. n += 3;
  63199. }
  63200. }
  63201. for (i = 0; i < meshInd.length; i++) {
  63202. var current_ind = p + meshInd[i];
  63203. indices.push(current_ind);
  63204. if (current_ind > 65535) {
  63205. this._needs32Bits = true;
  63206. }
  63207. }
  63208. if (this._pickable) {
  63209. var nbfaces = meshInd.length / 3;
  63210. for (i = 0; i < nbfaces; i++) {
  63211. this.pickedParticles.push({ idx: idx, faceId: i });
  63212. }
  63213. }
  63214. if (this._depthSort) {
  63215. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  63216. }
  63217. return this._copy;
  63218. };
  63219. // returns a shape array from positions array
  63220. SolidParticleSystem.prototype._posToShape = function (positions) {
  63221. var shape = [];
  63222. for (var i = 0; i < positions.length; i += 3) {
  63223. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  63224. }
  63225. return shape;
  63226. };
  63227. // returns a shapeUV array from a Vector4 uvs
  63228. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  63229. var shapeUV = [];
  63230. if (uvs) {
  63231. for (var i = 0; i < uvs.length; i++)
  63232. shapeUV.push(uvs[i]);
  63233. }
  63234. return shapeUV;
  63235. };
  63236. // adds a new particle object in the particles array
  63237. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  63238. if (bInfo === void 0) { bInfo = null; }
  63239. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  63240. this.particles.push(sp);
  63241. return sp;
  63242. };
  63243. /**
  63244. * Adds some particles to the SPS from the model shape. Returns the shape id.
  63245. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  63246. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  63247. * @param nb (positive integer) the number of particles to be created from this model
  63248. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  63249. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  63250. * @returns the number of shapes in the system
  63251. */
  63252. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  63253. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63254. var meshInd = mesh.getIndices();
  63255. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63256. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63257. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63258. var bbInfo;
  63259. if (this._particlesIntersect) {
  63260. bbInfo = mesh.getBoundingInfo();
  63261. }
  63262. var shape = this._posToShape(meshPos);
  63263. var shapeUV = this._uvsToShapeUV(meshUV);
  63264. var posfunc = options ? options.positionFunction : null;
  63265. var vtxfunc = options ? options.vertexFunction : null;
  63266. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  63267. // particles
  63268. var sp;
  63269. var currentCopy;
  63270. var idx = this.nbParticles;
  63271. for (var i = 0; i < nb; i++) {
  63272. var currentPos = this._positions.length;
  63273. var currentInd = this._indices.length;
  63274. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  63275. if (this._updatable) {
  63276. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  63277. sp.position.copyFrom(currentCopy.position);
  63278. sp.rotation.copyFrom(currentCopy.rotation);
  63279. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  63280. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  63281. }
  63282. if (currentCopy.color && sp.color) {
  63283. sp.color.copyFrom(currentCopy.color);
  63284. }
  63285. sp.scaling.copyFrom(currentCopy.scaling);
  63286. sp.uvs.copyFrom(currentCopy.uvs);
  63287. }
  63288. this._index += shape.length;
  63289. idx++;
  63290. }
  63291. this.nbParticles += nb;
  63292. this._shapeCounter++;
  63293. return this._shapeCounter - 1;
  63294. };
  63295. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  63296. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  63297. this._resetCopy();
  63298. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  63299. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  63300. }
  63301. if (this._copy.rotationQuaternion) {
  63302. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63303. }
  63304. else {
  63305. this._yaw = this._copy.rotation.y;
  63306. this._pitch = this._copy.rotation.x;
  63307. this._roll = this._copy.rotation.z;
  63308. this._quaternionRotationYPR();
  63309. }
  63310. this._quaternionToRotationMatrix();
  63311. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63312. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63313. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63314. if (this._copy.translateFromPivot) {
  63315. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63316. }
  63317. else {
  63318. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63319. }
  63320. this._shape = particle._model._shape;
  63321. for (var pt = 0; pt < this._shape.length; pt++) {
  63322. this._vertex.x = this._shape[pt].x;
  63323. this._vertex.y = this._shape[pt].y;
  63324. this._vertex.z = this._shape[pt].z;
  63325. if (particle._model._vertexFunction) {
  63326. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  63327. }
  63328. this._vertex.x *= this._copy.scaling.x;
  63329. this._vertex.y *= this._copy.scaling.y;
  63330. this._vertex.z *= this._copy.scaling.z;
  63331. this._vertex.x -= this._scaledPivot.x;
  63332. this._vertex.y -= this._scaledPivot.y;
  63333. this._vertex.z -= this._scaledPivot.z;
  63334. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63335. this._rotated.addInPlace(this._pivotBackTranslation);
  63336. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  63337. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  63338. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  63339. }
  63340. particle.position.x = 0.0;
  63341. particle.position.y = 0.0;
  63342. particle.position.z = 0.0;
  63343. particle.rotation.x = 0.0;
  63344. particle.rotation.y = 0.0;
  63345. particle.rotation.z = 0.0;
  63346. particle.rotationQuaternion = null;
  63347. particle.scaling.x = 1.0;
  63348. particle.scaling.y = 1.0;
  63349. particle.scaling.z = 1.0;
  63350. particle.uvs.x = 0.0;
  63351. particle.uvs.y = 0.0;
  63352. particle.uvs.z = 1.0;
  63353. particle.uvs.w = 1.0;
  63354. particle.pivot.x = 0.0;
  63355. particle.pivot.y = 0.0;
  63356. particle.pivot.z = 0.0;
  63357. particle.translateFromPivot = false;
  63358. particle.parentId = null;
  63359. };
  63360. /**
  63361. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63362. * @returns the SPS.
  63363. */
  63364. SolidParticleSystem.prototype.rebuildMesh = function () {
  63365. for (var p = 0; p < this.particles.length; p++) {
  63366. this._rebuildParticle(this.particles[p]);
  63367. }
  63368. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63369. return this;
  63370. };
  63371. /**
  63372. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63373. * This method calls `updateParticle()` for each particle of the SPS.
  63374. * For an animated SPS, it is usually called within the render loop.
  63375. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63376. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63377. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63378. * @returns the SPS.
  63379. */
  63380. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63381. if (start === void 0) { start = 0; }
  63382. if (end === void 0) { end = this.nbParticles - 1; }
  63383. if (update === void 0) { update = true; }
  63384. if (!this._updatable) {
  63385. return this;
  63386. }
  63387. // custom beforeUpdate
  63388. this.beforeUpdateParticles(start, end, update);
  63389. this._cam_axisX.x = 1.0;
  63390. this._cam_axisX.y = 0.0;
  63391. this._cam_axisX.z = 0.0;
  63392. this._cam_axisY.x = 0.0;
  63393. this._cam_axisY.y = 1.0;
  63394. this._cam_axisY.z = 0.0;
  63395. this._cam_axisZ.x = 0.0;
  63396. this._cam_axisZ.y = 0.0;
  63397. this._cam_axisZ.z = 1.0;
  63398. // cases when the World Matrix is to be computed first
  63399. if (this.billboard || this._depthSort) {
  63400. this.mesh.computeWorldMatrix(true);
  63401. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63402. }
  63403. // if the particles will always face the camera
  63404. if (this.billboard) {
  63405. // compute the camera position and un-rotate it by the current mesh rotation
  63406. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63407. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63408. this._cam_axisZ.normalize();
  63409. // same for camera up vector extracted from the cam view matrix
  63410. var view = this._camera.getViewMatrix(true);
  63411. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63412. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63413. this._cam_axisY.normalize();
  63414. this._cam_axisX.normalize();
  63415. }
  63416. // if depthSort, compute the camera global position in the mesh local system
  63417. if (this._depthSort) {
  63418. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63419. }
  63420. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63421. var idx = 0; // current position index in the global array positions32
  63422. var index = 0; // position start index in the global array positions32 of the current particle
  63423. var colidx = 0; // current color index in the global array colors32
  63424. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63425. var uvidx = 0; // current uv index in the global array uvs32
  63426. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63427. var pt = 0; // current index in the particle model shape
  63428. if (this.mesh.isFacetDataEnabled) {
  63429. this._computeBoundingBox = true;
  63430. }
  63431. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63432. if (this._computeBoundingBox) {
  63433. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63434. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63435. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63436. }
  63437. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63438. if (this.mesh._boundingInfo) {
  63439. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63440. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63441. }
  63442. }
  63443. }
  63444. // particle loop
  63445. index = this.particles[start]._pos;
  63446. var vpos = (index / 3) | 0;
  63447. colorIndex = vpos * 4;
  63448. uvIndex = vpos * 2;
  63449. for (var p = start; p <= end; p++) {
  63450. this._particle = this.particles[p];
  63451. this._shape = this._particle._model._shape;
  63452. this._shapeUV = this._particle._model._shapeUV;
  63453. // call to custom user function to update the particle properties
  63454. this.updateParticle(this._particle);
  63455. // camera-particle distance for depth sorting
  63456. if (this._depthSort && this._depthSortParticles) {
  63457. var dsp = this.depthSortedParticles[p];
  63458. dsp.ind = this._particle._ind;
  63459. dsp.indicesLength = this._particle._model._indicesLength;
  63460. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63461. }
  63462. // skip the computations for inactive or already invisible particles
  63463. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63464. // increment indexes for the next particle
  63465. pt = this._shape.length;
  63466. index += pt * 3;
  63467. colorIndex += pt * 4;
  63468. uvIndex += pt * 2;
  63469. continue;
  63470. }
  63471. if (this._particle.isVisible) {
  63472. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63473. this._particleHasParent = (this._particle.parentId !== null);
  63474. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63475. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63476. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63477. // particle rotation matrix
  63478. if (this.billboard) {
  63479. this._particle.rotation.x = 0.0;
  63480. this._particle.rotation.y = 0.0;
  63481. }
  63482. if (this._computeParticleRotation || this.billboard) {
  63483. if (this._particle.rotationQuaternion) {
  63484. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63485. }
  63486. else {
  63487. this._yaw = this._particle.rotation.y;
  63488. this._pitch = this._particle.rotation.x;
  63489. this._roll = this._particle.rotation.z;
  63490. this._quaternionRotationYPR();
  63491. }
  63492. this._quaternionToRotationMatrix();
  63493. }
  63494. if (this._particleHasParent) {
  63495. this._parent = this.particles[this._particle.parentId];
  63496. 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];
  63497. 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];
  63498. 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];
  63499. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63500. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63501. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63502. if (this._computeParticleRotation || this.billboard) {
  63503. 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];
  63504. 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];
  63505. 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];
  63506. 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];
  63507. 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];
  63508. 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];
  63509. 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];
  63510. 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];
  63511. 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];
  63512. }
  63513. }
  63514. else {
  63515. this._particle._globalPosition.x = this._particle.position.x;
  63516. this._particle._globalPosition.y = this._particle.position.y;
  63517. this._particle._globalPosition.z = this._particle.position.z;
  63518. if (this._computeParticleRotation || this.billboard) {
  63519. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63520. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63521. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63522. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63523. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63524. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63525. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63526. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63527. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63528. }
  63529. }
  63530. if (this._particle.translateFromPivot) {
  63531. this._pivotBackTranslation.x = 0.0;
  63532. this._pivotBackTranslation.y = 0.0;
  63533. this._pivotBackTranslation.z = 0.0;
  63534. }
  63535. else {
  63536. this._pivotBackTranslation.x = this._scaledPivot.x;
  63537. this._pivotBackTranslation.y = this._scaledPivot.y;
  63538. this._pivotBackTranslation.z = this._scaledPivot.z;
  63539. }
  63540. // particle vertex loop
  63541. for (pt = 0; pt < this._shape.length; pt++) {
  63542. idx = index + pt * 3;
  63543. colidx = colorIndex + pt * 4;
  63544. uvidx = uvIndex + pt * 2;
  63545. this._vertex.x = this._shape[pt].x;
  63546. this._vertex.y = this._shape[pt].y;
  63547. this._vertex.z = this._shape[pt].z;
  63548. if (this._computeParticleVertex) {
  63549. this.updateParticleVertex(this._particle, this._vertex, pt);
  63550. }
  63551. // positions
  63552. this._vertex.x *= this._particle.scaling.x;
  63553. this._vertex.y *= this._particle.scaling.y;
  63554. this._vertex.z *= this._particle.scaling.z;
  63555. this._vertex.x -= this._scaledPivot.x;
  63556. this._vertex.y -= this._scaledPivot.y;
  63557. this._vertex.z -= this._scaledPivot.z;
  63558. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63559. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63560. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63561. this._rotated.x += this._pivotBackTranslation.x;
  63562. this._rotated.y += this._pivotBackTranslation.y;
  63563. this._rotated.z += this._pivotBackTranslation.z;
  63564. 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;
  63565. 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;
  63566. 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;
  63567. if (this._computeBoundingBox) {
  63568. if (this._positions32[idx] < this._minimum.x) {
  63569. this._minimum.x = this._positions32[idx];
  63570. }
  63571. if (this._positions32[idx] > this._maximum.x) {
  63572. this._maximum.x = this._positions32[idx];
  63573. }
  63574. if (this._positions32[idx + 1] < this._minimum.y) {
  63575. this._minimum.y = this._positions32[idx + 1];
  63576. }
  63577. if (this._positions32[idx + 1] > this._maximum.y) {
  63578. this._maximum.y = this._positions32[idx + 1];
  63579. }
  63580. if (this._positions32[idx + 2] < this._minimum.z) {
  63581. this._minimum.z = this._positions32[idx + 2];
  63582. }
  63583. if (this._positions32[idx + 2] > this._maximum.z) {
  63584. this._maximum.z = this._positions32[idx + 2];
  63585. }
  63586. }
  63587. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63588. if (!this._computeParticleVertex) {
  63589. this._normal.x = this._fixedNormal32[idx];
  63590. this._normal.y = this._fixedNormal32[idx + 1];
  63591. this._normal.z = this._fixedNormal32[idx + 2];
  63592. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63593. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63594. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63595. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63596. 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;
  63597. 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;
  63598. }
  63599. if (this._computeParticleColor && this._particle.color) {
  63600. this._colors32[colidx] = this._particle.color.r;
  63601. this._colors32[colidx + 1] = this._particle.color.g;
  63602. this._colors32[colidx + 2] = this._particle.color.b;
  63603. this._colors32[colidx + 3] = this._particle.color.a;
  63604. }
  63605. if (this._computeParticleTexture) {
  63606. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63607. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63608. }
  63609. }
  63610. }
  63611. // particle just set invisible : scaled to zero and positioned at the origin
  63612. else {
  63613. this._particle._stillInvisible = true; // mark the particle as invisible
  63614. for (pt = 0; pt < this._shape.length; pt++) {
  63615. idx = index + pt * 3;
  63616. colidx = colorIndex + pt * 4;
  63617. uvidx = uvIndex + pt * 2;
  63618. this._positions32[idx] = 0.0;
  63619. this._positions32[idx + 1] = 0.0;
  63620. this._positions32[idx + 2] = 0.0;
  63621. this._normals32[idx] = 0.0;
  63622. this._normals32[idx + 1] = 0.0;
  63623. this._normals32[idx + 2] = 0.0;
  63624. if (this._computeParticleColor && this._particle.color) {
  63625. this._colors32[colidx] = this._particle.color.r;
  63626. this._colors32[colidx + 1] = this._particle.color.g;
  63627. this._colors32[colidx + 2] = this._particle.color.b;
  63628. this._colors32[colidx + 3] = this._particle.color.a;
  63629. }
  63630. if (this._computeParticleTexture) {
  63631. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63632. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63633. }
  63634. }
  63635. }
  63636. // if the particle intersections must be computed : update the bbInfo
  63637. if (this._particlesIntersect) {
  63638. var bInfo = this._particle._boundingInfo;
  63639. var bBox = bInfo.boundingBox;
  63640. var bSphere = bInfo.boundingSphere;
  63641. if (!this._bSphereOnly) {
  63642. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63643. for (var b = 0; b < bBox.vectors.length; b++) {
  63644. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63645. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63646. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63647. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63648. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63649. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63650. 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;
  63651. 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;
  63652. 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;
  63653. }
  63654. bBox._update(this.mesh._worldMatrix);
  63655. }
  63656. // place and scale the particle bouding sphere in the SPS local system, then update it
  63657. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63658. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63659. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63660. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63661. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63662. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63663. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63664. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63665. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63666. 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));
  63667. bSphere._update(this.mesh._worldMatrix);
  63668. }
  63669. // increment indexes for the next particle
  63670. index = idx + 3;
  63671. colorIndex = colidx + 4;
  63672. uvIndex = uvidx + 2;
  63673. }
  63674. // if the VBO must be updated
  63675. if (update) {
  63676. if (this._computeParticleColor) {
  63677. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63678. }
  63679. if (this._computeParticleTexture) {
  63680. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63681. }
  63682. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63683. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63684. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63685. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63686. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63687. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63688. for (var i = 0; i < this._normals32.length; i++) {
  63689. this._fixedNormal32[i] = this._normals32[i];
  63690. }
  63691. }
  63692. if (!this.mesh.areNormalsFrozen) {
  63693. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63694. }
  63695. }
  63696. if (this._depthSort && this._depthSortParticles) {
  63697. this.depthSortedParticles.sort(this._depthSortFunction);
  63698. var dspl = this.depthSortedParticles.length;
  63699. var sorted = 0;
  63700. var lind = 0;
  63701. var sind = 0;
  63702. var sid = 0;
  63703. for (sorted = 0; sorted < dspl; sorted++) {
  63704. lind = this.depthSortedParticles[sorted].indicesLength;
  63705. sind = this.depthSortedParticles[sorted].ind;
  63706. for (var i = 0; i < lind; i++) {
  63707. this._indices32[sid] = this._indices[sind + i];
  63708. sid++;
  63709. }
  63710. }
  63711. this.mesh.updateIndices(this._indices32);
  63712. }
  63713. }
  63714. if (this._computeBoundingBox) {
  63715. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63716. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63717. }
  63718. this.afterUpdateParticles(start, end, update);
  63719. return this;
  63720. };
  63721. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63722. this._halfroll = this._roll * 0.5;
  63723. this._halfpitch = this._pitch * 0.5;
  63724. this._halfyaw = this._yaw * 0.5;
  63725. this._sinRoll = Math.sin(this._halfroll);
  63726. this._cosRoll = Math.cos(this._halfroll);
  63727. this._sinPitch = Math.sin(this._halfpitch);
  63728. this._cosPitch = Math.cos(this._halfpitch);
  63729. this._sinYaw = Math.sin(this._halfyaw);
  63730. this._cosYaw = Math.cos(this._halfyaw);
  63731. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63732. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63733. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63734. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63735. };
  63736. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63737. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63738. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63739. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63740. this._rotMatrix.m[3] = 0;
  63741. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63742. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63743. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63744. this._rotMatrix.m[7] = 0;
  63745. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63746. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63747. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63748. this._rotMatrix.m[11] = 0;
  63749. this._rotMatrix.m[12] = 0;
  63750. this._rotMatrix.m[13] = 0;
  63751. this._rotMatrix.m[14] = 0;
  63752. this._rotMatrix.m[15] = 1.0;
  63753. };
  63754. /**
  63755. * Disposes the SPS.
  63756. */
  63757. SolidParticleSystem.prototype.dispose = function () {
  63758. this.mesh.dispose();
  63759. this.vars = null;
  63760. // drop references to internal big arrays for the GC
  63761. this._positions = null;
  63762. this._indices = null;
  63763. this._normals = null;
  63764. this._uvs = null;
  63765. this._colors = null;
  63766. this._indices32 = null;
  63767. this._positions32 = null;
  63768. this._normals32 = null;
  63769. this._fixedNormal32 = null;
  63770. this._uvs32 = null;
  63771. this._colors32 = null;
  63772. this.pickedParticles = null;
  63773. };
  63774. /**
  63775. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63776. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63777. * @returns the SPS.
  63778. */
  63779. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63780. if (!this._isVisibilityBoxLocked) {
  63781. this.mesh.refreshBoundingInfo();
  63782. }
  63783. return this;
  63784. };
  63785. /**
  63786. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63787. * @param size the size (float) of the visibility box
  63788. * note : this doesn't lock the SPS mesh bounding box.
  63789. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63790. */
  63791. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63792. var vis = size / 2;
  63793. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63794. };
  63795. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63796. /**
  63797. * Gets whether the SPS as always visible or not
  63798. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63799. */
  63800. get: function () {
  63801. return this._alwaysVisible;
  63802. },
  63803. /**
  63804. * Sets the SPS as always visible or not
  63805. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63806. */
  63807. set: function (val) {
  63808. this._alwaysVisible = val;
  63809. this.mesh.alwaysSelectAsActiveMesh = val;
  63810. },
  63811. enumerable: true,
  63812. configurable: true
  63813. });
  63814. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63815. /**
  63816. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63817. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63818. */
  63819. get: function () {
  63820. return this._isVisibilityBoxLocked;
  63821. },
  63822. /**
  63823. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63824. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63825. */
  63826. set: function (val) {
  63827. this._isVisibilityBoxLocked = val;
  63828. var boundingInfo = this.mesh.getBoundingInfo();
  63829. boundingInfo.isLocked = val;
  63830. },
  63831. enumerable: true,
  63832. configurable: true
  63833. });
  63834. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63835. /**
  63836. * Gets if `setParticles()` computes the particle rotations or not.
  63837. * Default value : true. The SPS is faster when it's set to false.
  63838. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63839. */
  63840. get: function () {
  63841. return this._computeParticleRotation;
  63842. },
  63843. /**
  63844. * Tells to `setParticles()` to compute the particle rotations or not.
  63845. * Default value : true. The SPS is faster when it's set to false.
  63846. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63847. */
  63848. set: function (val) {
  63849. this._computeParticleRotation = val;
  63850. },
  63851. enumerable: true,
  63852. configurable: true
  63853. });
  63854. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63855. /**
  63856. * Gets if `setParticles()` computes the particle colors or not.
  63857. * Default value : true. The SPS is faster when it's set to false.
  63858. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63859. */
  63860. get: function () {
  63861. return this._computeParticleColor;
  63862. },
  63863. /**
  63864. * Tells to `setParticles()` to compute the particle colors or not.
  63865. * Default value : true. The SPS is faster when it's set to false.
  63866. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63867. */
  63868. set: function (val) {
  63869. this._computeParticleColor = val;
  63870. },
  63871. enumerable: true,
  63872. configurable: true
  63873. });
  63874. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63875. /**
  63876. * Gets if `setParticles()` computes the particle textures or not.
  63877. * Default value : true. The SPS is faster when it's set to false.
  63878. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63879. */
  63880. get: function () {
  63881. return this._computeParticleTexture;
  63882. },
  63883. set: function (val) {
  63884. this._computeParticleTexture = val;
  63885. },
  63886. enumerable: true,
  63887. configurable: true
  63888. });
  63889. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63890. /**
  63891. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63892. * Default value : false. The SPS is faster when it's set to false.
  63893. * Note : the particle custom vertex positions aren't stored values.
  63894. */
  63895. get: function () {
  63896. return this._computeParticleVertex;
  63897. },
  63898. /**
  63899. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63900. * Default value : false. The SPS is faster when it's set to false.
  63901. * Note : the particle custom vertex positions aren't stored values.
  63902. */
  63903. set: function (val) {
  63904. this._computeParticleVertex = val;
  63905. },
  63906. enumerable: true,
  63907. configurable: true
  63908. });
  63909. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63910. /**
  63911. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63912. */
  63913. get: function () {
  63914. return this._computeBoundingBox;
  63915. },
  63916. /**
  63917. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63918. */
  63919. set: function (val) {
  63920. this._computeBoundingBox = val;
  63921. },
  63922. enumerable: true,
  63923. configurable: true
  63924. });
  63925. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63926. /**
  63927. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63928. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63929. * Default : `true`
  63930. */
  63931. get: function () {
  63932. return this._depthSortParticles;
  63933. },
  63934. /**
  63935. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  63936. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63937. * Default : `true`
  63938. */
  63939. set: function (val) {
  63940. this._depthSortParticles = val;
  63941. },
  63942. enumerable: true,
  63943. configurable: true
  63944. });
  63945. // =======================================================================
  63946. // Particle behavior logic
  63947. // these following methods may be overwritten by the user to fit his needs
  63948. /**
  63949. * This function does nothing. It may be overwritten to set all the particle first values.
  63950. * The SPS doesn't call this function, you may have to call it by your own.
  63951. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63952. */
  63953. SolidParticleSystem.prototype.initParticles = function () {
  63954. };
  63955. /**
  63956. * This function does nothing. It may be overwritten to recycle a particle.
  63957. * The SPS doesn't call this function, you may have to call it by your own.
  63958. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63959. * @param particle The particle to recycle
  63960. * @returns the recycled particle
  63961. */
  63962. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  63963. return particle;
  63964. };
  63965. /**
  63966. * Updates a particle : this function should be overwritten by the user.
  63967. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  63968. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63969. * @example : just set a particle position or velocity and recycle conditions
  63970. * @param particle The particle to update
  63971. * @returns the updated particle
  63972. */
  63973. SolidParticleSystem.prototype.updateParticle = function (particle) {
  63974. return particle;
  63975. };
  63976. /**
  63977. * Updates a vertex of a particle : it can be overwritten by the user.
  63978. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  63979. * @param particle the current particle
  63980. * @param vertex the current index of the current particle
  63981. * @param pt the index of the current vertex in the particle shape
  63982. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  63983. * @example : just set a vertex particle position
  63984. * @returns the updated vertex
  63985. */
  63986. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  63987. return vertex;
  63988. };
  63989. /**
  63990. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  63991. * This does nothing and may be overwritten by the user.
  63992. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63993. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63994. * @param update the boolean update value actually passed to setParticles()
  63995. */
  63996. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  63997. };
  63998. /**
  63999. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  64000. * This will be passed three parameters.
  64001. * This does nothing and may be overwritten by the user.
  64002. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64003. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64004. * @param update the boolean update value actually passed to setParticles()
  64005. */
  64006. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  64007. };
  64008. return SolidParticleSystem;
  64009. }());
  64010. BABYLON.SolidParticleSystem = SolidParticleSystem;
  64011. })(BABYLON || (BABYLON = {}));
  64012. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  64013. var BABYLON;
  64014. (function (BABYLON) {
  64015. /**
  64016. * Class containing static functions to help procedurally build meshes
  64017. */
  64018. var MeshBuilder = /** @class */ (function () {
  64019. function MeshBuilder() {
  64020. }
  64021. MeshBuilder.updateSideOrientation = function (orientation) {
  64022. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  64023. return BABYLON.Mesh.DOUBLESIDE;
  64024. }
  64025. if (orientation === undefined || orientation === null) {
  64026. return BABYLON.Mesh.FRONTSIDE;
  64027. }
  64028. return orientation;
  64029. };
  64030. /**
  64031. * Creates a box mesh
  64032. * * The parameter `size` sets the size (float) of each box side (default 1)
  64033. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  64034. * * 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)
  64035. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64036. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64037. * * 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
  64038. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64039. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  64040. * @param name defines the name of the mesh
  64041. * @param options defines the options used to create the mesh
  64042. * @param scene defines the hosting scene
  64043. * @returns the box mesh
  64044. */
  64045. MeshBuilder.CreateBox = function (name, options, scene) {
  64046. if (scene === void 0) { scene = null; }
  64047. var box = new BABYLON.Mesh(name, scene);
  64048. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64049. box._originalBuilderSideOrientation = options.sideOrientation;
  64050. var vertexData = BABYLON.VertexData.CreateBox(options);
  64051. vertexData.applyToMesh(box, options.updatable);
  64052. return box;
  64053. };
  64054. /**
  64055. * Creates a sphere mesh
  64056. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  64057. * * 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`)
  64058. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  64059. * * 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
  64060. * * 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)
  64061. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64062. * * 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
  64063. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64064. * @param name defines the name of the mesh
  64065. * @param options defines the options used to create the mesh
  64066. * @param scene defines the hosting scene
  64067. * @returns the sphere mesh
  64068. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  64069. */
  64070. MeshBuilder.CreateSphere = function (name, options, scene) {
  64071. var sphere = new BABYLON.Mesh(name, scene);
  64072. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64073. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64074. var vertexData = BABYLON.VertexData.CreateSphere(options);
  64075. vertexData.applyToMesh(sphere, options.updatable);
  64076. return sphere;
  64077. };
  64078. /**
  64079. * Creates a plane polygonal mesh. By default, this is a disc
  64080. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  64081. * * 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
  64082. * * 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
  64083. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64084. * * 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
  64085. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64086. * @param name defines the name of the mesh
  64087. * @param options defines the options used to create the mesh
  64088. * @param scene defines the hosting scene
  64089. * @returns the plane polygonal mesh
  64090. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  64091. */
  64092. MeshBuilder.CreateDisc = function (name, options, scene) {
  64093. if (scene === void 0) { scene = null; }
  64094. var disc = new BABYLON.Mesh(name, scene);
  64095. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64096. disc._originalBuilderSideOrientation = options.sideOrientation;
  64097. var vertexData = BABYLON.VertexData.CreateDisc(options);
  64098. vertexData.applyToMesh(disc, options.updatable);
  64099. return disc;
  64100. };
  64101. /**
  64102. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  64103. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  64104. * * 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`)
  64105. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  64106. * * 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
  64107. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64108. * * 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
  64109. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64110. * @param name defines the name of the mesh
  64111. * @param options defines the options used to create the mesh
  64112. * @param scene defines the hosting scene
  64113. * @returns the icosahedron mesh
  64114. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  64115. */
  64116. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  64117. var sphere = new BABYLON.Mesh(name, scene);
  64118. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64119. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64120. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  64121. vertexData.applyToMesh(sphere, options.updatable);
  64122. return sphere;
  64123. };
  64124. ;
  64125. /**
  64126. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64127. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  64128. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  64129. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  64130. * * 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
  64131. * * 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
  64132. * * 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
  64133. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64134. * * 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
  64135. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64136. * * 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
  64137. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  64138. * * 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
  64139. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  64140. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64141. * @param name defines the name of the mesh
  64142. * @param options defines the options used to create the mesh
  64143. * @param scene defines the hosting scene
  64144. * @returns the ribbon mesh
  64145. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  64146. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64147. */
  64148. MeshBuilder.CreateRibbon = function (name, options, scene) {
  64149. if (scene === void 0) { scene = null; }
  64150. var pathArray = options.pathArray;
  64151. var closeArray = options.closeArray;
  64152. var closePath = options.closePath;
  64153. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64154. var instance = options.instance;
  64155. var updatable = options.updatable;
  64156. if (instance) { // existing ribbon instance update
  64157. // positionFunction : ribbon case
  64158. // only pathArray and sideOrientation parameters are taken into account for positions update
  64159. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  64160. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  64161. var positionFunction = function (positions) {
  64162. var minlg = pathArray[0].length;
  64163. var i = 0;
  64164. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  64165. for (var si = 1; si <= ns; si++) {
  64166. for (var p = 0; p < pathArray.length; p++) {
  64167. var path = pathArray[p];
  64168. var l = path.length;
  64169. minlg = (minlg < l) ? minlg : l;
  64170. var j = 0;
  64171. while (j < minlg) {
  64172. positions[i] = path[j].x;
  64173. positions[i + 1] = path[j].y;
  64174. positions[i + 2] = path[j].z;
  64175. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  64176. BABYLON.Tmp.Vector3[0].x = path[j].x;
  64177. }
  64178. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  64179. BABYLON.Tmp.Vector3[1].x = path[j].x;
  64180. }
  64181. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  64182. BABYLON.Tmp.Vector3[0].y = path[j].y;
  64183. }
  64184. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  64185. BABYLON.Tmp.Vector3[1].y = path[j].y;
  64186. }
  64187. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  64188. BABYLON.Tmp.Vector3[0].z = path[j].z;
  64189. }
  64190. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  64191. BABYLON.Tmp.Vector3[1].z = path[j].z;
  64192. }
  64193. j++;
  64194. i += 3;
  64195. }
  64196. if (instance._closePath) {
  64197. positions[i] = path[0].x;
  64198. positions[i + 1] = path[0].y;
  64199. positions[i + 2] = path[0].z;
  64200. i += 3;
  64201. }
  64202. }
  64203. }
  64204. };
  64205. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64206. positionFunction(positions);
  64207. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  64208. instance._boundingInfo.update(instance._worldMatrix);
  64209. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64210. if (options.colors) {
  64211. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64212. for (var c = 0; c < options.colors.length; c++) {
  64213. colors[c * 4] = options.colors[c].r;
  64214. colors[c * 4 + 1] = options.colors[c].g;
  64215. colors[c * 4 + 2] = options.colors[c].b;
  64216. colors[c * 4 + 3] = options.colors[c].a;
  64217. }
  64218. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  64219. }
  64220. if (options.uvs) {
  64221. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64222. for (var i = 0; i < options.uvs.length; i++) {
  64223. uvs[i * 2] = options.uvs[i].x;
  64224. uvs[i * 2 + 1] = options.uvs[i].y;
  64225. }
  64226. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  64227. }
  64228. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  64229. var indices = instance.getIndices();
  64230. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64231. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  64232. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  64233. if (instance._closePath) {
  64234. var indexFirst = 0;
  64235. var indexLast = 0;
  64236. for (var p = 0; p < pathArray.length; p++) {
  64237. indexFirst = instance._idx[p] * 3;
  64238. if (p + 1 < pathArray.length) {
  64239. indexLast = (instance._idx[p + 1] - 1) * 3;
  64240. }
  64241. else {
  64242. indexLast = normals.length - 3;
  64243. }
  64244. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  64245. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  64246. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  64247. normals[indexLast] = normals[indexFirst];
  64248. normals[indexLast + 1] = normals[indexFirst + 1];
  64249. normals[indexLast + 2] = normals[indexFirst + 2];
  64250. }
  64251. }
  64252. if (!(instance.areNormalsFrozen)) {
  64253. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  64254. }
  64255. }
  64256. return instance;
  64257. }
  64258. else { // new ribbon creation
  64259. var ribbon = new BABYLON.Mesh(name, scene);
  64260. ribbon._originalBuilderSideOrientation = sideOrientation;
  64261. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  64262. if (closePath) {
  64263. ribbon._idx = vertexData._idx;
  64264. }
  64265. ribbon._closePath = closePath;
  64266. ribbon._closeArray = closeArray;
  64267. vertexData.applyToMesh(ribbon, updatable);
  64268. return ribbon;
  64269. }
  64270. };
  64271. /**
  64272. * Creates a cylinder or a cone mesh
  64273. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  64274. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  64275. * * 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.
  64276. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  64277. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  64278. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  64279. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  64280. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  64281. * * 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).
  64282. * * 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
  64283. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  64284. * * 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
  64285. * * 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.
  64286. * * If `enclose` is false, a ring surface is one element.
  64287. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  64288. * * 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
  64289. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64290. * * 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
  64291. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64292. * @param name defines the name of the mesh
  64293. * @param options defines the options used to create the mesh
  64294. * @param scene defines the hosting scene
  64295. * @returns the cylinder mesh
  64296. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  64297. */
  64298. MeshBuilder.CreateCylinder = function (name, options, scene) {
  64299. var cylinder = new BABYLON.Mesh(name, scene);
  64300. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64301. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  64302. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  64303. vertexData.applyToMesh(cylinder, options.updatable);
  64304. return cylinder;
  64305. };
  64306. /**
  64307. * Creates a torus mesh
  64308. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  64309. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  64310. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  64311. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64312. * * 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
  64313. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64314. * @param name defines the name of the mesh
  64315. * @param options defines the options used to create the mesh
  64316. * @param scene defines the hosting scene
  64317. * @returns the torus mesh
  64318. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  64319. */
  64320. MeshBuilder.CreateTorus = function (name, options, scene) {
  64321. var torus = new BABYLON.Mesh(name, scene);
  64322. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64323. torus._originalBuilderSideOrientation = options.sideOrientation;
  64324. var vertexData = BABYLON.VertexData.CreateTorus(options);
  64325. vertexData.applyToMesh(torus, options.updatable);
  64326. return torus;
  64327. };
  64328. /**
  64329. * Creates a torus knot mesh
  64330. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  64331. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  64332. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  64333. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  64334. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64335. * * 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
  64336. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64337. * @param name defines the name of the mesh
  64338. * @param options defines the options used to create the mesh
  64339. * @param scene defines the hosting scene
  64340. * @returns the torus knot mesh
  64341. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  64342. */
  64343. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  64344. var torusKnot = new BABYLON.Mesh(name, scene);
  64345. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64346. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  64347. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  64348. vertexData.applyToMesh(torusKnot, options.updatable);
  64349. return torusKnot;
  64350. };
  64351. /**
  64352. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64353. * * 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
  64354. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64355. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64356. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64357. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64358. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64359. * * 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
  64360. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64361. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64362. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64363. * @param name defines the name of the new line system
  64364. * @param options defines the options used to create the line system
  64365. * @param scene defines the hosting scene
  64366. * @returns a new line system mesh
  64367. */
  64368. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64369. var instance = options.instance;
  64370. var lines = options.lines;
  64371. var colors = options.colors;
  64372. if (instance) { // lines update
  64373. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64374. var vertexColor;
  64375. var lineColors;
  64376. if (colors) {
  64377. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64378. }
  64379. var i = 0;
  64380. var c = 0;
  64381. for (var l = 0; l < lines.length; l++) {
  64382. var points = lines[l];
  64383. for (var p = 0; p < points.length; p++) {
  64384. positions[i] = points[p].x;
  64385. positions[i + 1] = points[p].y;
  64386. positions[i + 2] = points[p].z;
  64387. if (colors && vertexColor) {
  64388. lineColors = colors[l];
  64389. vertexColor[c] = lineColors[p].r;
  64390. vertexColor[c + 1] = lineColors[p].g;
  64391. vertexColor[c + 2] = lineColors[p].b;
  64392. vertexColor[c + 3] = lineColors[p].a;
  64393. c += 4;
  64394. }
  64395. i += 3;
  64396. }
  64397. }
  64398. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64399. if (colors && vertexColor) {
  64400. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64401. }
  64402. return instance;
  64403. }
  64404. // line system creation
  64405. var useVertexColor = (colors) ? true : false;
  64406. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64407. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64408. vertexData.applyToMesh(lineSystem, options.updatable);
  64409. return lineSystem;
  64410. };
  64411. /**
  64412. * Creates a line mesh
  64413. * 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
  64414. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64415. * * The parameter `points` is an array successive Vector3
  64416. * * 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
  64417. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64418. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64419. * * When updating an instance, remember that only point positions can change, not the number of points
  64420. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64421. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64422. * @param name defines the name of the new line system
  64423. * @param options defines the options used to create the line system
  64424. * @param scene defines the hosting scene
  64425. * @returns a new line mesh
  64426. */
  64427. MeshBuilder.CreateLines = function (name, options, scene) {
  64428. if (scene === void 0) { scene = null; }
  64429. var colors = (options.colors) ? [options.colors] : null;
  64430. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64431. return lines;
  64432. };
  64433. /**
  64434. * Creates a dashed line mesh
  64435. * * 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
  64436. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64437. * * The parameter `points` is an array successive Vector3
  64438. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64439. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64440. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64441. * * 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
  64442. * * When updating an instance, remember that only point positions can change, not the number of points
  64443. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64444. * @param name defines the name of the mesh
  64445. * @param options defines the options used to create the mesh
  64446. * @param scene defines the hosting scene
  64447. * @returns the dashed line mesh
  64448. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64449. */
  64450. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64451. if (scene === void 0) { scene = null; }
  64452. var points = options.points;
  64453. var instance = options.instance;
  64454. var gapSize = options.gapSize || 1;
  64455. var dashSize = options.dashSize || 3;
  64456. if (instance) { // dashed lines update
  64457. var positionFunction = function (positions) {
  64458. var curvect = BABYLON.Vector3.Zero();
  64459. var nbSeg = positions.length / 6;
  64460. var lg = 0;
  64461. var nb = 0;
  64462. var shft = 0;
  64463. var dashshft = 0;
  64464. var curshft = 0;
  64465. var p = 0;
  64466. var i = 0;
  64467. var j = 0;
  64468. for (i = 0; i < points.length - 1; i++) {
  64469. points[i + 1].subtractToRef(points[i], curvect);
  64470. lg += curvect.length();
  64471. }
  64472. shft = lg / nbSeg;
  64473. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64474. for (i = 0; i < points.length - 1; i++) {
  64475. points[i + 1].subtractToRef(points[i], curvect);
  64476. nb = Math.floor(curvect.length() / shft);
  64477. curvect.normalize();
  64478. j = 0;
  64479. while (j < nb && p < positions.length) {
  64480. curshft = shft * j;
  64481. positions[p] = points[i].x + curshft * curvect.x;
  64482. positions[p + 1] = points[i].y + curshft * curvect.y;
  64483. positions[p + 2] = points[i].z + curshft * curvect.z;
  64484. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64485. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64486. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64487. p += 6;
  64488. j++;
  64489. }
  64490. }
  64491. while (p < positions.length) {
  64492. positions[p] = points[i].x;
  64493. positions[p + 1] = points[i].y;
  64494. positions[p + 2] = points[i].z;
  64495. p += 3;
  64496. }
  64497. };
  64498. instance.updateMeshPositions(positionFunction, false);
  64499. return instance;
  64500. }
  64501. // dashed lines creation
  64502. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64503. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64504. vertexData.applyToMesh(dashedLines, options.updatable);
  64505. dashedLines.dashSize = dashSize;
  64506. dashedLines.gapSize = gapSize;
  64507. return dashedLines;
  64508. };
  64509. /**
  64510. * 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.
  64511. * * 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.
  64512. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64513. * * 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.
  64514. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64515. * * 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
  64516. * * 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
  64517. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64518. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64519. * * 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
  64520. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64521. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64522. * @param name defines the name of the mesh
  64523. * @param options defines the options used to create the mesh
  64524. * @param scene defines the hosting scene
  64525. * @returns the extruded shape mesh
  64526. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64527. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64528. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64529. */
  64530. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64531. if (scene === void 0) { scene = null; }
  64532. var path = options.path;
  64533. var shape = options.shape;
  64534. var scale = options.scale || 1;
  64535. var rotation = options.rotation || 0;
  64536. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64537. var updatable = options.updatable;
  64538. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64539. var instance = options.instance || null;
  64540. var invertUV = options.invertUV || false;
  64541. 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);
  64542. };
  64543. /**
  64544. * Creates an custom extruded shape mesh.
  64545. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64546. * * 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.
  64547. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64548. * * 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
  64549. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64550. * * 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
  64551. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64552. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64553. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64554. * * 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
  64555. * * 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
  64556. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64557. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64558. * * 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
  64559. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64560. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64561. * @param name defines the name of the mesh
  64562. * @param options defines the options used to create the mesh
  64563. * @param scene defines the hosting scene
  64564. * @returns the custom extruded shape mesh
  64565. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64566. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64567. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64568. */
  64569. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64570. var path = options.path;
  64571. var shape = options.shape;
  64572. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64573. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64574. var ribbonCloseArray = options.ribbonCloseArray || false;
  64575. var ribbonClosePath = options.ribbonClosePath || false;
  64576. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64577. var updatable = options.updatable;
  64578. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64579. var instance = options.instance;
  64580. var invertUV = options.invertUV || false;
  64581. 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);
  64582. };
  64583. /**
  64584. * Creates lathe mesh.
  64585. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64586. * * 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
  64587. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64588. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64589. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64590. * * 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
  64591. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64592. * * 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
  64593. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64594. * * 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
  64595. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64596. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64597. * @param name defines the name of the mesh
  64598. * @param options defines the options used to create the mesh
  64599. * @param scene defines the hosting scene
  64600. * @returns the lathe mesh
  64601. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64602. */
  64603. MeshBuilder.CreateLathe = function (name, options, scene) {
  64604. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64605. var closed = (options.closed === undefined) ? true : options.closed;
  64606. var shape = options.shape;
  64607. var radius = options.radius || 1;
  64608. var tessellation = options.tessellation || 64;
  64609. var clip = options.clip || 0;
  64610. var updatable = options.updatable;
  64611. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64612. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64613. var pi2 = Math.PI * 2;
  64614. var paths = new Array();
  64615. var invertUV = options.invertUV || false;
  64616. var i = 0;
  64617. var p = 0;
  64618. var step = pi2 / tessellation * arc;
  64619. var rotated;
  64620. var path = new Array();
  64621. for (i = 0; i <= tessellation - clip; i++) {
  64622. var path = [];
  64623. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64624. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64625. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64626. }
  64627. for (p = 0; p < shape.length; p++) {
  64628. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64629. path.push(rotated);
  64630. }
  64631. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64632. 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));
  64633. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64634. }
  64635. paths.push(path);
  64636. }
  64637. // lathe ribbon
  64638. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64639. return lathe;
  64640. };
  64641. /**
  64642. * Creates a plane mesh
  64643. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64644. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64645. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64646. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64647. * * 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
  64648. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64649. * @param name defines the name of the mesh
  64650. * @param options defines the options used to create the mesh
  64651. * @param scene defines the hosting scene
  64652. * @returns the plane mesh
  64653. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64654. */
  64655. MeshBuilder.CreatePlane = function (name, options, scene) {
  64656. var plane = new BABYLON.Mesh(name, scene);
  64657. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64658. plane._originalBuilderSideOrientation = options.sideOrientation;
  64659. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64660. vertexData.applyToMesh(plane, options.updatable);
  64661. if (options.sourcePlane) {
  64662. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64663. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64664. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64665. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  64666. plane.rotate(vectorProduct, product);
  64667. }
  64668. }
  64669. return plane;
  64670. };
  64671. /**
  64672. * Creates a ground mesh
  64673. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64674. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64675. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64676. * @param name defines the name of the mesh
  64677. * @param options defines the options used to create the mesh
  64678. * @param scene defines the hosting scene
  64679. * @returns the ground mesh
  64680. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64681. */
  64682. MeshBuilder.CreateGround = function (name, options, scene) {
  64683. var ground = new BABYLON.GroundMesh(name, scene);
  64684. ground._setReady(false);
  64685. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64686. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64687. ground._width = options.width || 1;
  64688. ground._height = options.height || 1;
  64689. ground._maxX = ground._width / 2;
  64690. ground._maxZ = ground._height / 2;
  64691. ground._minX = -ground._maxX;
  64692. ground._minZ = -ground._maxZ;
  64693. var vertexData = BABYLON.VertexData.CreateGround(options);
  64694. vertexData.applyToMesh(ground, options.updatable);
  64695. ground._setReady(true);
  64696. return ground;
  64697. };
  64698. /**
  64699. * Creates a tiled ground mesh
  64700. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64701. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64702. * * 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
  64703. * * 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
  64704. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64705. * @param name defines the name of the mesh
  64706. * @param options defines the options used to create the mesh
  64707. * @param scene defines the hosting scene
  64708. * @returns the tiled ground mesh
  64709. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64710. */
  64711. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64712. var tiledGround = new BABYLON.Mesh(name, scene);
  64713. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64714. vertexData.applyToMesh(tiledGround, options.updatable);
  64715. return tiledGround;
  64716. };
  64717. /**
  64718. * Creates a ground mesh from a height map
  64719. * * The parameter `url` sets the URL of the height map image resource.
  64720. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64721. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64722. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64723. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64724. * * 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.
  64725. * * 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).
  64726. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  64727. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64728. * @param name defines the name of the mesh
  64729. * @param url defines the url to the height map
  64730. * @param options defines the options used to create the mesh
  64731. * @param scene defines the hosting scene
  64732. * @returns the ground mesh
  64733. * @see http://doc.babylonjs.com/babylon101/height_map
  64734. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64735. */
  64736. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64737. var width = options.width || 10.0;
  64738. var height = options.height || 10.0;
  64739. var subdivisions = options.subdivisions || 1 | 0;
  64740. var minHeight = options.minHeight || 0.0;
  64741. var maxHeight = options.maxHeight || 1.0;
  64742. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64743. var alphaFilter = options.alphaFilter || 0.0;
  64744. var updatable = options.updatable;
  64745. var onReady = options.onReady;
  64746. var ground = new BABYLON.GroundMesh(name, scene);
  64747. ground._subdivisionsX = subdivisions;
  64748. ground._subdivisionsY = subdivisions;
  64749. ground._width = width;
  64750. ground._height = height;
  64751. ground._maxX = ground._width / 2.0;
  64752. ground._maxZ = ground._height / 2.0;
  64753. ground._minX = -ground._maxX;
  64754. ground._minZ = -ground._maxZ;
  64755. ground._setReady(false);
  64756. var onload = function (img) {
  64757. // Getting height map data
  64758. var canvas = document.createElement("canvas");
  64759. var context = canvas.getContext("2d");
  64760. if (!context) {
  64761. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64762. }
  64763. if (scene.isDisposed) {
  64764. return;
  64765. }
  64766. var bufferWidth = img.width;
  64767. var bufferHeight = img.height;
  64768. canvas.width = bufferWidth;
  64769. canvas.height = bufferHeight;
  64770. context.drawImage(img, 0, 0);
  64771. // Create VertexData from map data
  64772. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64773. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64774. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64775. width: width, height: height,
  64776. subdivisions: subdivisions,
  64777. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64778. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  64779. alphaFilter: alphaFilter
  64780. });
  64781. vertexData.applyToMesh(ground, updatable);
  64782. //execute ready callback, if set
  64783. if (onReady) {
  64784. onReady(ground);
  64785. }
  64786. ground._setReady(true);
  64787. };
  64788. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64789. return ground;
  64790. };
  64791. /**
  64792. * Creates a polygon mesh
  64793. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64794. * * 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
  64795. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64796. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64797. * * 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)
  64798. * * Remember you can only change the shape positions, not their number when updating a polygon
  64799. * @param name defines the name of the mesh
  64800. * @param options defines the options used to create the mesh
  64801. * @param scene defines the hosting scene
  64802. * @returns the polygon mesh
  64803. */
  64804. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64805. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64806. var shape = options.shape;
  64807. var holes = options.holes || [];
  64808. var depth = options.depth || 0;
  64809. var contours = [];
  64810. var hole = [];
  64811. for (var i = 0; i < shape.length; i++) {
  64812. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64813. }
  64814. var epsilon = 0.00000001;
  64815. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64816. contours.pop();
  64817. }
  64818. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64819. for (var hNb = 0; hNb < holes.length; hNb++) {
  64820. hole = [];
  64821. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64822. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64823. }
  64824. polygonTriangulation.addHole(hole);
  64825. }
  64826. var polygon = polygonTriangulation.build(options.updatable, depth);
  64827. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64828. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64829. vertexData.applyToMesh(polygon, options.updatable);
  64830. return polygon;
  64831. };
  64832. ;
  64833. /**
  64834. * Creates an extruded polygon mesh, with depth in the Y direction.
  64835. * * 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)
  64836. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64837. * @param name defines the name of the mesh
  64838. * @param options defines the options used to create the mesh
  64839. * @param scene defines the hosting scene
  64840. * @returns the polygon mesh
  64841. */
  64842. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64843. return MeshBuilder.CreatePolygon(name, options, scene);
  64844. };
  64845. ;
  64846. /**
  64847. * Creates a tube mesh.
  64848. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64849. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64850. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64851. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64852. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64853. * * 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)
  64854. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64855. * * 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
  64856. * * 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
  64857. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64858. * * 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
  64859. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64860. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64861. * @param name defines the name of the mesh
  64862. * @param options defines the options used to create the mesh
  64863. * @param scene defines the hosting scene
  64864. * @returns the tube mesh
  64865. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64866. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64867. */
  64868. MeshBuilder.CreateTube = function (name, options, scene) {
  64869. var path = options.path;
  64870. var instance = options.instance;
  64871. var radius = 1.0;
  64872. if (instance) {
  64873. radius = instance.radius;
  64874. }
  64875. if (options.radius !== undefined) {
  64876. radius = options.radius;
  64877. }
  64878. ;
  64879. var tessellation = options.tessellation || 64 | 0;
  64880. var radiusFunction = options.radiusFunction || null;
  64881. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64882. var invertUV = options.invertUV || false;
  64883. var updatable = options.updatable;
  64884. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64885. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64886. // tube geometry
  64887. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64888. var tangents = path3D.getTangents();
  64889. var normals = path3D.getNormals();
  64890. var distances = path3D.getDistances();
  64891. var pi2 = Math.PI * 2;
  64892. var step = pi2 / tessellation * arc;
  64893. var returnRadius = function () { return radius; };
  64894. var radiusFunctionFinal = radiusFunction || returnRadius;
  64895. var circlePath;
  64896. var rad;
  64897. var normal;
  64898. var rotated;
  64899. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64900. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64901. for (var i = 0; i < path.length; i++) {
  64902. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64903. circlePath = Array(); // current circle array
  64904. normal = normals[i]; // current normal
  64905. for (var t = 0; t < tessellation; t++) {
  64906. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64907. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64908. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64909. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64910. circlePath[t] = rotated;
  64911. }
  64912. circlePaths[index] = circlePath;
  64913. index++;
  64914. }
  64915. // cap
  64916. var capPath = function (nbPoints, pathIndex) {
  64917. var pointCap = Array();
  64918. for (var i = 0; i < nbPoints; i++) {
  64919. pointCap.push(path[pathIndex]);
  64920. }
  64921. return pointCap;
  64922. };
  64923. switch (cap) {
  64924. case BABYLON.Mesh.NO_CAP:
  64925. break;
  64926. case BABYLON.Mesh.CAP_START:
  64927. circlePaths[0] = capPath(tessellation, 0);
  64928. circlePaths[1] = circlePaths[2].slice(0);
  64929. break;
  64930. case BABYLON.Mesh.CAP_END:
  64931. circlePaths[index] = circlePaths[index - 1].slice(0);
  64932. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64933. break;
  64934. case BABYLON.Mesh.CAP_ALL:
  64935. circlePaths[0] = capPath(tessellation, 0);
  64936. circlePaths[1] = circlePaths[2].slice(0);
  64937. circlePaths[index] = circlePaths[index - 1].slice(0);
  64938. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64939. break;
  64940. default:
  64941. break;
  64942. }
  64943. return circlePaths;
  64944. };
  64945. var path3D;
  64946. var pathArray;
  64947. if (instance) { // tube update
  64948. var arc = options.arc || instance.arc;
  64949. path3D = (instance.path3D).update(path);
  64950. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  64951. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  64952. instance.path3D = path3D;
  64953. instance.pathArray = pathArray;
  64954. instance.arc = arc;
  64955. instance.radius = radius;
  64956. return instance;
  64957. }
  64958. // tube creation
  64959. path3D = new BABYLON.Path3D(path);
  64960. var newPathArray = new Array();
  64961. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64962. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  64963. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64964. tube.pathArray = pathArray;
  64965. tube.path3D = path3D;
  64966. tube.tessellation = tessellation;
  64967. tube.cap = cap;
  64968. tube.arc = options.arc;
  64969. tube.radius = radius;
  64970. return tube;
  64971. };
  64972. /**
  64973. * Creates a polyhedron mesh
  64974. * * 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
  64975. * * The parameter `size` (positive float, default 1) sets the polygon size
  64976. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  64977. * * 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`
  64978. * * 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
  64979. * * 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)`)
  64980. * * 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
  64981. * * 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
  64982. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64983. * * 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
  64984. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64985. * @param name defines the name of the mesh
  64986. * @param options defines the options used to create the mesh
  64987. * @param scene defines the hosting scene
  64988. * @returns the polyhedron mesh
  64989. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  64990. */
  64991. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  64992. var polyhedron = new BABYLON.Mesh(name, scene);
  64993. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64994. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  64995. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  64996. vertexData.applyToMesh(polyhedron, options.updatable);
  64997. return polyhedron;
  64998. };
  64999. /**
  65000. * Creates a decal mesh.
  65001. * 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
  65002. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  65003. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  65004. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  65005. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  65006. * @param name defines the name of the mesh
  65007. * @param sourceMesh defines the mesh where the decal must be applied
  65008. * @param options defines the options used to create the mesh
  65009. * @param scene defines the hosting scene
  65010. * @returns the decal mesh
  65011. * @see http://doc.babylonjs.com/how_to/decals
  65012. */
  65013. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  65014. var indices = sourceMesh.getIndices();
  65015. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65016. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65017. var position = options.position || BABYLON.Vector3.Zero();
  65018. var normal = options.normal || BABYLON.Vector3.Up();
  65019. var size = options.size || BABYLON.Vector3.One();
  65020. var angle = options.angle || 0;
  65021. // Getting correct rotation
  65022. if (!normal) {
  65023. var target = new BABYLON.Vector3(0, 0, 1);
  65024. var camera = sourceMesh.getScene().activeCamera;
  65025. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  65026. normal = camera.globalPosition.subtract(cameraWorldTarget);
  65027. }
  65028. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  65029. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  65030. var pitch = Math.atan2(normal.y, len);
  65031. // Matrix
  65032. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  65033. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  65034. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  65035. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  65036. var vertexData = new BABYLON.VertexData();
  65037. vertexData.indices = [];
  65038. vertexData.positions = [];
  65039. vertexData.normals = [];
  65040. vertexData.uvs = [];
  65041. var currentVertexDataIndex = 0;
  65042. var extractDecalVector3 = function (indexId) {
  65043. var result = new BABYLON.PositionNormalVertex();
  65044. if (!indices || !positions || !normals) {
  65045. return result;
  65046. }
  65047. var vertexId = indices[indexId];
  65048. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  65049. // Send vector to decal local world
  65050. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  65051. // Get normal
  65052. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  65053. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  65054. return result;
  65055. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  65056. var clip = function (vertices, axis) {
  65057. if (vertices.length === 0) {
  65058. return vertices;
  65059. }
  65060. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  65061. var clipVertices = function (v0, v1) {
  65062. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  65063. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  65064. };
  65065. var result = new Array();
  65066. for (var index = 0; index < vertices.length; index += 3) {
  65067. var v1Out;
  65068. var v2Out;
  65069. var v3Out;
  65070. var total = 0;
  65071. var nV1 = null;
  65072. var nV2 = null;
  65073. var nV3 = null;
  65074. var nV4 = null;
  65075. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  65076. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  65077. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  65078. v1Out = d1 > 0;
  65079. v2Out = d2 > 0;
  65080. v3Out = d3 > 0;
  65081. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  65082. switch (total) {
  65083. case 0:
  65084. result.push(vertices[index]);
  65085. result.push(vertices[index + 1]);
  65086. result.push(vertices[index + 2]);
  65087. break;
  65088. case 1:
  65089. if (v1Out) {
  65090. nV1 = vertices[index + 1];
  65091. nV2 = vertices[index + 2];
  65092. nV3 = clipVertices(vertices[index], nV1);
  65093. nV4 = clipVertices(vertices[index], nV2);
  65094. }
  65095. if (v2Out) {
  65096. nV1 = vertices[index];
  65097. nV2 = vertices[index + 2];
  65098. nV3 = clipVertices(vertices[index + 1], nV1);
  65099. nV4 = clipVertices(vertices[index + 1], nV2);
  65100. result.push(nV3);
  65101. result.push(nV2.clone());
  65102. result.push(nV1.clone());
  65103. result.push(nV2.clone());
  65104. result.push(nV3.clone());
  65105. result.push(nV4);
  65106. break;
  65107. }
  65108. if (v3Out) {
  65109. nV1 = vertices[index];
  65110. nV2 = vertices[index + 1];
  65111. nV3 = clipVertices(vertices[index + 2], nV1);
  65112. nV4 = clipVertices(vertices[index + 2], nV2);
  65113. }
  65114. if (nV1 && nV2 && nV3 && nV4) {
  65115. result.push(nV1.clone());
  65116. result.push(nV2.clone());
  65117. result.push(nV3);
  65118. result.push(nV4);
  65119. result.push(nV3.clone());
  65120. result.push(nV2.clone());
  65121. }
  65122. break;
  65123. case 2:
  65124. if (!v1Out) {
  65125. nV1 = vertices[index].clone();
  65126. nV2 = clipVertices(nV1, vertices[index + 1]);
  65127. nV3 = clipVertices(nV1, vertices[index + 2]);
  65128. result.push(nV1);
  65129. result.push(nV2);
  65130. result.push(nV3);
  65131. }
  65132. if (!v2Out) {
  65133. nV1 = vertices[index + 1].clone();
  65134. nV2 = clipVertices(nV1, vertices[index + 2]);
  65135. nV3 = clipVertices(nV1, vertices[index]);
  65136. result.push(nV1);
  65137. result.push(nV2);
  65138. result.push(nV3);
  65139. }
  65140. if (!v3Out) {
  65141. nV1 = vertices[index + 2].clone();
  65142. nV2 = clipVertices(nV1, vertices[index]);
  65143. nV3 = clipVertices(nV1, vertices[index + 1]);
  65144. result.push(nV1);
  65145. result.push(nV2);
  65146. result.push(nV3);
  65147. }
  65148. break;
  65149. case 3:
  65150. break;
  65151. }
  65152. }
  65153. return result;
  65154. };
  65155. for (var index = 0; index < indices.length; index += 3) {
  65156. var faceVertices = new Array();
  65157. faceVertices.push(extractDecalVector3(index));
  65158. faceVertices.push(extractDecalVector3(index + 1));
  65159. faceVertices.push(extractDecalVector3(index + 2));
  65160. // Clip
  65161. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  65162. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  65163. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  65164. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  65165. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  65166. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  65167. if (faceVertices.length === 0) {
  65168. continue;
  65169. }
  65170. // Add UVs and get back to world
  65171. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  65172. var vertex = faceVertices[vIndex];
  65173. //TODO check for Int32Array | Uint32Array | Uint16Array
  65174. vertexData.indices.push(currentVertexDataIndex);
  65175. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  65176. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  65177. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  65178. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  65179. currentVertexDataIndex++;
  65180. }
  65181. }
  65182. // Return mesh
  65183. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  65184. vertexData.applyToMesh(decal);
  65185. decal.position = position.clone();
  65186. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  65187. return decal;
  65188. };
  65189. // Privates
  65190. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  65191. // extrusion geometry
  65192. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  65193. var tangents = path3D.getTangents();
  65194. var normals = path3D.getNormals();
  65195. var binormals = path3D.getBinormals();
  65196. var distances = path3D.getDistances();
  65197. var angle = 0;
  65198. var returnScale = function () { return scale !== null ? scale : 1; };
  65199. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  65200. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  65201. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  65202. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65203. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65204. for (var i = 0; i < curve.length; i++) {
  65205. var shapePath = new Array();
  65206. var angleStep = rotate(i, distances[i]);
  65207. var scaleRatio = scl(i, distances[i]);
  65208. for (var p = 0; p < shape.length; p++) {
  65209. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  65210. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  65211. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  65212. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  65213. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  65214. shapePath[p] = rotated;
  65215. }
  65216. shapePaths[index] = shapePath;
  65217. angle += angleStep;
  65218. index++;
  65219. }
  65220. // cap
  65221. var capPath = function (shapePath) {
  65222. var pointCap = Array();
  65223. var barycenter = BABYLON.Vector3.Zero();
  65224. var i;
  65225. for (i = 0; i < shapePath.length; i++) {
  65226. barycenter.addInPlace(shapePath[i]);
  65227. }
  65228. barycenter.scaleInPlace(1.0 / shapePath.length);
  65229. for (i = 0; i < shapePath.length; i++) {
  65230. pointCap.push(barycenter);
  65231. }
  65232. return pointCap;
  65233. };
  65234. switch (cap) {
  65235. case BABYLON.Mesh.NO_CAP:
  65236. break;
  65237. case BABYLON.Mesh.CAP_START:
  65238. shapePaths[0] = capPath(shapePaths[2]);
  65239. shapePaths[1] = shapePaths[2];
  65240. break;
  65241. case BABYLON.Mesh.CAP_END:
  65242. shapePaths[index] = shapePaths[index - 1];
  65243. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65244. break;
  65245. case BABYLON.Mesh.CAP_ALL:
  65246. shapePaths[0] = capPath(shapePaths[2]);
  65247. shapePaths[1] = shapePaths[2];
  65248. shapePaths[index] = shapePaths[index - 1];
  65249. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65250. break;
  65251. default:
  65252. break;
  65253. }
  65254. return shapePaths;
  65255. };
  65256. var path3D;
  65257. var pathArray;
  65258. if (instance) { // instance update
  65259. path3D = (instance.path3D).update(curve);
  65260. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  65261. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  65262. return instance;
  65263. }
  65264. // extruded shape creation
  65265. path3D = new BABYLON.Path3D(curve);
  65266. var newShapePaths = new Array();
  65267. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65268. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  65269. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  65270. extrudedGeneric.pathArray = pathArray;
  65271. extrudedGeneric.path3D = path3D;
  65272. extrudedGeneric.cap = cap;
  65273. return extrudedGeneric;
  65274. };
  65275. return MeshBuilder;
  65276. }());
  65277. BABYLON.MeshBuilder = MeshBuilder;
  65278. })(BABYLON || (BABYLON = {}));
  65279. //# sourceMappingURL=babylon.meshBuilder.js.map
  65280. var BABYLON;
  65281. (function (BABYLON) {
  65282. /**
  65283. * Draco compression (https://google.github.io/draco/)
  65284. *
  65285. * This class wraps the Draco module.
  65286. *
  65287. * **Encoder**
  65288. *
  65289. * The encoder is not currently implemented.
  65290. *
  65291. * **Decoder**
  65292. *
  65293. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  65294. *
  65295. * To update the configuration, use the following code:
  65296. * ```javascript
  65297. * BABYLON.DracoCompression.Configuration = {
  65298. * decoder: {
  65299. * wasmUrl: "<url to the WebAssembly library>",
  65300. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  65301. * fallbackUrl: "<url to the fallback JavaScript library>",
  65302. * }
  65303. * };
  65304. * ```
  65305. *
  65306. * 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.
  65307. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  65308. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  65309. *
  65310. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  65311. * ```javascript
  65312. * var dracoCompression = new BABYLON.DracoCompression();
  65313. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  65314. * [BABYLON.VertexBuffer.PositionKind]: 0
  65315. * });
  65316. * ```
  65317. *
  65318. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  65319. */
  65320. var DracoCompression = /** @class */ (function () {
  65321. /**
  65322. * Constructor
  65323. */
  65324. function DracoCompression() {
  65325. }
  65326. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  65327. /**
  65328. * Returns true if the decoder is available.
  65329. */
  65330. get: function () {
  65331. if (typeof DracoDecoderModule !== "undefined") {
  65332. return true;
  65333. }
  65334. var decoder = DracoCompression.Configuration.decoder;
  65335. if (decoder) {
  65336. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65337. return true;
  65338. }
  65339. if (decoder.fallbackUrl) {
  65340. return true;
  65341. }
  65342. }
  65343. return false;
  65344. },
  65345. enumerable: true,
  65346. configurable: true
  65347. });
  65348. /**
  65349. * Stop all async operations and release resources.
  65350. */
  65351. DracoCompression.prototype.dispose = function () {
  65352. };
  65353. /**
  65354. * Decode Draco compressed mesh data to vertex data.
  65355. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65356. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65357. * @returns A promise that resolves with the decoded vertex data
  65358. */
  65359. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65360. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65361. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65362. var module = wrappedModule.module;
  65363. var vertexData = new BABYLON.VertexData();
  65364. var buffer = new module.DecoderBuffer();
  65365. buffer.Init(dataView, dataView.byteLength);
  65366. var decoder = new module.Decoder();
  65367. var geometry;
  65368. var status;
  65369. try {
  65370. var type = decoder.GetEncodedGeometryType(buffer);
  65371. switch (type) {
  65372. case module.TRIANGULAR_MESH:
  65373. geometry = new module.Mesh();
  65374. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65375. break;
  65376. case module.POINT_CLOUD:
  65377. geometry = new module.PointCloud();
  65378. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65379. break;
  65380. default:
  65381. throw new Error("Invalid geometry type " + type);
  65382. }
  65383. if (!status.ok() || !geometry.ptr) {
  65384. throw new Error(status.error_msg());
  65385. }
  65386. var numPoints = geometry.num_points();
  65387. if (type === module.TRIANGULAR_MESH) {
  65388. var numFaces = geometry.num_faces();
  65389. var faceIndices = new module.DracoInt32Array();
  65390. try {
  65391. var indices = new Uint32Array(numFaces * 3);
  65392. for (var i = 0; i < numFaces; i++) {
  65393. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65394. var offset = i * 3;
  65395. indices[offset + 0] = faceIndices.GetValue(0);
  65396. indices[offset + 1] = faceIndices.GetValue(1);
  65397. indices[offset + 2] = faceIndices.GetValue(2);
  65398. }
  65399. vertexData.indices = indices;
  65400. }
  65401. finally {
  65402. module.destroy(faceIndices);
  65403. }
  65404. }
  65405. for (var kind in attributes) {
  65406. var uniqueId = attributes[kind];
  65407. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65408. var dracoData = new module.DracoFloat32Array();
  65409. try {
  65410. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65411. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65412. for (var i = 0; i < babylonData.length; i++) {
  65413. babylonData[i] = dracoData.GetValue(i);
  65414. }
  65415. vertexData.set(babylonData, kind);
  65416. }
  65417. finally {
  65418. module.destroy(dracoData);
  65419. }
  65420. }
  65421. }
  65422. finally {
  65423. if (geometry) {
  65424. module.destroy(geometry);
  65425. }
  65426. module.destroy(decoder);
  65427. module.destroy(buffer);
  65428. }
  65429. return vertexData;
  65430. });
  65431. };
  65432. DracoCompression._GetDecoderModule = function () {
  65433. if (!DracoCompression._DecoderModulePromise) {
  65434. var promise = null;
  65435. var config_1 = {};
  65436. if (typeof DracoDecoderModule !== "undefined") {
  65437. promise = Promise.resolve();
  65438. }
  65439. else {
  65440. var decoder = DracoCompression.Configuration.decoder;
  65441. if (decoder) {
  65442. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65443. promise = Promise.all([
  65444. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65445. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65446. config_1.wasmBinary = data;
  65447. })
  65448. ]);
  65449. }
  65450. else if (decoder.fallbackUrl) {
  65451. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65452. }
  65453. }
  65454. }
  65455. if (!promise) {
  65456. throw new Error("Draco decoder module is not available");
  65457. }
  65458. DracoCompression._DecoderModulePromise = promise.then(function () {
  65459. return new Promise(function (resolve) {
  65460. config_1.onModuleLoaded = function (decoderModule) {
  65461. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65462. resolve({ module: decoderModule });
  65463. };
  65464. DracoDecoderModule(config_1);
  65465. });
  65466. });
  65467. }
  65468. return DracoCompression._DecoderModulePromise;
  65469. };
  65470. DracoCompression._LoadScriptAsync = function (url) {
  65471. return new Promise(function (resolve, reject) {
  65472. BABYLON.Tools.LoadScript(url, function () {
  65473. resolve();
  65474. }, function (message) {
  65475. reject(new Error(message));
  65476. });
  65477. });
  65478. };
  65479. DracoCompression._LoadFileAsync = function (url) {
  65480. return new Promise(function (resolve, reject) {
  65481. BABYLON.Tools.LoadFile(url, function (data) {
  65482. resolve(data);
  65483. }, undefined, undefined, true, function (request, exception) {
  65484. reject(exception);
  65485. });
  65486. });
  65487. };
  65488. /**
  65489. * The configuration. Defaults to the following urls:
  65490. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65491. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65492. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65493. */
  65494. DracoCompression.Configuration = {
  65495. decoder: {
  65496. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65497. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65498. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65499. }
  65500. };
  65501. return DracoCompression;
  65502. }());
  65503. BABYLON.DracoCompression = DracoCompression;
  65504. })(BABYLON || (BABYLON = {}));
  65505. //# sourceMappingURL=babylon.dracoCompression.js.map
  65506. var BABYLON;
  65507. (function (BABYLON) {
  65508. // Sets the default audio engine to Babylon JS.
  65509. BABYLON.Engine.AudioEngineFactory = function () { return new AudioEngine(); };
  65510. var AudioEngine = /** @class */ (function () {
  65511. function AudioEngine() {
  65512. this._audioContext = null;
  65513. this._audioContextInitialized = false;
  65514. this.canUseWebAudio = false;
  65515. this.WarnedWebAudioUnsupported = false;
  65516. this.unlocked = false;
  65517. this.isMP3supported = false;
  65518. this.isOGGsupported = false;
  65519. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65520. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65521. this.canUseWebAudio = true;
  65522. }
  65523. var audioElem = document.createElement('audio');
  65524. try {
  65525. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65526. this.isMP3supported = true;
  65527. }
  65528. }
  65529. catch (e) {
  65530. // protect error during capability check.
  65531. }
  65532. try {
  65533. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65534. this.isOGGsupported = true;
  65535. }
  65536. }
  65537. catch (e) {
  65538. // protect error during capability check.
  65539. }
  65540. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65541. this._unlockiOSaudio();
  65542. }
  65543. else {
  65544. this.unlocked = true;
  65545. }
  65546. }
  65547. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65548. get: function () {
  65549. if (!this._audioContextInitialized) {
  65550. this._initializeAudioContext();
  65551. }
  65552. return this._audioContext;
  65553. },
  65554. enumerable: true,
  65555. configurable: true
  65556. });
  65557. AudioEngine.prototype._unlockiOSaudio = function () {
  65558. var _this = this;
  65559. var unlockaudio = function () {
  65560. if (!_this.audioContext) {
  65561. return;
  65562. }
  65563. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65564. var source = _this.audioContext.createBufferSource();
  65565. source.buffer = buffer;
  65566. source.connect(_this.audioContext.destination);
  65567. source.start(0);
  65568. setTimeout(function () {
  65569. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65570. _this.unlocked = true;
  65571. window.removeEventListener('touchend', unlockaudio, false);
  65572. if (_this.onAudioUnlocked) {
  65573. _this.onAudioUnlocked();
  65574. }
  65575. }
  65576. }, 0);
  65577. };
  65578. window.addEventListener('touchend', unlockaudio, false);
  65579. };
  65580. AudioEngine.prototype._initializeAudioContext = function () {
  65581. try {
  65582. if (this.canUseWebAudio) {
  65583. this._audioContext = new AudioContext();
  65584. // create a global volume gain node
  65585. this.masterGain = this._audioContext.createGain();
  65586. this.masterGain.gain.value = 1;
  65587. this.masterGain.connect(this._audioContext.destination);
  65588. this._audioContextInitialized = true;
  65589. }
  65590. }
  65591. catch (e) {
  65592. this.canUseWebAudio = false;
  65593. BABYLON.Tools.Error("Web Audio: " + e.message);
  65594. }
  65595. };
  65596. AudioEngine.prototype.dispose = function () {
  65597. if (this.canUseWebAudio && this._audioContextInitialized) {
  65598. if (this._connectedAnalyser && this._audioContext) {
  65599. this._connectedAnalyser.stopDebugCanvas();
  65600. this._connectedAnalyser.dispose();
  65601. this.masterGain.disconnect();
  65602. this.masterGain.connect(this._audioContext.destination);
  65603. this._connectedAnalyser = null;
  65604. }
  65605. this.masterGain.gain.value = 1;
  65606. }
  65607. this.WarnedWebAudioUnsupported = false;
  65608. };
  65609. AudioEngine.prototype.getGlobalVolume = function () {
  65610. if (this.canUseWebAudio && this._audioContextInitialized) {
  65611. return this.masterGain.gain.value;
  65612. }
  65613. else {
  65614. return -1;
  65615. }
  65616. };
  65617. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65618. if (this.canUseWebAudio && this._audioContextInitialized) {
  65619. this.masterGain.gain.value = newVolume;
  65620. }
  65621. };
  65622. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65623. if (this._connectedAnalyser) {
  65624. this._connectedAnalyser.stopDebugCanvas();
  65625. }
  65626. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65627. this._connectedAnalyser = analyser;
  65628. this.masterGain.disconnect();
  65629. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65630. }
  65631. };
  65632. return AudioEngine;
  65633. }());
  65634. BABYLON.AudioEngine = AudioEngine;
  65635. })(BABYLON || (BABYLON = {}));
  65636. //# sourceMappingURL=babylon.audioEngine.js.map
  65637. var BABYLON;
  65638. (function (BABYLON) {
  65639. var Sound = /** @class */ (function () {
  65640. /**
  65641. * Create a sound and attach it to a scene
  65642. * @param name Name of your sound
  65643. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65644. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65645. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65646. */
  65647. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65648. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65649. var _this = this;
  65650. this.autoplay = false;
  65651. this.loop = false;
  65652. this.useCustomAttenuation = false;
  65653. this.spatialSound = false;
  65654. this.refDistance = 1;
  65655. this.rolloffFactor = 1;
  65656. this.maxDistance = 100;
  65657. this.distanceModel = "linear";
  65658. this._panningModel = "equalpower";
  65659. /**
  65660. * Observable event when the current playing sound finishes.
  65661. */
  65662. this.onEndedObservable = new BABYLON.Observable();
  65663. this._playbackRate = 1;
  65664. this._streaming = false;
  65665. this._startTime = 0;
  65666. this._startOffset = 0;
  65667. this._position = BABYLON.Vector3.Zero();
  65668. /** @hidden */
  65669. this._positionInEmitterSpace = false;
  65670. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65671. this._volume = 1;
  65672. this._isReadyToPlay = false;
  65673. this.isPlaying = false;
  65674. this.isPaused = false;
  65675. this._isDirectional = false;
  65676. // Used if you'd like to create a directional sound.
  65677. // If not set, the sound will be omnidirectional
  65678. this._coneInnerAngle = 360;
  65679. this._coneOuterAngle = 360;
  65680. this._coneOuterGain = 0;
  65681. this._isOutputConnected = false;
  65682. this._urlType = "Unknown";
  65683. this.name = name;
  65684. this._scene = scene;
  65685. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  65686. if (!compo) {
  65687. compo = new BABYLON.AudioSceneComponent(scene);
  65688. scene._addComponent(compo);
  65689. }
  65690. this._readyToPlayCallback = readyToPlayCallback;
  65691. // Default custom attenuation function is a linear attenuation
  65692. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65693. if (currentDistance < maxDistance) {
  65694. return currentVolume * (1 - currentDistance / maxDistance);
  65695. }
  65696. else {
  65697. return 0;
  65698. }
  65699. };
  65700. if (options) {
  65701. this.autoplay = options.autoplay || false;
  65702. this.loop = options.loop || false;
  65703. // if volume === 0, we need another way to check this option
  65704. if (options.volume !== undefined) {
  65705. this._volume = options.volume;
  65706. }
  65707. this.spatialSound = options.spatialSound || false;
  65708. this.maxDistance = options.maxDistance || 100;
  65709. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65710. this.rolloffFactor = options.rolloffFactor || 1;
  65711. this.refDistance = options.refDistance || 1;
  65712. this.distanceModel = options.distanceModel || "linear";
  65713. this._playbackRate = options.playbackRate || 1;
  65714. this._streaming = options.streaming || false;
  65715. }
  65716. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65717. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65718. this._soundGain.gain.value = this._volume;
  65719. this._inputAudioNode = this._soundGain;
  65720. this._outputAudioNode = this._soundGain;
  65721. if (this.spatialSound) {
  65722. this._createSpatialParameters();
  65723. }
  65724. this._scene.mainSoundTrack.AddSound(this);
  65725. var validParameter = true;
  65726. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65727. if (urlOrArrayBuffer) {
  65728. try {
  65729. if (typeof (urlOrArrayBuffer) === "string") {
  65730. this._urlType = "String";
  65731. }
  65732. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65733. this._urlType = "ArrayBuffer";
  65734. }
  65735. else if (urlOrArrayBuffer instanceof MediaStream) {
  65736. this._urlType = "MediaStream";
  65737. }
  65738. else if (Array.isArray(urlOrArrayBuffer)) {
  65739. this._urlType = "Array";
  65740. }
  65741. var urls = [];
  65742. var codecSupportedFound = false;
  65743. switch (this._urlType) {
  65744. case "MediaStream":
  65745. this._streaming = true;
  65746. this._isReadyToPlay = true;
  65747. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65748. if (this.autoplay) {
  65749. this.play();
  65750. }
  65751. if (this._readyToPlayCallback) {
  65752. this._readyToPlayCallback();
  65753. }
  65754. break;
  65755. case "ArrayBuffer":
  65756. if (urlOrArrayBuffer.byteLength > 0) {
  65757. codecSupportedFound = true;
  65758. this._soundLoaded(urlOrArrayBuffer);
  65759. }
  65760. break;
  65761. case "String":
  65762. urls.push(urlOrArrayBuffer);
  65763. case "Array":
  65764. if (urls.length === 0)
  65765. urls = urlOrArrayBuffer;
  65766. // If we found a supported format, we load it immediately and stop the loop
  65767. for (var i = 0; i < urls.length; i++) {
  65768. var url = urls[i];
  65769. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65770. codecSupportedFound = true;
  65771. }
  65772. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65773. codecSupportedFound = true;
  65774. }
  65775. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65776. codecSupportedFound = true;
  65777. }
  65778. if (url.indexOf("blob:") !== -1) {
  65779. codecSupportedFound = true;
  65780. }
  65781. if (codecSupportedFound) {
  65782. // Loading sound using XHR2
  65783. if (!this._streaming) {
  65784. this._scene._loadFile(url, function (data) {
  65785. _this._soundLoaded(data);
  65786. }, undefined, true, true, function (exception) {
  65787. if (exception) {
  65788. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65789. }
  65790. BABYLON.Tools.Error("Sound creation aborted.");
  65791. _this._scene.mainSoundTrack.RemoveSound(_this);
  65792. });
  65793. }
  65794. // Streaming sound using HTML5 Audio tag
  65795. else {
  65796. this._htmlAudioElement = new Audio(url);
  65797. this._htmlAudioElement.controls = false;
  65798. this._htmlAudioElement.loop = this.loop;
  65799. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65800. this._htmlAudioElement.preload = "auto";
  65801. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65802. _this._isReadyToPlay = true;
  65803. if (_this.autoplay) {
  65804. _this.play();
  65805. }
  65806. if (_this._readyToPlayCallback) {
  65807. _this._readyToPlayCallback();
  65808. }
  65809. });
  65810. document.body.appendChild(this._htmlAudioElement);
  65811. }
  65812. break;
  65813. }
  65814. }
  65815. break;
  65816. default:
  65817. validParameter = false;
  65818. break;
  65819. }
  65820. if (!validParameter) {
  65821. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65822. }
  65823. else {
  65824. if (!codecSupportedFound) {
  65825. this._isReadyToPlay = true;
  65826. // Simulating a ready to play event to avoid breaking code path
  65827. if (this._readyToPlayCallback) {
  65828. window.setTimeout(function () {
  65829. if (_this._readyToPlayCallback) {
  65830. _this._readyToPlayCallback();
  65831. }
  65832. }, 1000);
  65833. }
  65834. }
  65835. }
  65836. }
  65837. catch (ex) {
  65838. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65839. this._scene.mainSoundTrack.RemoveSound(this);
  65840. }
  65841. }
  65842. }
  65843. else {
  65844. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65845. this._scene.mainSoundTrack.AddSound(this);
  65846. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65847. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65848. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65849. }
  65850. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65851. if (this._readyToPlayCallback) {
  65852. window.setTimeout(function () {
  65853. if (_this._readyToPlayCallback) {
  65854. _this._readyToPlayCallback();
  65855. }
  65856. }, 1000);
  65857. }
  65858. }
  65859. }
  65860. Sound.prototype.dispose = function () {
  65861. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65862. if (this.isPlaying) {
  65863. this.stop();
  65864. }
  65865. this._isReadyToPlay = false;
  65866. if (this.soundTrackId === -1) {
  65867. this._scene.mainSoundTrack.RemoveSound(this);
  65868. }
  65869. else if (this._scene.soundTracks) {
  65870. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65871. }
  65872. if (this._soundGain) {
  65873. this._soundGain.disconnect();
  65874. this._soundGain = null;
  65875. }
  65876. if (this._soundPanner) {
  65877. this._soundPanner.disconnect();
  65878. this._soundPanner = null;
  65879. }
  65880. if (this._soundSource) {
  65881. this._soundSource.disconnect();
  65882. this._soundSource = null;
  65883. }
  65884. this._audioBuffer = null;
  65885. if (this._htmlAudioElement) {
  65886. this._htmlAudioElement.pause();
  65887. this._htmlAudioElement.src = "";
  65888. document.body.removeChild(this._htmlAudioElement);
  65889. }
  65890. if (this._streamingSource) {
  65891. this._streamingSource.disconnect();
  65892. }
  65893. if (this._connectedMesh && this._registerFunc) {
  65894. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65895. this._connectedMesh = null;
  65896. }
  65897. }
  65898. };
  65899. Sound.prototype.isReady = function () {
  65900. return this._isReadyToPlay;
  65901. };
  65902. Sound.prototype._soundLoaded = function (audioData) {
  65903. var _this = this;
  65904. if (!BABYLON.Engine.audioEngine.audioContext) {
  65905. return;
  65906. }
  65907. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65908. _this._audioBuffer = buffer;
  65909. _this._isReadyToPlay = true;
  65910. if (_this.autoplay) {
  65911. _this.play();
  65912. }
  65913. if (_this._readyToPlayCallback) {
  65914. _this._readyToPlayCallback();
  65915. }
  65916. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65917. };
  65918. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65919. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65920. this._audioBuffer = audioBuffer;
  65921. this._isReadyToPlay = true;
  65922. }
  65923. };
  65924. Sound.prototype.updateOptions = function (options) {
  65925. if (options) {
  65926. this.loop = options.loop || this.loop;
  65927. this.maxDistance = options.maxDistance || this.maxDistance;
  65928. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65929. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65930. this.refDistance = options.refDistance || this.refDistance;
  65931. this.distanceModel = options.distanceModel || this.distanceModel;
  65932. this._playbackRate = options.playbackRate || this._playbackRate;
  65933. this._updateSpatialParameters();
  65934. if (this.isPlaying) {
  65935. if (this._streaming && this._htmlAudioElement) {
  65936. this._htmlAudioElement.playbackRate = this._playbackRate;
  65937. }
  65938. else {
  65939. if (this._soundSource) {
  65940. this._soundSource.playbackRate.value = this._playbackRate;
  65941. }
  65942. }
  65943. }
  65944. }
  65945. };
  65946. Sound.prototype._createSpatialParameters = function () {
  65947. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65948. if (this._scene.headphone) {
  65949. this._panningModel = "HRTF";
  65950. }
  65951. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  65952. this._updateSpatialParameters();
  65953. this._soundPanner.connect(this._outputAudioNode);
  65954. this._inputAudioNode = this._soundPanner;
  65955. }
  65956. };
  65957. Sound.prototype._updateSpatialParameters = function () {
  65958. if (this.spatialSound && this._soundPanner) {
  65959. if (this.useCustomAttenuation) {
  65960. // Tricks to disable in a way embedded Web Audio attenuation
  65961. this._soundPanner.distanceModel = "linear";
  65962. this._soundPanner.maxDistance = Number.MAX_VALUE;
  65963. this._soundPanner.refDistance = 1;
  65964. this._soundPanner.rolloffFactor = 1;
  65965. this._soundPanner.panningModel = this._panningModel;
  65966. }
  65967. else {
  65968. this._soundPanner.distanceModel = this.distanceModel;
  65969. this._soundPanner.maxDistance = this.maxDistance;
  65970. this._soundPanner.refDistance = this.refDistance;
  65971. this._soundPanner.rolloffFactor = this.rolloffFactor;
  65972. this._soundPanner.panningModel = this._panningModel;
  65973. }
  65974. }
  65975. };
  65976. Sound.prototype.switchPanningModelToHRTF = function () {
  65977. this._panningModel = "HRTF";
  65978. this._switchPanningModel();
  65979. };
  65980. Sound.prototype.switchPanningModelToEqualPower = function () {
  65981. this._panningModel = "equalpower";
  65982. this._switchPanningModel();
  65983. };
  65984. Sound.prototype._switchPanningModel = function () {
  65985. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65986. this._soundPanner.panningModel = this._panningModel;
  65987. }
  65988. };
  65989. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  65990. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65991. if (this._isOutputConnected) {
  65992. this._outputAudioNode.disconnect();
  65993. }
  65994. this._outputAudioNode.connect(soundTrackAudioNode);
  65995. this._isOutputConnected = true;
  65996. }
  65997. };
  65998. /**
  65999. * Transform this sound into a directional source
  66000. * @param coneInnerAngle Size of the inner cone in degree
  66001. * @param coneOuterAngle Size of the outer cone in degree
  66002. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  66003. */
  66004. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  66005. if (coneOuterAngle < coneInnerAngle) {
  66006. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  66007. return;
  66008. }
  66009. this._coneInnerAngle = coneInnerAngle;
  66010. this._coneOuterAngle = coneOuterAngle;
  66011. this._coneOuterGain = coneOuterGain;
  66012. this._isDirectional = true;
  66013. if (this.isPlaying && this.loop) {
  66014. this.stop();
  66015. this.play();
  66016. }
  66017. };
  66018. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  66019. /**
  66020. * Gets or sets the inner angle for the directional cone.
  66021. */
  66022. get: function () {
  66023. return this._coneInnerAngle;
  66024. },
  66025. /**
  66026. * Gets or sets the inner angle for the directional cone.
  66027. */
  66028. set: function (value) {
  66029. if (value != this._coneInnerAngle) {
  66030. if (this._coneOuterAngle < value) {
  66031. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66032. return;
  66033. }
  66034. this._coneInnerAngle = value;
  66035. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66036. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66037. }
  66038. }
  66039. },
  66040. enumerable: true,
  66041. configurable: true
  66042. });
  66043. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  66044. /**
  66045. * Gets or sets the outer angle for the directional cone.
  66046. */
  66047. get: function () {
  66048. return this._coneOuterAngle;
  66049. },
  66050. /**
  66051. * Gets or sets the outer angle for the directional cone.
  66052. */
  66053. set: function (value) {
  66054. if (value != this._coneOuterAngle) {
  66055. if (value < this._coneInnerAngle) {
  66056. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66057. return;
  66058. }
  66059. this._coneOuterAngle = value;
  66060. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66061. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66062. }
  66063. }
  66064. },
  66065. enumerable: true,
  66066. configurable: true
  66067. });
  66068. Sound.prototype.setPosition = function (newPosition) {
  66069. this._position = newPosition;
  66070. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66071. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66072. }
  66073. };
  66074. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  66075. this._localDirection = newLocalDirection;
  66076. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  66077. this._updateDirection();
  66078. }
  66079. };
  66080. Sound.prototype._updateDirection = function () {
  66081. if (!this._connectedMesh || !this._soundPanner) {
  66082. return;
  66083. }
  66084. var mat = this._connectedMesh.getWorldMatrix();
  66085. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  66086. direction.normalize();
  66087. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  66088. };
  66089. Sound.prototype.updateDistanceFromListener = function () {
  66090. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  66091. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  66092. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  66093. }
  66094. };
  66095. Sound.prototype.setAttenuationFunction = function (callback) {
  66096. this._customAttenuationFunction = callback;
  66097. };
  66098. /**
  66099. * Play the sound
  66100. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  66101. * @param offset (optional) Start the sound setting it at a specific time
  66102. */
  66103. Sound.prototype.play = function (time, offset) {
  66104. var _this = this;
  66105. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  66106. try {
  66107. if (this._startOffset < 0) {
  66108. time = -this._startOffset;
  66109. this._startOffset = 0;
  66110. }
  66111. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66112. if (!this._soundSource || !this._streamingSource) {
  66113. if (this.spatialSound && this._soundPanner) {
  66114. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66115. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66116. }
  66117. if (this._isDirectional) {
  66118. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66119. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66120. this._soundPanner.coneOuterGain = this._coneOuterGain;
  66121. if (this._connectedMesh) {
  66122. this._updateDirection();
  66123. }
  66124. else {
  66125. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  66126. }
  66127. }
  66128. }
  66129. }
  66130. if (this._streaming) {
  66131. if (!this._streamingSource) {
  66132. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  66133. this._htmlAudioElement.onended = function () { _this._onended(); };
  66134. this._htmlAudioElement.playbackRate = this._playbackRate;
  66135. }
  66136. this._streamingSource.disconnect();
  66137. this._streamingSource.connect(this._inputAudioNode);
  66138. if (this._htmlAudioElement) {
  66139. this._htmlAudioElement.play();
  66140. }
  66141. }
  66142. else {
  66143. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  66144. this._soundSource.buffer = this._audioBuffer;
  66145. this._soundSource.connect(this._inputAudioNode);
  66146. this._soundSource.loop = this.loop;
  66147. this._soundSource.playbackRate.value = this._playbackRate;
  66148. this._soundSource.onended = function () { _this._onended(); };
  66149. if (this._soundSource.buffer) {
  66150. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  66151. }
  66152. }
  66153. this._startTime = startTime;
  66154. this.isPlaying = true;
  66155. this.isPaused = false;
  66156. }
  66157. catch (ex) {
  66158. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  66159. }
  66160. }
  66161. };
  66162. Sound.prototype._onended = function () {
  66163. this.isPlaying = false;
  66164. if (this.onended) {
  66165. this.onended();
  66166. }
  66167. this.onEndedObservable.notifyObservers(this);
  66168. };
  66169. /**
  66170. * Stop the sound
  66171. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  66172. */
  66173. Sound.prototype.stop = function (time) {
  66174. if (this.isPlaying) {
  66175. if (this._streaming) {
  66176. if (this._htmlAudioElement) {
  66177. this._htmlAudioElement.pause();
  66178. // Test needed for Firefox or it will generate an Invalid State Error
  66179. if (this._htmlAudioElement.currentTime > 0) {
  66180. this._htmlAudioElement.currentTime = 0;
  66181. }
  66182. }
  66183. else {
  66184. this._streamingSource.disconnect();
  66185. }
  66186. }
  66187. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  66188. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66189. this._soundSource.stop(stopTime);
  66190. this._soundSource.onended = function () { };
  66191. if (!this.isPaused) {
  66192. this._startOffset = 0;
  66193. }
  66194. }
  66195. this.isPlaying = false;
  66196. }
  66197. };
  66198. Sound.prototype.pause = function () {
  66199. if (this.isPlaying) {
  66200. this.isPaused = true;
  66201. if (this._streaming) {
  66202. if (this._htmlAudioElement) {
  66203. this._htmlAudioElement.pause();
  66204. }
  66205. else {
  66206. this._streamingSource.disconnect();
  66207. }
  66208. }
  66209. else if (BABYLON.Engine.audioEngine.audioContext) {
  66210. this.stop(0);
  66211. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  66212. }
  66213. }
  66214. };
  66215. Sound.prototype.setVolume = function (newVolume, time) {
  66216. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  66217. if (time && BABYLON.Engine.audioEngine.audioContext) {
  66218. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  66219. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  66220. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  66221. }
  66222. else {
  66223. this._soundGain.gain.value = newVolume;
  66224. }
  66225. }
  66226. this._volume = newVolume;
  66227. };
  66228. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  66229. this._playbackRate = newPlaybackRate;
  66230. if (this.isPlaying) {
  66231. if (this._streaming && this._htmlAudioElement) {
  66232. this._htmlAudioElement.playbackRate = this._playbackRate;
  66233. }
  66234. else if (this._soundSource) {
  66235. this._soundSource.playbackRate.value = this._playbackRate;
  66236. }
  66237. }
  66238. };
  66239. Sound.prototype.getVolume = function () {
  66240. return this._volume;
  66241. };
  66242. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  66243. var _this = this;
  66244. if (this._connectedMesh && this._registerFunc) {
  66245. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66246. this._registerFunc = null;
  66247. }
  66248. this._connectedMesh = meshToConnectTo;
  66249. if (!this.spatialSound) {
  66250. this.spatialSound = true;
  66251. this._createSpatialParameters();
  66252. if (this.isPlaying && this.loop) {
  66253. this.stop();
  66254. this.play();
  66255. }
  66256. }
  66257. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  66258. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  66259. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  66260. };
  66261. Sound.prototype.detachFromMesh = function () {
  66262. if (this._connectedMesh && this._registerFunc) {
  66263. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66264. this._registerFunc = null;
  66265. this._connectedMesh = null;
  66266. }
  66267. };
  66268. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  66269. if (!node.getBoundingInfo) {
  66270. return;
  66271. }
  66272. var mesh = node;
  66273. if (this._positionInEmitterSpace) {
  66274. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  66275. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  66276. }
  66277. else {
  66278. var boundingInfo = mesh.getBoundingInfo();
  66279. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  66280. }
  66281. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  66282. this._updateDirection();
  66283. }
  66284. };
  66285. Sound.prototype.clone = function () {
  66286. var _this = this;
  66287. if (!this._streaming) {
  66288. var setBufferAndRun = function () {
  66289. if (_this._isReadyToPlay) {
  66290. clonedSound._audioBuffer = _this.getAudioBuffer();
  66291. clonedSound._isReadyToPlay = true;
  66292. if (clonedSound.autoplay) {
  66293. clonedSound.play();
  66294. }
  66295. }
  66296. else {
  66297. window.setTimeout(setBufferAndRun, 300);
  66298. }
  66299. };
  66300. var currentOptions = {
  66301. autoplay: this.autoplay, loop: this.loop,
  66302. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  66303. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  66304. refDistance: this.refDistance, distanceModel: this.distanceModel
  66305. };
  66306. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  66307. if (this.useCustomAttenuation) {
  66308. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  66309. }
  66310. clonedSound.setPosition(this._position);
  66311. clonedSound.setPlaybackRate(this._playbackRate);
  66312. setBufferAndRun();
  66313. return clonedSound;
  66314. }
  66315. // Can't clone a streaming sound
  66316. else {
  66317. return null;
  66318. }
  66319. };
  66320. Sound.prototype.getAudioBuffer = function () {
  66321. return this._audioBuffer;
  66322. };
  66323. Sound.prototype.serialize = function () {
  66324. var serializationObject = {
  66325. name: this.name,
  66326. url: this.name,
  66327. autoplay: this.autoplay,
  66328. loop: this.loop,
  66329. volume: this._volume,
  66330. spatialSound: this.spatialSound,
  66331. maxDistance: this.maxDistance,
  66332. rolloffFactor: this.rolloffFactor,
  66333. refDistance: this.refDistance,
  66334. distanceModel: this.distanceModel,
  66335. playbackRate: this._playbackRate,
  66336. panningModel: this._panningModel,
  66337. soundTrackId: this.soundTrackId
  66338. };
  66339. if (this.spatialSound) {
  66340. if (this._connectedMesh)
  66341. serializationObject.connectedMeshId = this._connectedMesh.id;
  66342. serializationObject.position = this._position.asArray();
  66343. serializationObject.refDistance = this.refDistance;
  66344. serializationObject.distanceModel = this.distanceModel;
  66345. serializationObject.isDirectional = this._isDirectional;
  66346. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  66347. serializationObject.coneInnerAngle = this._coneInnerAngle;
  66348. serializationObject.coneOuterAngle = this._coneOuterAngle;
  66349. serializationObject.coneOuterGain = this._coneOuterGain;
  66350. }
  66351. return serializationObject;
  66352. };
  66353. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  66354. var soundName = parsedSound.name;
  66355. var soundUrl;
  66356. if (parsedSound.url) {
  66357. soundUrl = rootUrl + parsedSound.url;
  66358. }
  66359. else {
  66360. soundUrl = rootUrl + soundName;
  66361. }
  66362. var options = {
  66363. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66364. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66365. rolloffFactor: parsedSound.rolloffFactor,
  66366. refDistance: parsedSound.refDistance,
  66367. distanceModel: parsedSound.distanceModel,
  66368. playbackRate: parsedSound.playbackRate
  66369. };
  66370. var newSound;
  66371. if (!sourceSound) {
  66372. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66373. scene._addPendingData(newSound);
  66374. }
  66375. else {
  66376. var setBufferAndRun = function () {
  66377. if (sourceSound._isReadyToPlay) {
  66378. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66379. newSound._isReadyToPlay = true;
  66380. if (newSound.autoplay) {
  66381. newSound.play();
  66382. }
  66383. }
  66384. else {
  66385. window.setTimeout(setBufferAndRun, 300);
  66386. }
  66387. };
  66388. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66389. setBufferAndRun();
  66390. }
  66391. if (parsedSound.position) {
  66392. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66393. newSound.setPosition(soundPosition);
  66394. }
  66395. if (parsedSound.isDirectional) {
  66396. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66397. if (parsedSound.localDirectionToMesh) {
  66398. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66399. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66400. }
  66401. }
  66402. if (parsedSound.connectedMeshId) {
  66403. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66404. if (connectedMesh) {
  66405. newSound.attachToMesh(connectedMesh);
  66406. }
  66407. }
  66408. return newSound;
  66409. };
  66410. return Sound;
  66411. }());
  66412. BABYLON.Sound = Sound;
  66413. })(BABYLON || (BABYLON = {}));
  66414. //# sourceMappingURL=babylon.sound.js.map
  66415. var BABYLON;
  66416. (function (BABYLON) {
  66417. var SoundTrack = /** @class */ (function () {
  66418. function SoundTrack(scene, options) {
  66419. this.id = -1;
  66420. this._isMainTrack = false;
  66421. this._isInitialized = false;
  66422. this._scene = scene;
  66423. this.soundCollection = new Array();
  66424. this._options = options;
  66425. if (!this._isMainTrack && this._scene.soundTracks) {
  66426. this._scene.soundTracks.push(this);
  66427. this.id = this._scene.soundTracks.length - 1;
  66428. }
  66429. }
  66430. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66431. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66432. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66433. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66434. if (this._options) {
  66435. if (this._options.volume) {
  66436. this._outputAudioNode.gain.value = this._options.volume;
  66437. }
  66438. if (this._options.mainTrack) {
  66439. this._isMainTrack = this._options.mainTrack;
  66440. }
  66441. }
  66442. this._isInitialized = true;
  66443. }
  66444. };
  66445. SoundTrack.prototype.dispose = function () {
  66446. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66447. if (this._connectedAnalyser) {
  66448. this._connectedAnalyser.stopDebugCanvas();
  66449. }
  66450. while (this.soundCollection.length) {
  66451. this.soundCollection[0].dispose();
  66452. }
  66453. if (this._outputAudioNode) {
  66454. this._outputAudioNode.disconnect();
  66455. }
  66456. this._outputAudioNode = null;
  66457. }
  66458. };
  66459. SoundTrack.prototype.AddSound = function (sound) {
  66460. if (!this._isInitialized) {
  66461. this._initializeSoundTrackAudioGraph();
  66462. }
  66463. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66464. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66465. }
  66466. if (sound.soundTrackId) {
  66467. if (sound.soundTrackId === -1) {
  66468. this._scene.mainSoundTrack.RemoveSound(sound);
  66469. }
  66470. else if (this._scene.soundTracks) {
  66471. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66472. }
  66473. }
  66474. this.soundCollection.push(sound);
  66475. sound.soundTrackId = this.id;
  66476. };
  66477. SoundTrack.prototype.RemoveSound = function (sound) {
  66478. var index = this.soundCollection.indexOf(sound);
  66479. if (index !== -1) {
  66480. this.soundCollection.splice(index, 1);
  66481. }
  66482. };
  66483. SoundTrack.prototype.setVolume = function (newVolume) {
  66484. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66485. this._outputAudioNode.gain.value = newVolume;
  66486. }
  66487. };
  66488. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66489. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66490. for (var i = 0; i < this.soundCollection.length; i++) {
  66491. this.soundCollection[i].switchPanningModelToHRTF();
  66492. }
  66493. }
  66494. };
  66495. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66496. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66497. for (var i = 0; i < this.soundCollection.length; i++) {
  66498. this.soundCollection[i].switchPanningModelToEqualPower();
  66499. }
  66500. }
  66501. };
  66502. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66503. if (this._connectedAnalyser) {
  66504. this._connectedAnalyser.stopDebugCanvas();
  66505. }
  66506. this._connectedAnalyser = analyser;
  66507. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66508. this._outputAudioNode.disconnect();
  66509. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66510. }
  66511. };
  66512. return SoundTrack;
  66513. }());
  66514. BABYLON.SoundTrack = SoundTrack;
  66515. })(BABYLON || (BABYLON = {}));
  66516. //# sourceMappingURL=babylon.soundtrack.js.map
  66517. var BABYLON;
  66518. (function (BABYLON) {
  66519. /**
  66520. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66521. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66522. */
  66523. var Analyser = /** @class */ (function () {
  66524. /**
  66525. * Creates a new analyser
  66526. * @param scene defines hosting scene
  66527. */
  66528. function Analyser(scene) {
  66529. /**
  66530. * Gets or sets the smoothing
  66531. * @ignorenaming
  66532. */
  66533. this.SMOOTHING = 0.75;
  66534. /**
  66535. * Gets or sets the FFT table size
  66536. * @ignorenaming
  66537. */
  66538. this.FFT_SIZE = 512;
  66539. /**
  66540. * Gets or sets the bar graph amplitude
  66541. * @ignorenaming
  66542. */
  66543. this.BARGRAPHAMPLITUDE = 256;
  66544. /**
  66545. * Gets or sets the position of the debug canvas
  66546. * @ignorenaming
  66547. */
  66548. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66549. /**
  66550. * Gets or sets the debug canvas size
  66551. * @ignorenaming
  66552. */
  66553. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66554. this._scene = scene;
  66555. this._audioEngine = BABYLON.Engine.audioEngine;
  66556. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66557. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66558. this._webAudioAnalyser.minDecibels = -140;
  66559. this._webAudioAnalyser.maxDecibels = 0;
  66560. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66561. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66562. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66563. }
  66564. }
  66565. /**
  66566. * Get the number of data values you will have to play with for the visualization
  66567. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66568. * @returns a number
  66569. */
  66570. Analyser.prototype.getFrequencyBinCount = function () {
  66571. if (this._audioEngine.canUseWebAudio) {
  66572. return this._webAudioAnalyser.frequencyBinCount;
  66573. }
  66574. else {
  66575. return 0;
  66576. }
  66577. };
  66578. /**
  66579. * Gets the current frequency data as a byte array
  66580. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66581. * @returns a Uint8Array
  66582. */
  66583. Analyser.prototype.getByteFrequencyData = function () {
  66584. if (this._audioEngine.canUseWebAudio) {
  66585. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66586. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66587. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66588. }
  66589. return this._byteFreqs;
  66590. };
  66591. /**
  66592. * Gets the current waveform as a byte array
  66593. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66594. * @returns a Uint8Array
  66595. */
  66596. Analyser.prototype.getByteTimeDomainData = function () {
  66597. if (this._audioEngine.canUseWebAudio) {
  66598. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66599. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66600. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66601. }
  66602. return this._byteTime;
  66603. };
  66604. /**
  66605. * Gets the current frequency data as a float array
  66606. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66607. * @returns a Float32Array
  66608. */
  66609. Analyser.prototype.getFloatFrequencyData = function () {
  66610. if (this._audioEngine.canUseWebAudio) {
  66611. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66612. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66613. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66614. }
  66615. return this._floatFreqs;
  66616. };
  66617. /**
  66618. * Renders the debug canvas
  66619. */
  66620. Analyser.prototype.drawDebugCanvas = function () {
  66621. var _this = this;
  66622. if (this._audioEngine.canUseWebAudio) {
  66623. if (!this._debugCanvas) {
  66624. this._debugCanvas = document.createElement("canvas");
  66625. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66626. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66627. this._debugCanvas.style.position = "absolute";
  66628. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66629. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66630. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66631. document.body.appendChild(this._debugCanvas);
  66632. this._registerFunc = function () {
  66633. _this.drawDebugCanvas();
  66634. };
  66635. this._scene.registerBeforeRender(this._registerFunc);
  66636. }
  66637. if (this._registerFunc && this._debugCanvasContext) {
  66638. var workingArray = this.getByteFrequencyData();
  66639. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66640. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66641. // Draw the frequency domain chart.
  66642. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66643. var value = workingArray[i];
  66644. var percent = value / this.BARGRAPHAMPLITUDE;
  66645. var height = this.DEBUGCANVASSIZE.height * percent;
  66646. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66647. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66648. var hue = i / this.getFrequencyBinCount() * 360;
  66649. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66650. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66651. }
  66652. }
  66653. }
  66654. };
  66655. /**
  66656. * Stops rendering the debug canvas and removes it
  66657. */
  66658. Analyser.prototype.stopDebugCanvas = function () {
  66659. if (this._debugCanvas) {
  66660. if (this._registerFunc) {
  66661. this._scene.unregisterBeforeRender(this._registerFunc);
  66662. this._registerFunc = null;
  66663. }
  66664. document.body.removeChild(this._debugCanvas);
  66665. this._debugCanvas = null;
  66666. this._debugCanvasContext = null;
  66667. }
  66668. };
  66669. /**
  66670. * Connects two audio nodes
  66671. * @param inputAudioNode defines first node to connect
  66672. * @param outputAudioNode defines second node to connect
  66673. */
  66674. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66675. if (this._audioEngine.canUseWebAudio) {
  66676. inputAudioNode.connect(this._webAudioAnalyser);
  66677. this._webAudioAnalyser.connect(outputAudioNode);
  66678. }
  66679. };
  66680. /**
  66681. * Releases all associated resources
  66682. */
  66683. Analyser.prototype.dispose = function () {
  66684. if (this._audioEngine.canUseWebAudio) {
  66685. this._webAudioAnalyser.disconnect();
  66686. }
  66687. };
  66688. return Analyser;
  66689. }());
  66690. BABYLON.Analyser = Analyser;
  66691. })(BABYLON || (BABYLON = {}));
  66692. //# sourceMappingURL=babylon.analyser.js.map
  66693. var BABYLON;
  66694. (function (BABYLON) {
  66695. /**
  66696. * Wraps one or more Sound objects and selects one with random weight for playback.
  66697. */
  66698. var WeightedSound = /** @class */ (function () {
  66699. /**
  66700. * Creates a new WeightedSound from the list of sounds given.
  66701. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66702. * @param sounds Array of Sounds that will be selected from.
  66703. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66704. */
  66705. function WeightedSound(loop, sounds, weights) {
  66706. var _this = this;
  66707. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66708. this.loop = false;
  66709. this._coneInnerAngle = 360;
  66710. this._coneOuterAngle = 360;
  66711. this._volume = 1;
  66712. /** A Sound is currently playing. */
  66713. this.isPlaying = false;
  66714. /** A Sound is currently paused. */
  66715. this.isPaused = false;
  66716. this._sounds = [];
  66717. this._weights = [];
  66718. if (sounds.length !== weights.length) {
  66719. throw new Error('Sounds length does not equal weights length');
  66720. }
  66721. this.loop = loop;
  66722. this._weights = weights;
  66723. // Normalize the weights
  66724. var weightSum = 0;
  66725. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66726. var weight = weights_1[_i];
  66727. weightSum += weight;
  66728. }
  66729. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66730. for (var i = 0; i < this._weights.length; i++) {
  66731. this._weights[i] *= invWeightSum;
  66732. }
  66733. this._sounds = sounds;
  66734. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66735. var sound = _b[_a];
  66736. sound.onEndedObservable.add(function () { _this._onended(); });
  66737. }
  66738. }
  66739. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66740. /**
  66741. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66742. */
  66743. get: function () {
  66744. return this._coneInnerAngle;
  66745. },
  66746. /**
  66747. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66748. */
  66749. set: function (value) {
  66750. if (value !== this._coneInnerAngle) {
  66751. if (this._coneOuterAngle < value) {
  66752. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66753. return;
  66754. }
  66755. this._coneInnerAngle = value;
  66756. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66757. var sound = _a[_i];
  66758. sound.directionalConeInnerAngle = value;
  66759. }
  66760. }
  66761. },
  66762. enumerable: true,
  66763. configurable: true
  66764. });
  66765. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66766. /**
  66767. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66768. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66769. */
  66770. get: function () {
  66771. return this._coneOuterAngle;
  66772. },
  66773. /**
  66774. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66775. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66776. */
  66777. set: function (value) {
  66778. if (value !== this._coneOuterAngle) {
  66779. if (value < this._coneInnerAngle) {
  66780. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66781. return;
  66782. }
  66783. this._coneOuterAngle = value;
  66784. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66785. var sound = _a[_i];
  66786. sound.directionalConeOuterAngle = value;
  66787. }
  66788. }
  66789. },
  66790. enumerable: true,
  66791. configurable: true
  66792. });
  66793. Object.defineProperty(WeightedSound.prototype, "volume", {
  66794. /**
  66795. * Playback volume.
  66796. */
  66797. get: function () {
  66798. return this._volume;
  66799. },
  66800. /**
  66801. * Playback volume.
  66802. */
  66803. set: function (value) {
  66804. if (value !== this._volume) {
  66805. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66806. var sound = _a[_i];
  66807. sound.setVolume(value);
  66808. }
  66809. }
  66810. },
  66811. enumerable: true,
  66812. configurable: true
  66813. });
  66814. WeightedSound.prototype._onended = function () {
  66815. if (this._currentIndex !== undefined) {
  66816. this._sounds[this._currentIndex].autoplay = false;
  66817. }
  66818. if (this.loop && this.isPlaying) {
  66819. this.play();
  66820. }
  66821. else {
  66822. this.isPlaying = false;
  66823. }
  66824. };
  66825. /**
  66826. * Suspend playback
  66827. */
  66828. WeightedSound.prototype.pause = function () {
  66829. this.isPaused = true;
  66830. if (this._currentIndex !== undefined) {
  66831. this._sounds[this._currentIndex].pause();
  66832. }
  66833. };
  66834. /**
  66835. * Stop playback
  66836. */
  66837. WeightedSound.prototype.stop = function () {
  66838. this.isPlaying = false;
  66839. if (this._currentIndex !== undefined) {
  66840. this._sounds[this._currentIndex].stop();
  66841. }
  66842. };
  66843. /**
  66844. * Start playback.
  66845. * @param startOffset Position the clip head at a specific time in seconds.
  66846. */
  66847. WeightedSound.prototype.play = function (startOffset) {
  66848. if (!this.isPaused) {
  66849. this.stop();
  66850. var randomValue = Math.random();
  66851. var total = 0;
  66852. for (var i = 0; i < this._weights.length; i++) {
  66853. total += this._weights[i];
  66854. if (randomValue <= total) {
  66855. this._currentIndex = i;
  66856. break;
  66857. }
  66858. }
  66859. }
  66860. var sound = this._sounds[this._currentIndex];
  66861. if (sound.isReady()) {
  66862. sound.play(0, this.isPaused ? undefined : startOffset);
  66863. }
  66864. else {
  66865. sound.autoplay = true;
  66866. }
  66867. this.isPlaying = true;
  66868. this.isPaused = false;
  66869. };
  66870. return WeightedSound;
  66871. }());
  66872. BABYLON.WeightedSound = WeightedSound;
  66873. })(BABYLON || (BABYLON = {}));
  66874. //# sourceMappingURL=babylon.weightedsound.js.map
  66875. var BABYLON;
  66876. (function (BABYLON) {
  66877. // Adds the parser to the scene parsers.
  66878. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  66879. // TODO: add sound
  66880. var loadedSounds = [];
  66881. var loadedSound;
  66882. container.sounds = container.sounds || [];
  66883. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66884. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66885. var parsedSound = parsedData.sounds[index];
  66886. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66887. if (!parsedSound.url)
  66888. parsedSound.url = parsedSound.name;
  66889. if (!loadedSounds[parsedSound.url]) {
  66890. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66891. loadedSounds[parsedSound.url] = loadedSound;
  66892. container.sounds.push(loadedSound);
  66893. }
  66894. else {
  66895. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66896. }
  66897. }
  66898. else {
  66899. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66900. }
  66901. }
  66902. }
  66903. loadedSounds = [];
  66904. });
  66905. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  66906. get: function () {
  66907. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66908. if (!compo) {
  66909. compo = new AudioSceneComponent(this);
  66910. this._addComponent(compo);
  66911. }
  66912. if (!this._mainSoundTrack) {
  66913. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  66914. }
  66915. return this._mainSoundTrack;
  66916. },
  66917. enumerable: true,
  66918. configurable: true
  66919. });
  66920. BABYLON.Scene.prototype.getSoundByName = function (name) {
  66921. var index;
  66922. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  66923. if (this.mainSoundTrack.soundCollection[index].name === name) {
  66924. return this.mainSoundTrack.soundCollection[index];
  66925. }
  66926. }
  66927. if (this.soundTracks) {
  66928. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  66929. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  66930. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  66931. return this.soundTracks[sdIndex].soundCollection[index];
  66932. }
  66933. }
  66934. }
  66935. }
  66936. return null;
  66937. };
  66938. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  66939. get: function () {
  66940. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66941. if (!compo) {
  66942. compo = new AudioSceneComponent(this);
  66943. this._addComponent(compo);
  66944. }
  66945. return compo.audioEnabled;
  66946. },
  66947. set: function (value) {
  66948. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66949. if (!compo) {
  66950. compo = new AudioSceneComponent(this);
  66951. this._addComponent(compo);
  66952. }
  66953. if (value) {
  66954. compo.enableAudio();
  66955. }
  66956. else {
  66957. compo.disableAudio();
  66958. }
  66959. },
  66960. enumerable: true,
  66961. configurable: true
  66962. });
  66963. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  66964. get: function () {
  66965. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66966. if (!compo) {
  66967. compo = new AudioSceneComponent(this);
  66968. this._addComponent(compo);
  66969. }
  66970. return compo.headphone;
  66971. },
  66972. set: function (value) {
  66973. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66974. if (!compo) {
  66975. compo = new AudioSceneComponent(this);
  66976. this._addComponent(compo);
  66977. }
  66978. if (value) {
  66979. compo.switchAudioModeForHeadphones();
  66980. }
  66981. else {
  66982. compo.switchAudioModeForNormalSpeakers();
  66983. }
  66984. },
  66985. enumerable: true,
  66986. configurable: true
  66987. });
  66988. /**
  66989. * Defines the sound scene component responsible to manage any sounds
  66990. * in a given scene.
  66991. */
  66992. var AudioSceneComponent = /** @class */ (function () {
  66993. /**
  66994. * Creates a new instance of the component for the given scene
  66995. * @param scene Defines the scene to register the component in
  66996. */
  66997. function AudioSceneComponent(scene) {
  66998. /**
  66999. * The component name helpfull to identify the component in the list of scene components.
  67000. */
  67001. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  67002. this._audioEnabled = true;
  67003. this._headphone = false;
  67004. this.scene = scene;
  67005. scene.soundTracks = new Array();
  67006. scene.sounds = new Array();
  67007. }
  67008. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  67009. /**
  67010. * Gets whether audio is enabled or not.
  67011. * Please use related enable/disable method to switch state.
  67012. */
  67013. get: function () {
  67014. return this._audioEnabled;
  67015. },
  67016. enumerable: true,
  67017. configurable: true
  67018. });
  67019. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  67020. /**
  67021. * Gets whether audio is outputing to headphone or not.
  67022. * Please use the according Switch methods to change output.
  67023. */
  67024. get: function () {
  67025. return this._headphone;
  67026. },
  67027. enumerable: true,
  67028. configurable: true
  67029. });
  67030. /**
  67031. * Registers the component in a given scene
  67032. */
  67033. AudioSceneComponent.prototype.register = function () {
  67034. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  67035. };
  67036. /**
  67037. * Rebuilds the elements related to this component in case of
  67038. * context lost for instance.
  67039. */
  67040. AudioSceneComponent.prototype.rebuild = function () {
  67041. // Nothing to do here. (Not rendering related)
  67042. };
  67043. /**
  67044. * Serializes the component data to the specified json object
  67045. * @param serializationObject The object to serialize to
  67046. */
  67047. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  67048. serializationObject.sounds = [];
  67049. if (this.scene.soundTracks) {
  67050. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  67051. var soundtrack = this.scene.soundTracks[index];
  67052. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  67053. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  67054. }
  67055. }
  67056. }
  67057. };
  67058. /**
  67059. * Adds all the element from the container to the scene
  67060. * @param container the container holding the elements
  67061. */
  67062. AudioSceneComponent.prototype.addFromContainer = function (container) {
  67063. var _this = this;
  67064. if (!container.sounds) {
  67065. return;
  67066. }
  67067. container.sounds.forEach(function (sound) {
  67068. sound.play();
  67069. sound.autoplay = true;
  67070. _this.scene.mainSoundTrack.AddSound(sound);
  67071. });
  67072. };
  67073. /**
  67074. * Removes all the elements in the container from the scene
  67075. * @param container contains the elements to remove
  67076. */
  67077. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  67078. var _this = this;
  67079. if (!container.sounds) {
  67080. return;
  67081. }
  67082. container.sounds.forEach(function (sound) {
  67083. sound.stop();
  67084. sound.autoplay = false;
  67085. _this.scene.mainSoundTrack.RemoveSound(sound);
  67086. });
  67087. };
  67088. /**
  67089. * Disposes the component and the associated ressources.
  67090. */
  67091. AudioSceneComponent.prototype.dispose = function () {
  67092. var scene = this.scene;
  67093. if (scene._mainSoundTrack) {
  67094. scene.mainSoundTrack.dispose();
  67095. }
  67096. if (scene.soundTracks) {
  67097. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  67098. scene.soundTracks[scIndex].dispose();
  67099. }
  67100. }
  67101. };
  67102. /**
  67103. * Disables audio in the associated scene.
  67104. */
  67105. AudioSceneComponent.prototype.disableAudio = function () {
  67106. var scene = this.scene;
  67107. this._audioEnabled = false;
  67108. var i;
  67109. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67110. scene.mainSoundTrack.soundCollection[i].pause();
  67111. }
  67112. if (scene.soundTracks) {
  67113. for (i = 0; i < scene.soundTracks.length; i++) {
  67114. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67115. scene.soundTracks[i].soundCollection[j].pause();
  67116. }
  67117. }
  67118. }
  67119. };
  67120. /**
  67121. * Enables audio in the associated scene.
  67122. */
  67123. AudioSceneComponent.prototype.enableAudio = function () {
  67124. var scene = this.scene;
  67125. this._audioEnabled = true;
  67126. var i;
  67127. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67128. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  67129. scene.mainSoundTrack.soundCollection[i].play();
  67130. }
  67131. }
  67132. if (scene.soundTracks) {
  67133. for (i = 0; i < scene.soundTracks.length; i++) {
  67134. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67135. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  67136. scene.soundTracks[i].soundCollection[j].play();
  67137. }
  67138. }
  67139. }
  67140. }
  67141. };
  67142. /**
  67143. * Switch audio to headphone output.
  67144. */
  67145. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  67146. var scene = this.scene;
  67147. this._headphone = true;
  67148. scene.mainSoundTrack.switchPanningModelToHRTF();
  67149. if (scene.soundTracks) {
  67150. for (var i = 0; i < scene.soundTracks.length; i++) {
  67151. scene.soundTracks[i].switchPanningModelToHRTF();
  67152. }
  67153. }
  67154. };
  67155. /**
  67156. * Switch audio to normal speakers.
  67157. */
  67158. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  67159. var scene = this.scene;
  67160. this._headphone = false;
  67161. scene.mainSoundTrack.switchPanningModelToEqualPower();
  67162. if (scene.soundTracks) {
  67163. for (var i = 0; i < scene.soundTracks.length; i++) {
  67164. scene.soundTracks[i].switchPanningModelToEqualPower();
  67165. }
  67166. }
  67167. };
  67168. AudioSceneComponent.prototype._afterRender = function () {
  67169. var scene = this.scene;
  67170. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  67171. return;
  67172. }
  67173. var listeningCamera;
  67174. var audioEngine = BABYLON.Engine.audioEngine;
  67175. if (scene.activeCameras.length > 0) {
  67176. listeningCamera = scene.activeCameras[0];
  67177. }
  67178. else {
  67179. listeningCamera = scene.activeCamera;
  67180. }
  67181. if (listeningCamera && audioEngine.audioContext) {
  67182. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  67183. // for VR cameras
  67184. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  67185. listeningCamera = listeningCamera.rigCameras[0];
  67186. }
  67187. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  67188. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  67189. cameraDirection.normalize();
  67190. // To avoid some errors on GearVR
  67191. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  67192. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  67193. }
  67194. var i;
  67195. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67196. var sound = scene.mainSoundTrack.soundCollection[i];
  67197. if (sound.useCustomAttenuation) {
  67198. sound.updateDistanceFromListener();
  67199. }
  67200. }
  67201. if (scene.soundTracks) {
  67202. for (i = 0; i < scene.soundTracks.length; i++) {
  67203. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67204. sound = scene.soundTracks[i].soundCollection[j];
  67205. if (sound.useCustomAttenuation) {
  67206. sound.updateDistanceFromListener();
  67207. }
  67208. }
  67209. }
  67210. }
  67211. }
  67212. };
  67213. return AudioSceneComponent;
  67214. }());
  67215. BABYLON.AudioSceneComponent = AudioSceneComponent;
  67216. })(BABYLON || (BABYLON = {}));
  67217. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  67218. var BABYLON;
  67219. (function (BABYLON) {
  67220. /**
  67221. * This defines an action helpful to play a defined sound on a triggered action.
  67222. */
  67223. var PlaySoundAction = /** @class */ (function (_super) {
  67224. __extends(PlaySoundAction, _super);
  67225. /**
  67226. * Instantiate the action
  67227. * @param triggerOptions defines the trigger options
  67228. * @param sound defines the sound to play
  67229. * @param condition defines the trigger related conditions
  67230. */
  67231. function PlaySoundAction(triggerOptions, sound, condition) {
  67232. var _this = _super.call(this, triggerOptions, condition) || this;
  67233. _this._sound = sound;
  67234. return _this;
  67235. }
  67236. /** @hidden */
  67237. PlaySoundAction.prototype._prepare = function () {
  67238. };
  67239. /**
  67240. * Execute the action and play the sound.
  67241. */
  67242. PlaySoundAction.prototype.execute = function () {
  67243. if (this._sound !== undefined)
  67244. this._sound.play();
  67245. };
  67246. /**
  67247. * Serializes the actions and its related information.
  67248. * @param parent defines the object to serialize in
  67249. * @returns the serialized object
  67250. */
  67251. PlaySoundAction.prototype.serialize = function (parent) {
  67252. return _super.prototype._serialize.call(this, {
  67253. name: "PlaySoundAction",
  67254. properties: [{ name: "sound", value: this._sound.name }]
  67255. }, parent);
  67256. };
  67257. return PlaySoundAction;
  67258. }(BABYLON.Action));
  67259. BABYLON.PlaySoundAction = PlaySoundAction;
  67260. /**
  67261. * This defines an action helpful to stop a defined sound on a triggered action.
  67262. */
  67263. var StopSoundAction = /** @class */ (function (_super) {
  67264. __extends(StopSoundAction, _super);
  67265. /**
  67266. * Instantiate the action
  67267. * @param triggerOptions defines the trigger options
  67268. * @param sound defines the sound to stop
  67269. * @param condition defines the trigger related conditions
  67270. */
  67271. function StopSoundAction(triggerOptions, sound, condition) {
  67272. var _this = _super.call(this, triggerOptions, condition) || this;
  67273. _this._sound = sound;
  67274. return _this;
  67275. }
  67276. /** @hidden */
  67277. StopSoundAction.prototype._prepare = function () {
  67278. };
  67279. /**
  67280. * Execute the action and stop the sound.
  67281. */
  67282. StopSoundAction.prototype.execute = function () {
  67283. if (this._sound !== undefined)
  67284. this._sound.stop();
  67285. };
  67286. /**
  67287. * Serializes the actions and its related information.
  67288. * @param parent defines the object to serialize in
  67289. * @returns the serialized object
  67290. */
  67291. StopSoundAction.prototype.serialize = function (parent) {
  67292. return _super.prototype._serialize.call(this, {
  67293. name: "StopSoundAction",
  67294. properties: [{ name: "sound", value: this._sound.name }]
  67295. }, parent);
  67296. };
  67297. return StopSoundAction;
  67298. }(BABYLON.Action));
  67299. BABYLON.StopSoundAction = StopSoundAction;
  67300. })(BABYLON || (BABYLON = {}));
  67301. //# sourceMappingURL=babylon.directAudioActions.js.map
  67302. var BABYLON;
  67303. (function (BABYLON) {
  67304. var CubeTexture = /** @class */ (function (_super) {
  67305. __extends(CubeTexture, _super);
  67306. /**
  67307. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  67308. * as prefiltered data.
  67309. * @param rootUrl defines the url of the texture or the root name of the six images
  67310. * @param scene defines the scene the texture is attached to
  67311. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  67312. * @param noMipmap defines if mipmaps should be created or not
  67313. * @param files defines the six files to load for the different faces
  67314. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  67315. * @param onError defines a callback triggered in case of error during load
  67316. * @param format defines the internal format to use for the texture once loaded
  67317. * @param prefiltered defines whether or not the texture is created from prefiltered data
  67318. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  67319. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67320. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67321. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67322. * @return the cube texture
  67323. */
  67324. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  67325. if (extensions === void 0) { extensions = null; }
  67326. if (noMipmap === void 0) { noMipmap = false; }
  67327. if (files === void 0) { files = null; }
  67328. if (onLoad === void 0) { onLoad = null; }
  67329. if (onError === void 0) { onError = null; }
  67330. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67331. if (prefiltered === void 0) { prefiltered = false; }
  67332. if (forcedExtension === void 0) { forcedExtension = null; }
  67333. if (createPolynomials === void 0) { createPolynomials = false; }
  67334. if (lodScale === void 0) { lodScale = 0.8; }
  67335. if (lodOffset === void 0) { lodOffset = 0; }
  67336. var _this = _super.call(this, scene) || this;
  67337. /**
  67338. * Gets or sets the center of the bounding box associated with the cube texture
  67339. * It must define where the camera used to render the texture was set
  67340. */
  67341. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67342. _this._rotationY = 0;
  67343. /** @hidden */
  67344. _this._prefiltered = false;
  67345. _this.name = rootUrl;
  67346. _this.url = rootUrl;
  67347. _this._noMipmap = noMipmap;
  67348. _this.hasAlpha = false;
  67349. _this._format = format;
  67350. _this.isCube = true;
  67351. _this._textureMatrix = BABYLON.Matrix.Identity();
  67352. _this._createPolynomials = createPolynomials;
  67353. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67354. if (!rootUrl && !files) {
  67355. return _this;
  67356. }
  67357. var lastDot = rootUrl.lastIndexOf(".");
  67358. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  67359. var isDDS = (extension === ".dds");
  67360. var isEnv = (extension === ".env");
  67361. if (isEnv) {
  67362. _this.gammaSpace = false;
  67363. _this._prefiltered = false;
  67364. }
  67365. else {
  67366. _this._prefiltered = prefiltered;
  67367. if (prefiltered) {
  67368. _this.gammaSpace = false;
  67369. }
  67370. }
  67371. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  67372. if (!files) {
  67373. if (!isEnv && !isDDS && !extensions) {
  67374. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  67375. }
  67376. files = [];
  67377. if (extensions) {
  67378. for (var index = 0; index < extensions.length; index++) {
  67379. files.push(rootUrl + extensions[index]);
  67380. }
  67381. }
  67382. }
  67383. _this._files = files;
  67384. if (!_this._texture) {
  67385. if (!scene.useDelayedTextureLoading) {
  67386. if (prefiltered) {
  67387. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  67388. }
  67389. else {
  67390. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  67391. }
  67392. }
  67393. else {
  67394. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67395. }
  67396. }
  67397. else if (onLoad) {
  67398. if (_this._texture.isReady) {
  67399. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  67400. }
  67401. else {
  67402. _this._texture.onLoadedObservable.add(onLoad);
  67403. }
  67404. }
  67405. return _this;
  67406. }
  67407. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  67408. get: function () {
  67409. return this._boundingBoxSize;
  67410. },
  67411. /**
  67412. * Gets or sets the size of the bounding box associated with the cube texture
  67413. * When defined, the cubemap will switch to local mode
  67414. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67415. * @example https://www.babylonjs-playground.com/#RNASML
  67416. */
  67417. set: function (value) {
  67418. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67419. return;
  67420. }
  67421. this._boundingBoxSize = value;
  67422. var scene = this.getScene();
  67423. if (scene) {
  67424. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67425. }
  67426. },
  67427. enumerable: true,
  67428. configurable: true
  67429. });
  67430. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  67431. /**
  67432. * Gets texture matrix rotation angle around Y axis radians.
  67433. */
  67434. get: function () {
  67435. return this._rotationY;
  67436. },
  67437. /**
  67438. * Sets texture matrix rotation angle around Y axis in radians.
  67439. */
  67440. set: function (value) {
  67441. this._rotationY = value;
  67442. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  67443. },
  67444. enumerable: true,
  67445. configurable: true
  67446. });
  67447. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  67448. var rootUrlKey = "";
  67449. files.forEach(function (url) { return rootUrlKey += url; });
  67450. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  67451. };
  67452. /**
  67453. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  67454. * @param url defines the url of the prefiltered texture
  67455. * @param scene defines the scene the texture is attached to
  67456. * @param forcedExtension defines the extension of the file if different from the url
  67457. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67458. * @return the prefiltered texture
  67459. */
  67460. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  67461. if (forcedExtension === void 0) { forcedExtension = null; }
  67462. if (createPolynomials === void 0) { createPolynomials = true; }
  67463. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  67464. };
  67465. // Methods
  67466. CubeTexture.prototype.delayLoad = function () {
  67467. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67468. return;
  67469. }
  67470. var scene = this.getScene();
  67471. if (!scene) {
  67472. return;
  67473. }
  67474. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67475. this._texture = this._getFromCache(this.url, this._noMipmap);
  67476. if (!this._texture) {
  67477. if (this._prefiltered) {
  67478. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  67479. }
  67480. else {
  67481. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  67482. }
  67483. }
  67484. };
  67485. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  67486. return this._textureMatrix;
  67487. };
  67488. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67489. this._textureMatrix = value;
  67490. };
  67491. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67492. var texture = BABYLON.SerializationHelper.Parse(function () {
  67493. var prefiltered = false;
  67494. if (parsedTexture.prefiltered) {
  67495. prefiltered = parsedTexture.prefiltered;
  67496. }
  67497. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  67498. }, parsedTexture, scene);
  67499. // Local Cubemaps
  67500. if (parsedTexture.boundingBoxPosition) {
  67501. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  67502. }
  67503. if (parsedTexture.boundingBoxSize) {
  67504. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  67505. }
  67506. // Animations
  67507. if (parsedTexture.animations) {
  67508. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  67509. var parsedAnimation = parsedTexture.animations[animationIndex];
  67510. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67511. }
  67512. }
  67513. return texture;
  67514. };
  67515. CubeTexture.prototype.clone = function () {
  67516. var _this = this;
  67517. return BABYLON.SerializationHelper.Clone(function () {
  67518. var scene = _this.getScene();
  67519. if (!scene) {
  67520. return _this;
  67521. }
  67522. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  67523. }, this);
  67524. };
  67525. __decorate([
  67526. BABYLON.serialize("rotationY")
  67527. ], CubeTexture.prototype, "rotationY", null);
  67528. return CubeTexture;
  67529. }(BABYLON.BaseTexture));
  67530. BABYLON.CubeTexture = CubeTexture;
  67531. })(BABYLON || (BABYLON = {}));
  67532. //# sourceMappingURL=babylon.cubeTexture.js.map
  67533. var BABYLON;
  67534. (function (BABYLON) {
  67535. /**
  67536. * Raw cube texture where the raw buffers are passed in
  67537. */
  67538. var RawCubeTexture = /** @class */ (function (_super) {
  67539. __extends(RawCubeTexture, _super);
  67540. /**
  67541. * Creates a cube texture where the raw buffers are passed in.
  67542. * @param scene defines the scene the texture is attached to
  67543. * @param data defines the array of data to use to create each face
  67544. * @param size defines the size of the textures
  67545. * @param format defines the format of the data
  67546. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  67547. * @param generateMipMaps defines if the engine should generate the mip levels
  67548. * @param invertY defines if data must be stored with Y axis inverted
  67549. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  67550. * @param compression defines the compression used (null by default)
  67551. */
  67552. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  67553. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67554. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67555. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67556. if (invertY === void 0) { invertY = false; }
  67557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67558. if (compression === void 0) { compression = null; }
  67559. var _this = _super.call(this, "", scene) || this;
  67560. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  67561. return _this;
  67562. }
  67563. /**
  67564. * Updates the raw cube texture.
  67565. * @param data defines the data to store
  67566. * @param format defines the data format
  67567. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  67568. * @param invertY defines if data must be stored with Y axis inverted
  67569. * @param compression defines the compression used (null by default)
  67570. * @param level defines which level of the texture to update
  67571. */
  67572. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  67573. if (compression === void 0) { compression = null; }
  67574. if (level === void 0) { level = 0; }
  67575. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  67576. };
  67577. /**
  67578. * Updates a raw cube texture with RGBD encoded data.
  67579. * @param data defines the array of data [mipmap][face] to use to create each face
  67580. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  67581. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67582. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67583. * @returns a promsie that resolves when the operation is complete
  67584. */
  67585. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  67586. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  67587. if (lodScale === void 0) { lodScale = 0.8; }
  67588. if (lodOffset === void 0) { lodOffset = 0; }
  67589. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  67590. };
  67591. /**
  67592. * Clones the raw cube texture.
  67593. * @return a new cube texture
  67594. */
  67595. RawCubeTexture.prototype.clone = function () {
  67596. var _this = this;
  67597. return BABYLON.SerializationHelper.Clone(function () {
  67598. var scene = _this.getScene();
  67599. var internalTexture = _this._texture;
  67600. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  67601. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  67602. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  67603. }
  67604. return texture;
  67605. }, this);
  67606. };
  67607. /** @hidden */
  67608. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  67609. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  67610. internalTexture._bufferViewArrayArray = data;
  67611. internalTexture._lodGenerationScale = lodScale;
  67612. internalTexture._lodGenerationOffset = lodOffset;
  67613. internalTexture._sphericalPolynomial = sphericalPolynomial;
  67614. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  67615. internalTexture.isReady = true;
  67616. });
  67617. };
  67618. return RawCubeTexture;
  67619. }(BABYLON.CubeTexture));
  67620. BABYLON.RawCubeTexture = RawCubeTexture;
  67621. })(BABYLON || (BABYLON = {}));
  67622. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  67623. var BABYLON;
  67624. (function (BABYLON) {
  67625. var RenderTargetTexture = /** @class */ (function (_super) {
  67626. __extends(RenderTargetTexture, _super);
  67627. /**
  67628. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  67629. * or used a shadow, depth texture...
  67630. * @param name The friendly name of the texture
  67631. * @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)
  67632. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  67633. * @param generateMipMaps True if mip maps need to be generated after render.
  67634. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  67635. * @param type The type of the buffer in the RTT (int, half float, float...)
  67636. * @param isCube True if a cube texture needs to be created
  67637. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  67638. * @param generateDepthBuffer True to generate a depth buffer
  67639. * @param generateStencilBuffer True to generate a stencil buffer
  67640. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  67641. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  67642. */
  67643. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  67644. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  67645. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67646. if (isCube === void 0) { isCube = false; }
  67647. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67648. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67649. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  67650. if (isMulti === void 0) { isMulti = false; }
  67651. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67652. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67653. _this.isCube = isCube;
  67654. _this.renderParticles = true;
  67655. _this.renderSprites = false;
  67656. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  67657. _this.ignoreCameraViewport = false;
  67658. // Events
  67659. /**
  67660. * An event triggered when the texture is unbind.
  67661. */
  67662. _this.onBeforeBindObservable = new BABYLON.Observable();
  67663. /**
  67664. * An event triggered when the texture is unbind.
  67665. */
  67666. _this.onAfterUnbindObservable = new BABYLON.Observable();
  67667. /**
  67668. * An event triggered before rendering the texture
  67669. */
  67670. _this.onBeforeRenderObservable = new BABYLON.Observable();
  67671. /**
  67672. * An event triggered after rendering the texture
  67673. */
  67674. _this.onAfterRenderObservable = new BABYLON.Observable();
  67675. /**
  67676. * An event triggered after the texture clear
  67677. */
  67678. _this.onClearObservable = new BABYLON.Observable();
  67679. _this._currentRefreshId = -1;
  67680. _this._refreshRate = 1;
  67681. _this._samples = 1;
  67682. /**
  67683. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  67684. * It must define where the camera used to render the texture is set
  67685. */
  67686. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67687. scene = _this.getScene();
  67688. if (!scene) {
  67689. return _this;
  67690. }
  67691. _this.renderList = new Array();
  67692. _this._engine = scene.getEngine();
  67693. _this.name = name;
  67694. _this.isRenderTarget = true;
  67695. _this._initialSizeParameter = size;
  67696. _this._processSizeParameter(size);
  67697. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  67698. });
  67699. _this._generateMipMaps = generateMipMaps ? true : false;
  67700. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  67701. // Rendering groups
  67702. _this._renderingManager = new BABYLON.RenderingManager(scene);
  67703. _this._renderingManager._useSceneAutoClearSetup = true;
  67704. if (isMulti) {
  67705. return _this;
  67706. }
  67707. _this._renderTargetOptions = {
  67708. generateMipMaps: generateMipMaps,
  67709. type: type,
  67710. format: format,
  67711. samplingMode: samplingMode,
  67712. generateDepthBuffer: generateDepthBuffer,
  67713. generateStencilBuffer: generateStencilBuffer
  67714. };
  67715. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  67716. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67717. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67718. }
  67719. if (isCube) {
  67720. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  67721. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  67722. _this._textureMatrix = BABYLON.Matrix.Identity();
  67723. }
  67724. else {
  67725. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  67726. }
  67727. return _this;
  67728. }
  67729. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  67730. get: function () {
  67731. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  67732. },
  67733. enumerable: true,
  67734. configurable: true
  67735. });
  67736. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  67737. get: function () {
  67738. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  67739. },
  67740. enumerable: true,
  67741. configurable: true
  67742. });
  67743. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  67744. get: function () {
  67745. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  67746. },
  67747. enumerable: true,
  67748. configurable: true
  67749. });
  67750. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  67751. /**
  67752. * Use this list to define the list of mesh you want to render.
  67753. */
  67754. get: function () {
  67755. return this._renderList;
  67756. },
  67757. set: function (value) {
  67758. this._renderList = value;
  67759. if (this._renderList) {
  67760. this._hookArray(this._renderList);
  67761. }
  67762. },
  67763. enumerable: true,
  67764. configurable: true
  67765. });
  67766. RenderTargetTexture.prototype._hookArray = function (array) {
  67767. var _this = this;
  67768. var oldPush = array.push;
  67769. array.push = function () {
  67770. var items = [];
  67771. for (var _i = 0; _i < arguments.length; _i++) {
  67772. items[_i] = arguments[_i];
  67773. }
  67774. var result = oldPush.apply(array, items);
  67775. _this.getScene().meshes.forEach(function (mesh) {
  67776. mesh._markSubMeshesAsLightDirty();
  67777. });
  67778. return result;
  67779. };
  67780. var oldSplice = array.splice;
  67781. array.splice = function (index, deleteCount) {
  67782. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67783. _this.getScene().meshes.forEach(function (mesh) {
  67784. mesh._markSubMeshesAsLightDirty();
  67785. });
  67786. return deleted;
  67787. };
  67788. };
  67789. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  67790. set: function (callback) {
  67791. if (this._onAfterUnbindObserver) {
  67792. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  67793. }
  67794. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  67795. },
  67796. enumerable: true,
  67797. configurable: true
  67798. });
  67799. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  67800. set: function (callback) {
  67801. if (this._onBeforeRenderObserver) {
  67802. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67803. }
  67804. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67805. },
  67806. enumerable: true,
  67807. configurable: true
  67808. });
  67809. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  67810. set: function (callback) {
  67811. if (this._onAfterRenderObserver) {
  67812. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67813. }
  67814. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67815. },
  67816. enumerable: true,
  67817. configurable: true
  67818. });
  67819. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  67820. set: function (callback) {
  67821. if (this._onClearObserver) {
  67822. this.onClearObservable.remove(this._onClearObserver);
  67823. }
  67824. this._onClearObserver = this.onClearObservable.add(callback);
  67825. },
  67826. enumerable: true,
  67827. configurable: true
  67828. });
  67829. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  67830. get: function () {
  67831. return this._renderTargetOptions;
  67832. },
  67833. enumerable: true,
  67834. configurable: true
  67835. });
  67836. RenderTargetTexture.prototype._onRatioRescale = function () {
  67837. if (this._sizeRatio) {
  67838. this.resize(this._initialSizeParameter);
  67839. }
  67840. };
  67841. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  67842. get: function () {
  67843. return this._boundingBoxSize;
  67844. },
  67845. /**
  67846. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  67847. * When defined, the cubemap will switch to local mode
  67848. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67849. * @example https://www.babylonjs-playground.com/#RNASML
  67850. */
  67851. set: function (value) {
  67852. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67853. return;
  67854. }
  67855. this._boundingBoxSize = value;
  67856. var scene = this.getScene();
  67857. if (scene) {
  67858. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67859. }
  67860. },
  67861. enumerable: true,
  67862. configurable: true
  67863. });
  67864. /**
  67865. * Creates a depth stencil texture.
  67866. * This is only available in WebGL 2 or with the depth texture extension available.
  67867. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  67868. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  67869. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  67870. */
  67871. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  67872. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  67873. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  67874. if (generateStencil === void 0) { generateStencil = false; }
  67875. if (!this.getScene()) {
  67876. return;
  67877. }
  67878. var engine = this.getScene().getEngine();
  67879. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  67880. bilinearFiltering: bilinearFiltering,
  67881. comparisonFunction: comparisonFunction,
  67882. generateStencil: generateStencil,
  67883. isCube: this.isCube
  67884. });
  67885. engine.setFrameBufferDepthStencilTexture(this);
  67886. };
  67887. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  67888. if (size.ratio) {
  67889. this._sizeRatio = size.ratio;
  67890. this._size = {
  67891. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  67892. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  67893. };
  67894. }
  67895. else {
  67896. this._size = size;
  67897. }
  67898. };
  67899. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  67900. get: function () {
  67901. return this._samples;
  67902. },
  67903. set: function (value) {
  67904. if (this._samples === value) {
  67905. return;
  67906. }
  67907. var scene = this.getScene();
  67908. if (!scene) {
  67909. return;
  67910. }
  67911. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  67912. },
  67913. enumerable: true,
  67914. configurable: true
  67915. });
  67916. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  67917. this._currentRefreshId = -1;
  67918. };
  67919. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  67920. get: function () {
  67921. return this._refreshRate;
  67922. },
  67923. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67924. set: function (value) {
  67925. this._refreshRate = value;
  67926. this.resetRefreshCounter();
  67927. },
  67928. enumerable: true,
  67929. configurable: true
  67930. });
  67931. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  67932. if (!this._postProcessManager) {
  67933. var scene = this.getScene();
  67934. if (!scene) {
  67935. return;
  67936. }
  67937. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  67938. this._postProcesses = new Array();
  67939. }
  67940. this._postProcesses.push(postProcess);
  67941. this._postProcesses[0].autoClear = false;
  67942. };
  67943. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  67944. if (!this._postProcesses) {
  67945. return;
  67946. }
  67947. if (dispose) {
  67948. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  67949. var postProcess = _a[_i];
  67950. postProcess.dispose();
  67951. }
  67952. }
  67953. this._postProcesses = [];
  67954. };
  67955. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  67956. if (!this._postProcesses) {
  67957. return;
  67958. }
  67959. var index = this._postProcesses.indexOf(postProcess);
  67960. if (index === -1) {
  67961. return;
  67962. }
  67963. this._postProcesses.splice(index, 1);
  67964. if (this._postProcesses.length > 0) {
  67965. this._postProcesses[0].autoClear = false;
  67966. }
  67967. };
  67968. /** @hidden */
  67969. RenderTargetTexture.prototype._shouldRender = function () {
  67970. if (this._currentRefreshId === -1) { // At least render once
  67971. this._currentRefreshId = 1;
  67972. return true;
  67973. }
  67974. if (this.refreshRate === this._currentRefreshId) {
  67975. this._currentRefreshId = 1;
  67976. return true;
  67977. }
  67978. this._currentRefreshId++;
  67979. return false;
  67980. };
  67981. RenderTargetTexture.prototype.getRenderSize = function () {
  67982. if (this._size.width) {
  67983. return this._size.width;
  67984. }
  67985. return this._size;
  67986. };
  67987. RenderTargetTexture.prototype.getRenderWidth = function () {
  67988. if (this._size.width) {
  67989. return this._size.width;
  67990. }
  67991. return this._size;
  67992. };
  67993. RenderTargetTexture.prototype.getRenderHeight = function () {
  67994. if (this._size.width) {
  67995. return this._size.height;
  67996. }
  67997. return this._size;
  67998. };
  67999. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  68000. get: function () {
  68001. return true;
  68002. },
  68003. enumerable: true,
  68004. configurable: true
  68005. });
  68006. RenderTargetTexture.prototype.scale = function (ratio) {
  68007. var newSize = this.getRenderSize() * ratio;
  68008. this.resize(newSize);
  68009. };
  68010. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  68011. if (this.isCube) {
  68012. return this._textureMatrix;
  68013. }
  68014. return _super.prototype.getReflectionTextureMatrix.call(this);
  68015. };
  68016. RenderTargetTexture.prototype.resize = function (size) {
  68017. this.releaseInternalTexture();
  68018. var scene = this.getScene();
  68019. if (!scene) {
  68020. return;
  68021. }
  68022. this._processSizeParameter(size);
  68023. if (this.isCube) {
  68024. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  68025. }
  68026. else {
  68027. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  68028. }
  68029. };
  68030. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  68031. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  68032. if (dumpForDebug === void 0) { dumpForDebug = false; }
  68033. var scene = this.getScene();
  68034. if (!scene) {
  68035. return;
  68036. }
  68037. var engine = scene.getEngine();
  68038. if (this.useCameraPostProcesses !== undefined) {
  68039. useCameraPostProcess = this.useCameraPostProcesses;
  68040. }
  68041. if (this._waitingRenderList) {
  68042. this.renderList = [];
  68043. for (var index = 0; index < this._waitingRenderList.length; index++) {
  68044. var id = this._waitingRenderList[index];
  68045. var mesh_1 = scene.getMeshByID(id);
  68046. if (mesh_1) {
  68047. this.renderList.push(mesh_1);
  68048. }
  68049. }
  68050. delete this._waitingRenderList;
  68051. }
  68052. // Is predicate defined?
  68053. if (this.renderListPredicate) {
  68054. if (this.renderList) {
  68055. this.renderList.splice(0); // Clear previous renderList
  68056. }
  68057. else {
  68058. this.renderList = [];
  68059. }
  68060. var scene = this.getScene();
  68061. if (!scene) {
  68062. return;
  68063. }
  68064. var sceneMeshes = scene.meshes;
  68065. for (var index = 0; index < sceneMeshes.length; index++) {
  68066. var mesh = sceneMeshes[index];
  68067. if (this.renderListPredicate(mesh)) {
  68068. this.renderList.push(mesh);
  68069. }
  68070. }
  68071. }
  68072. this.onBeforeBindObservable.notifyObservers(this);
  68073. // Set custom projection.
  68074. // Needs to be before binding to prevent changing the aspect ratio.
  68075. var camera;
  68076. if (this.activeCamera) {
  68077. camera = this.activeCamera;
  68078. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  68079. if (this.activeCamera !== scene.activeCamera) {
  68080. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  68081. }
  68082. }
  68083. else {
  68084. camera = scene.activeCamera;
  68085. if (camera) {
  68086. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  68087. }
  68088. }
  68089. // Prepare renderingManager
  68090. this._renderingManager.reset();
  68091. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  68092. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  68093. var sceneRenderId = scene.getRenderId();
  68094. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  68095. var mesh = currentRenderList[meshIndex];
  68096. if (mesh) {
  68097. if (!mesh.isReady(this.refreshRate === 0)) {
  68098. this.resetRefreshCounter();
  68099. continue;
  68100. }
  68101. mesh._preActivateForIntermediateRendering(sceneRenderId);
  68102. var isMasked = void 0;
  68103. if (!this.renderList && camera) {
  68104. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  68105. }
  68106. else {
  68107. isMasked = false;
  68108. }
  68109. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  68110. mesh._activate(sceneRenderId);
  68111. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  68112. var subMesh = mesh.subMeshes[subIndex];
  68113. scene._activeIndices.addCount(subMesh.indexCount, false);
  68114. this._renderingManager.dispatch(subMesh, mesh);
  68115. }
  68116. }
  68117. }
  68118. }
  68119. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  68120. var particleSystem = scene.particleSystems[particleIndex];
  68121. var emitter = particleSystem.emitter;
  68122. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  68123. continue;
  68124. }
  68125. if (currentRenderList.indexOf(emitter) >= 0) {
  68126. this._renderingManager.dispatchParticles(particleSystem);
  68127. }
  68128. }
  68129. if (this.isCube) {
  68130. for (var face = 0; face < 6; face++) {
  68131. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  68132. scene.incrementRenderId();
  68133. scene.resetCachedMaterial();
  68134. }
  68135. }
  68136. else {
  68137. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  68138. }
  68139. this.onAfterUnbindObservable.notifyObservers(this);
  68140. if (scene.activeCamera) {
  68141. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  68142. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  68143. }
  68144. engine.setViewport(scene.activeCamera.viewport);
  68145. }
  68146. scene.resetCachedMaterial();
  68147. };
  68148. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  68149. var minimum = 128;
  68150. var x = renderDimension * scale;
  68151. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  68152. // Ensure we don't exceed the render dimension (while staying POT)
  68153. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  68154. };
  68155. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68156. var _this = this;
  68157. if (!this._texture) {
  68158. return;
  68159. }
  68160. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  68161. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68162. });
  68163. };
  68164. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  68165. var scene = this.getScene();
  68166. if (!scene) {
  68167. return;
  68168. }
  68169. var engine = scene.getEngine();
  68170. if (!this._texture) {
  68171. return;
  68172. }
  68173. // Bind
  68174. if (this._postProcessManager) {
  68175. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  68176. }
  68177. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  68178. if (this._texture) {
  68179. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  68180. }
  68181. }
  68182. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  68183. // Clear
  68184. if (this.onClearObservable.hasObservers()) {
  68185. this.onClearObservable.notifyObservers(engine);
  68186. }
  68187. else {
  68188. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  68189. }
  68190. if (!this._doNotChangeAspectRatio) {
  68191. scene.updateTransformMatrix(true);
  68192. }
  68193. // Render
  68194. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  68195. if (this._postProcessManager) {
  68196. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  68197. }
  68198. else if (useCameraPostProcess) {
  68199. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  68200. }
  68201. if (!this._doNotChangeAspectRatio) {
  68202. scene.updateTransformMatrix(true);
  68203. }
  68204. // Dump ?
  68205. if (dumpForDebug) {
  68206. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  68207. }
  68208. // Unbind
  68209. if (!this.isCube || faceIndex === 5) {
  68210. if (this.isCube) {
  68211. if (faceIndex === 5) {
  68212. engine.generateMipMapsForCubemap(this._texture);
  68213. }
  68214. }
  68215. this.unbindFrameBuffer(engine, faceIndex);
  68216. }
  68217. else {
  68218. this.onAfterRenderObservable.notifyObservers(faceIndex);
  68219. }
  68220. };
  68221. /**
  68222. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  68223. * This allowed control for front to back rendering or reversly depending of the special needs.
  68224. *
  68225. * @param renderingGroupId The rendering group id corresponding to its index
  68226. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  68227. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  68228. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  68229. */
  68230. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  68231. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  68232. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  68233. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  68234. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  68235. };
  68236. /**
  68237. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  68238. *
  68239. * @param renderingGroupId The rendering group id corresponding to its index
  68240. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  68241. */
  68242. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  68243. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  68244. this._renderingManager._useSceneAutoClearSetup = false;
  68245. };
  68246. RenderTargetTexture.prototype.clone = function () {
  68247. var textureSize = this.getSize();
  68248. 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);
  68249. // Base texture
  68250. newTexture.hasAlpha = this.hasAlpha;
  68251. newTexture.level = this.level;
  68252. // RenderTarget Texture
  68253. newTexture.coordinatesMode = this.coordinatesMode;
  68254. if (this.renderList) {
  68255. newTexture.renderList = this.renderList.slice(0);
  68256. }
  68257. return newTexture;
  68258. };
  68259. RenderTargetTexture.prototype.serialize = function () {
  68260. if (!this.name) {
  68261. return null;
  68262. }
  68263. var serializationObject = _super.prototype.serialize.call(this);
  68264. serializationObject.renderTargetSize = this.getRenderSize();
  68265. serializationObject.renderList = [];
  68266. if (this.renderList) {
  68267. for (var index = 0; index < this.renderList.length; index++) {
  68268. serializationObject.renderList.push(this.renderList[index].id);
  68269. }
  68270. }
  68271. return serializationObject;
  68272. };
  68273. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  68274. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  68275. var objBuffer = this.getInternalTexture();
  68276. var scene = this.getScene();
  68277. if (objBuffer && scene) {
  68278. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  68279. }
  68280. };
  68281. RenderTargetTexture.prototype.dispose = function () {
  68282. if (this._postProcessManager) {
  68283. this._postProcessManager.dispose();
  68284. this._postProcessManager = null;
  68285. }
  68286. this.clearPostProcesses(true);
  68287. if (this._resizeObserver) {
  68288. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  68289. this._resizeObserver = null;
  68290. }
  68291. this.renderList = null;
  68292. // Remove from custom render targets
  68293. var scene = this.getScene();
  68294. if (!scene) {
  68295. return;
  68296. }
  68297. var index = scene.customRenderTargets.indexOf(this);
  68298. if (index >= 0) {
  68299. scene.customRenderTargets.splice(index, 1);
  68300. }
  68301. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  68302. var camera = _a[_i];
  68303. index = camera.customRenderTargets.indexOf(this);
  68304. if (index >= 0) {
  68305. camera.customRenderTargets.splice(index, 1);
  68306. }
  68307. }
  68308. _super.prototype.dispose.call(this);
  68309. };
  68310. /** @hidden */
  68311. RenderTargetTexture.prototype._rebuild = function () {
  68312. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68313. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68314. }
  68315. if (this._postProcessManager) {
  68316. this._postProcessManager._rebuild();
  68317. }
  68318. };
  68319. /**
  68320. * Clear the info related to rendering groups preventing retention point in material dispose.
  68321. */
  68322. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  68323. if (this._renderingManager) {
  68324. this._renderingManager.freeRenderingGroups();
  68325. }
  68326. };
  68327. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  68328. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  68329. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  68330. return RenderTargetTexture;
  68331. }(BABYLON.Texture));
  68332. BABYLON.RenderTargetTexture = RenderTargetTexture;
  68333. })(BABYLON || (BABYLON = {}));
  68334. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  68335. var BABYLON;
  68336. (function (BABYLON) {
  68337. ;
  68338. var MultiRenderTarget = /** @class */ (function (_super) {
  68339. __extends(MultiRenderTarget, _super);
  68340. function MultiRenderTarget(name, size, count, scene, options) {
  68341. var _this = this;
  68342. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  68343. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  68344. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  68345. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  68346. _this._engine = scene.getEngine();
  68347. if (!_this.isSupported) {
  68348. _this.dispose();
  68349. return;
  68350. }
  68351. var types = [];
  68352. var samplingModes = [];
  68353. for (var i = 0; i < count; i++) {
  68354. if (options && options.types && options.types[i] !== undefined) {
  68355. types.push(options.types[i]);
  68356. }
  68357. else {
  68358. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68359. }
  68360. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  68361. samplingModes.push(options.samplingModes[i]);
  68362. }
  68363. else {
  68364. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68365. }
  68366. }
  68367. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  68368. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  68369. _this._size = size;
  68370. _this._multiRenderTargetOptions = {
  68371. samplingModes: samplingModes,
  68372. generateMipMaps: generateMipMaps,
  68373. generateDepthBuffer: generateDepthBuffer,
  68374. generateStencilBuffer: generateStencilBuffer,
  68375. generateDepthTexture: generateDepthTexture,
  68376. types: types,
  68377. textureCount: count
  68378. };
  68379. _this._createInternalTextures();
  68380. _this._createTextures();
  68381. return _this;
  68382. }
  68383. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  68384. get: function () {
  68385. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  68386. },
  68387. enumerable: true,
  68388. configurable: true
  68389. });
  68390. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  68391. get: function () {
  68392. return this._textures;
  68393. },
  68394. enumerable: true,
  68395. configurable: true
  68396. });
  68397. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  68398. get: function () {
  68399. return this._textures[this._textures.length - 1];
  68400. },
  68401. enumerable: true,
  68402. configurable: true
  68403. });
  68404. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  68405. set: function (wrap) {
  68406. if (this._textures) {
  68407. for (var i = 0; i < this._textures.length; i++) {
  68408. this._textures[i].wrapU = wrap;
  68409. }
  68410. }
  68411. },
  68412. enumerable: true,
  68413. configurable: true
  68414. });
  68415. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  68416. set: function (wrap) {
  68417. if (this._textures) {
  68418. for (var i = 0; i < this._textures.length; i++) {
  68419. this._textures[i].wrapV = wrap;
  68420. }
  68421. }
  68422. },
  68423. enumerable: true,
  68424. configurable: true
  68425. });
  68426. /** @hidden */
  68427. MultiRenderTarget.prototype._rebuild = function () {
  68428. this.releaseInternalTextures();
  68429. this._createInternalTextures();
  68430. for (var i = 0; i < this._internalTextures.length; i++) {
  68431. var texture = this._textures[i];
  68432. texture._texture = this._internalTextures[i];
  68433. }
  68434. // Keeps references to frame buffer and stencil/depth buffer
  68435. this._texture = this._internalTextures[0];
  68436. };
  68437. MultiRenderTarget.prototype._createInternalTextures = function () {
  68438. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  68439. };
  68440. MultiRenderTarget.prototype._createTextures = function () {
  68441. this._textures = [];
  68442. for (var i = 0; i < this._internalTextures.length; i++) {
  68443. var texture = new BABYLON.Texture(null, this.getScene());
  68444. texture._texture = this._internalTextures[i];
  68445. this._textures.push(texture);
  68446. }
  68447. // Keeps references to frame buffer and stencil/depth buffer
  68448. this._texture = this._internalTextures[0];
  68449. };
  68450. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  68451. get: function () {
  68452. return this._samples;
  68453. },
  68454. set: function (value) {
  68455. if (this._samples === value) {
  68456. return;
  68457. }
  68458. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  68459. },
  68460. enumerable: true,
  68461. configurable: true
  68462. });
  68463. MultiRenderTarget.prototype.resize = function (size) {
  68464. this.releaseInternalTextures();
  68465. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  68466. this._createInternalTextures();
  68467. };
  68468. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68469. var _this = this;
  68470. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  68471. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68472. });
  68473. };
  68474. MultiRenderTarget.prototype.dispose = function () {
  68475. this.releaseInternalTextures();
  68476. _super.prototype.dispose.call(this);
  68477. };
  68478. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  68479. if (!this._internalTextures) {
  68480. return;
  68481. }
  68482. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  68483. if (this._internalTextures[i] !== undefined) {
  68484. this._internalTextures[i].dispose();
  68485. this._internalTextures.splice(i, 1);
  68486. }
  68487. }
  68488. };
  68489. return MultiRenderTarget;
  68490. }(BABYLON.RenderTargetTexture));
  68491. BABYLON.MultiRenderTarget = MultiRenderTarget;
  68492. })(BABYLON || (BABYLON = {}));
  68493. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  68494. var BABYLON;
  68495. (function (BABYLON) {
  68496. var MirrorTexture = /** @class */ (function (_super) {
  68497. __extends(MirrorTexture, _super);
  68498. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  68499. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68500. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68501. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  68502. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  68503. _this.scene = scene;
  68504. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  68505. _this._transformMatrix = BABYLON.Matrix.Zero();
  68506. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  68507. _this._adaptiveBlurKernel = 0;
  68508. _this._blurKernelX = 0;
  68509. _this._blurKernelY = 0;
  68510. _this._blurRatio = 1.0;
  68511. _this.ignoreCameraViewport = true;
  68512. _this._updateGammaSpace();
  68513. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  68514. _this._updateGammaSpace;
  68515. });
  68516. _this.onBeforeRenderObservable.add(function () {
  68517. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  68518. _this._savedViewMatrix = scene.getViewMatrix();
  68519. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  68520. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  68521. scene.clipPlane = _this.mirrorPlane;
  68522. scene.getEngine().cullBackFaces = false;
  68523. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  68524. });
  68525. _this.onAfterRenderObservable.add(function () {
  68526. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  68527. scene.getEngine().cullBackFaces = true;
  68528. scene._mirroredCameraPosition = null;
  68529. delete scene.clipPlane;
  68530. });
  68531. return _this;
  68532. }
  68533. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  68534. get: function () {
  68535. return this._blurRatio;
  68536. },
  68537. set: function (value) {
  68538. if (this._blurRatio === value) {
  68539. return;
  68540. }
  68541. this._blurRatio = value;
  68542. this._preparePostProcesses();
  68543. },
  68544. enumerable: true,
  68545. configurable: true
  68546. });
  68547. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  68548. set: function (value) {
  68549. this._adaptiveBlurKernel = value;
  68550. this._autoComputeBlurKernel();
  68551. },
  68552. enumerable: true,
  68553. configurable: true
  68554. });
  68555. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  68556. set: function (value) {
  68557. this.blurKernelX = value;
  68558. this.blurKernelY = value;
  68559. },
  68560. enumerable: true,
  68561. configurable: true
  68562. });
  68563. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  68564. get: function () {
  68565. return this._blurKernelX;
  68566. },
  68567. set: function (value) {
  68568. if (this._blurKernelX === value) {
  68569. return;
  68570. }
  68571. this._blurKernelX = value;
  68572. this._preparePostProcesses();
  68573. },
  68574. enumerable: true,
  68575. configurable: true
  68576. });
  68577. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  68578. get: function () {
  68579. return this._blurKernelY;
  68580. },
  68581. set: function (value) {
  68582. if (this._blurKernelY === value) {
  68583. return;
  68584. }
  68585. this._blurKernelY = value;
  68586. this._preparePostProcesses();
  68587. },
  68588. enumerable: true,
  68589. configurable: true
  68590. });
  68591. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  68592. var engine = this.getScene().getEngine();
  68593. var dw = this.getRenderWidth() / engine.getRenderWidth();
  68594. var dh = this.getRenderHeight() / engine.getRenderHeight();
  68595. this.blurKernelX = this._adaptiveBlurKernel * dw;
  68596. this.blurKernelY = this._adaptiveBlurKernel * dh;
  68597. };
  68598. MirrorTexture.prototype._onRatioRescale = function () {
  68599. if (this._sizeRatio) {
  68600. this.resize(this._initialSizeParameter);
  68601. if (!this._adaptiveBlurKernel) {
  68602. this._preparePostProcesses();
  68603. }
  68604. }
  68605. if (this._adaptiveBlurKernel) {
  68606. this._autoComputeBlurKernel();
  68607. }
  68608. };
  68609. MirrorTexture.prototype._updateGammaSpace = function () {
  68610. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  68611. };
  68612. MirrorTexture.prototype._preparePostProcesses = function () {
  68613. this.clearPostProcesses(true);
  68614. if (this._blurKernelX && this._blurKernelY) {
  68615. var engine = this.getScene().getEngine();
  68616. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68617. 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);
  68618. this._blurX.autoClear = false;
  68619. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  68620. this._blurX.inputTexture = this._texture;
  68621. }
  68622. else {
  68623. this._blurX.alwaysForcePOT = true;
  68624. }
  68625. 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);
  68626. this._blurY.autoClear = false;
  68627. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  68628. this.addPostProcess(this._blurX);
  68629. this.addPostProcess(this._blurY);
  68630. }
  68631. else {
  68632. if (this._blurY) {
  68633. this.removePostProcess(this._blurY);
  68634. this._blurY.dispose();
  68635. this._blurY = null;
  68636. }
  68637. if (this._blurX) {
  68638. this.removePostProcess(this._blurX);
  68639. this._blurX.dispose();
  68640. this._blurX = null;
  68641. }
  68642. }
  68643. };
  68644. MirrorTexture.prototype.clone = function () {
  68645. var scene = this.getScene();
  68646. if (!scene) {
  68647. return this;
  68648. }
  68649. var textureSize = this.getSize();
  68650. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  68651. // Base texture
  68652. newTexture.hasAlpha = this.hasAlpha;
  68653. newTexture.level = this.level;
  68654. // Mirror Texture
  68655. newTexture.mirrorPlane = this.mirrorPlane.clone();
  68656. if (this.renderList) {
  68657. newTexture.renderList = this.renderList.slice(0);
  68658. }
  68659. return newTexture;
  68660. };
  68661. MirrorTexture.prototype.serialize = function () {
  68662. if (!this.name) {
  68663. return null;
  68664. }
  68665. var serializationObject = _super.prototype.serialize.call(this);
  68666. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  68667. return serializationObject;
  68668. };
  68669. MirrorTexture.prototype.dispose = function () {
  68670. _super.prototype.dispose.call(this);
  68671. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  68672. };
  68673. return MirrorTexture;
  68674. }(BABYLON.RenderTargetTexture));
  68675. BABYLON.MirrorTexture = MirrorTexture;
  68676. })(BABYLON || (BABYLON = {}));
  68677. //# sourceMappingURL=babylon.mirrorTexture.js.map
  68678. var BABYLON;
  68679. (function (BABYLON) {
  68680. /**
  68681. * Creates a refraction texture used by refraction channel of the standard material.
  68682. * @param name the texture name
  68683. * @param size size of the underlying texture
  68684. * @param scene root scene
  68685. */
  68686. var RefractionTexture = /** @class */ (function (_super) {
  68687. __extends(RefractionTexture, _super);
  68688. function RefractionTexture(name, size, scene, generateMipMaps) {
  68689. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  68690. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  68691. _this.depth = 2.0;
  68692. _this.onBeforeRenderObservable.add(function () {
  68693. scene.clipPlane = _this.refractionPlane;
  68694. });
  68695. _this.onAfterRenderObservable.add(function () {
  68696. delete scene.clipPlane;
  68697. });
  68698. return _this;
  68699. }
  68700. RefractionTexture.prototype.clone = function () {
  68701. var scene = this.getScene();
  68702. if (!scene) {
  68703. return this;
  68704. }
  68705. var textureSize = this.getSize();
  68706. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  68707. // Base texture
  68708. newTexture.hasAlpha = this.hasAlpha;
  68709. newTexture.level = this.level;
  68710. // Refraction Texture
  68711. newTexture.refractionPlane = this.refractionPlane.clone();
  68712. if (this.renderList) {
  68713. newTexture.renderList = this.renderList.slice(0);
  68714. }
  68715. newTexture.depth = this.depth;
  68716. return newTexture;
  68717. };
  68718. RefractionTexture.prototype.serialize = function () {
  68719. if (!this.name) {
  68720. return null;
  68721. }
  68722. var serializationObject = _super.prototype.serialize.call(this);
  68723. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  68724. serializationObject.depth = this.depth;
  68725. return serializationObject;
  68726. };
  68727. return RefractionTexture;
  68728. }(BABYLON.RenderTargetTexture));
  68729. BABYLON.RefractionTexture = RefractionTexture;
  68730. })(BABYLON || (BABYLON = {}));
  68731. //# sourceMappingURL=babylon.refractionTexture.js.map
  68732. var BABYLON;
  68733. (function (BABYLON) {
  68734. /**
  68735. * A class extending {BABYLON.Texture} allowing drawing on a texture
  68736. * @see http://doc.babylonjs.com/how_to/dynamictexture
  68737. */
  68738. var DynamicTexture = /** @class */ (function (_super) {
  68739. __extends(DynamicTexture, _super);
  68740. /**
  68741. * Creates a {BABYLON.DynamicTexture}
  68742. * @param name defines the name of the texture
  68743. * @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
  68744. * @param scene defines the scene where you want the texture
  68745. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  68746. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  68747. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  68748. */
  68749. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  68750. if (scene === void 0) { scene = null; }
  68751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68752. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68753. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  68754. _this.name = name;
  68755. _this._engine = _this.getScene().getEngine();
  68756. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68757. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68758. _this._generateMipMaps = generateMipMaps;
  68759. if (options.getContext) {
  68760. _this._canvas = options;
  68761. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68762. }
  68763. else {
  68764. _this._canvas = document.createElement("canvas");
  68765. if (options.width || options.width === 0) {
  68766. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68767. }
  68768. else {
  68769. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  68770. }
  68771. }
  68772. var textureSize = _this.getSize();
  68773. _this._canvas.width = textureSize.width;
  68774. _this._canvas.height = textureSize.height;
  68775. _this._context = _this._canvas.getContext("2d");
  68776. return _this;
  68777. }
  68778. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  68779. /**
  68780. * Gets the current state of canRescale
  68781. */
  68782. get: function () {
  68783. return true;
  68784. },
  68785. enumerable: true,
  68786. configurable: true
  68787. });
  68788. DynamicTexture.prototype._recreate = function (textureSize) {
  68789. this._canvas.width = textureSize.width;
  68790. this._canvas.height = textureSize.height;
  68791. this.releaseInternalTexture();
  68792. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  68793. };
  68794. /**
  68795. * Scales the texture
  68796. * @param ratio the scale factor to apply to both width and height
  68797. */
  68798. DynamicTexture.prototype.scale = function (ratio) {
  68799. var textureSize = this.getSize();
  68800. textureSize.width *= ratio;
  68801. textureSize.height *= ratio;
  68802. this._recreate(textureSize);
  68803. };
  68804. /**
  68805. * Resizes the texture
  68806. * @param width the new width
  68807. * @param height the new height
  68808. */
  68809. DynamicTexture.prototype.scaleTo = function (width, height) {
  68810. var textureSize = this.getSize();
  68811. textureSize.width = width;
  68812. textureSize.height = height;
  68813. this._recreate(textureSize);
  68814. };
  68815. /**
  68816. * Gets the context of the canvas used by the texture
  68817. * @returns the canvas context of the dynamic texture
  68818. */
  68819. DynamicTexture.prototype.getContext = function () {
  68820. return this._context;
  68821. };
  68822. /**
  68823. * Clears the texture
  68824. */
  68825. DynamicTexture.prototype.clear = function () {
  68826. var size = this.getSize();
  68827. this._context.fillRect(0, 0, size.width, size.height);
  68828. };
  68829. /**
  68830. * Updates the texture
  68831. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68832. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  68833. */
  68834. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  68835. if (premulAlpha === void 0) { premulAlpha = false; }
  68836. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  68837. };
  68838. /**
  68839. * Draws text onto the texture
  68840. * @param text defines the text to be drawn
  68841. * @param x defines the placement of the text from the left
  68842. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  68843. * @param font defines the font to be used with font-style, font-size, font-name
  68844. * @param color defines the color used for the text
  68845. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  68846. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68847. * @param update defines whether texture is immediately update (default is true)
  68848. */
  68849. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  68850. if (update === void 0) { update = true; }
  68851. var size = this.getSize();
  68852. if (clearColor) {
  68853. this._context.fillStyle = clearColor;
  68854. this._context.fillRect(0, 0, size.width, size.height);
  68855. }
  68856. this._context.font = font;
  68857. if (x === null || x === undefined) {
  68858. var textSize = this._context.measureText(text);
  68859. x = (size.width - textSize.width) / 2;
  68860. }
  68861. if (y === null || y === undefined) {
  68862. var fontSize = parseInt((font.replace(/\D/g, '')));
  68863. y = (size.height / 2) + (fontSize / 3.65);
  68864. }
  68865. this._context.fillStyle = color;
  68866. this._context.fillText(text, x, y);
  68867. if (update) {
  68868. this.update(invertY);
  68869. }
  68870. };
  68871. /**
  68872. * Clones the texture
  68873. * @returns the clone of the texture.
  68874. */
  68875. DynamicTexture.prototype.clone = function () {
  68876. var scene = this.getScene();
  68877. if (!scene) {
  68878. return this;
  68879. }
  68880. var textureSize = this.getSize();
  68881. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  68882. // Base texture
  68883. newTexture.hasAlpha = this.hasAlpha;
  68884. newTexture.level = this.level;
  68885. // Dynamic Texture
  68886. newTexture.wrapU = this.wrapU;
  68887. newTexture.wrapV = this.wrapV;
  68888. return newTexture;
  68889. };
  68890. /**
  68891. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  68892. * @returns a serialized dynamic texture object
  68893. */
  68894. DynamicTexture.prototype.serialize = function () {
  68895. var scene = this.getScene();
  68896. if (scene && !scene.isReady()) {
  68897. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  68898. }
  68899. var serializationObject = _super.prototype.serialize.call(this);
  68900. serializationObject.base64String = this._canvas.toDataURL();
  68901. serializationObject.invertY = this._invertY;
  68902. serializationObject.samplingMode = this.samplingMode;
  68903. return serializationObject;
  68904. };
  68905. /** @hidden */
  68906. DynamicTexture.prototype._rebuild = function () {
  68907. this.update();
  68908. };
  68909. return DynamicTexture;
  68910. }(BABYLON.Texture));
  68911. BABYLON.DynamicTexture = DynamicTexture;
  68912. })(BABYLON || (BABYLON = {}));
  68913. //# sourceMappingURL=babylon.dynamicTexture.js.map
  68914. var BABYLON;
  68915. (function (BABYLON) {
  68916. var VideoTexture = /** @class */ (function (_super) {
  68917. __extends(VideoTexture, _super);
  68918. /**
  68919. * Creates a video texture.
  68920. * Sample : https://doc.babylonjs.com/how_to/video_texture
  68921. * @param {string | null} name optional name, will detect from video source, if not defined
  68922. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  68923. * @param {BABYLON.Scene} scene is obviously the current scene.
  68924. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  68925. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  68926. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  68927. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  68928. */
  68929. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  68930. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68931. if (invertY === void 0) { invertY = false; }
  68932. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68933. if (settings === void 0) { settings = {
  68934. autoPlay: true,
  68935. loop: true,
  68936. autoUpdateTexture: true,
  68937. }; }
  68938. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68939. _this._onUserActionRequestedObservable = null;
  68940. _this._stillImageCaptured = false;
  68941. _this._poster = false;
  68942. _this._createInternalTexture = function () {
  68943. if (_this._texture != null) {
  68944. if (_this._poster) {
  68945. _this._texture.dispose();
  68946. _this._poster = false;
  68947. }
  68948. else {
  68949. return;
  68950. }
  68951. }
  68952. if (!_this._engine.needPOTTextures ||
  68953. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  68954. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68955. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68956. }
  68957. else {
  68958. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68959. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68960. _this._generateMipMaps = false;
  68961. }
  68962. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  68963. if (!_this.video.autoplay) {
  68964. var oldHandler_1 = _this.video.onplaying;
  68965. var error_1 = false;
  68966. _this.video.onplaying = function () {
  68967. _this.video.onplaying = oldHandler_1;
  68968. _this._texture.isReady = true;
  68969. _this._updateInternalTexture();
  68970. if (!error_1) {
  68971. _this.video.pause();
  68972. }
  68973. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68974. _this.onLoadObservable.notifyObservers(_this);
  68975. }
  68976. };
  68977. var playing = _this.video.play();
  68978. if (playing) {
  68979. playing.then(function () {
  68980. // Everything is good.
  68981. })
  68982. .catch(function () {
  68983. error_1 = true;
  68984. // On Chrome for instance, new policies might prevent playing without user interaction.
  68985. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  68986. _this._onUserActionRequestedObservable.notifyObservers(_this);
  68987. }
  68988. });
  68989. }
  68990. else {
  68991. _this.video.onplaying = oldHandler_1;
  68992. _this._texture.isReady = true;
  68993. _this._updateInternalTexture();
  68994. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68995. _this.onLoadObservable.notifyObservers(_this);
  68996. }
  68997. }
  68998. }
  68999. else {
  69000. _this._texture.isReady = true;
  69001. _this._updateInternalTexture();
  69002. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  69003. _this.onLoadObservable.notifyObservers(_this);
  69004. }
  69005. }
  69006. };
  69007. _this.reset = function () {
  69008. if (_this._texture == null) {
  69009. return;
  69010. }
  69011. if (!_this._poster) {
  69012. _this._texture.dispose();
  69013. _this._texture = null;
  69014. }
  69015. };
  69016. _this._updateInternalTexture = function (e) {
  69017. if (_this._texture == null || !_this._texture.isReady) {
  69018. return;
  69019. }
  69020. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  69021. return;
  69022. }
  69023. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  69024. };
  69025. _this._engine = _this.getScene().getEngine();
  69026. _this._generateMipMaps = generateMipMaps;
  69027. _this._samplingMode = samplingMode;
  69028. _this.autoUpdateTexture = settings.autoUpdateTexture;
  69029. _this.name = name || _this._getName(src);
  69030. _this.video = _this._getVideo(src);
  69031. if (settings.poster) {
  69032. _this.video.poster = settings.poster;
  69033. }
  69034. if (settings.autoPlay !== undefined) {
  69035. _this.video.autoplay = settings.autoPlay;
  69036. }
  69037. if (settings.loop !== undefined) {
  69038. _this.video.loop = settings.loop;
  69039. }
  69040. _this.video.setAttribute("playsinline", "");
  69041. _this.video.addEventListener("canplay", _this._createInternalTexture);
  69042. _this.video.addEventListener("paused", _this._updateInternalTexture);
  69043. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  69044. _this.video.addEventListener("emptied", _this.reset);
  69045. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  69046. _this._createInternalTexture();
  69047. }
  69048. if (settings.poster) {
  69049. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  69050. _this._poster = true;
  69051. }
  69052. return _this;
  69053. }
  69054. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  69055. get: function () {
  69056. if (!this._onUserActionRequestedObservable) {
  69057. this._onUserActionRequestedObservable = new BABYLON.Observable();
  69058. }
  69059. return this._onUserActionRequestedObservable;
  69060. },
  69061. enumerable: true,
  69062. configurable: true
  69063. });
  69064. VideoTexture.prototype._getName = function (src) {
  69065. if (src instanceof HTMLVideoElement) {
  69066. return src.currentSrc;
  69067. }
  69068. if (typeof src === "object") {
  69069. return src.toString();
  69070. }
  69071. return src;
  69072. };
  69073. ;
  69074. VideoTexture.prototype._getVideo = function (src) {
  69075. if (src instanceof HTMLVideoElement) {
  69076. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  69077. return src;
  69078. }
  69079. var video = document.createElement("video");
  69080. if (typeof src === "string") {
  69081. BABYLON.Tools.SetCorsBehavior(src, video);
  69082. video.src = src;
  69083. }
  69084. else {
  69085. BABYLON.Tools.SetCorsBehavior(src[0], video);
  69086. src.forEach(function (url) {
  69087. var source = document.createElement("source");
  69088. source.src = url;
  69089. video.appendChild(source);
  69090. });
  69091. }
  69092. return video;
  69093. };
  69094. ;
  69095. /**
  69096. * @hidden Internal method to initiate `update`.
  69097. */
  69098. VideoTexture.prototype._rebuild = function () {
  69099. this.update();
  69100. };
  69101. /**
  69102. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  69103. */
  69104. VideoTexture.prototype.update = function () {
  69105. if (!this.autoUpdateTexture) {
  69106. // Expecting user to call `updateTexture` manually
  69107. return;
  69108. }
  69109. this.updateTexture(true);
  69110. };
  69111. /**
  69112. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  69113. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  69114. */
  69115. VideoTexture.prototype.updateTexture = function (isVisible) {
  69116. if (!isVisible) {
  69117. return;
  69118. }
  69119. if (this.video.paused && this._stillImageCaptured) {
  69120. return;
  69121. }
  69122. this._stillImageCaptured = true;
  69123. this._updateInternalTexture();
  69124. };
  69125. /**
  69126. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  69127. * @param url New url.
  69128. */
  69129. VideoTexture.prototype.updateURL = function (url) {
  69130. this.video.src = url;
  69131. };
  69132. VideoTexture.prototype.dispose = function () {
  69133. _super.prototype.dispose.call(this);
  69134. if (this._onUserActionRequestedObservable) {
  69135. this._onUserActionRequestedObservable.clear();
  69136. this._onUserActionRequestedObservable = null;
  69137. }
  69138. this.video.removeEventListener("canplay", this._createInternalTexture);
  69139. this.video.removeEventListener("paused", this._updateInternalTexture);
  69140. this.video.removeEventListener("seeked", this._updateInternalTexture);
  69141. this.video.removeEventListener("emptied", this.reset);
  69142. this.video.pause();
  69143. };
  69144. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  69145. var video = document.createElement("video");
  69146. video.setAttribute('autoplay', '');
  69147. video.setAttribute('muted', '');
  69148. video.setAttribute('playsinline', '');
  69149. var constraintsDeviceId;
  69150. if (constraints && constraints.deviceId) {
  69151. constraintsDeviceId = {
  69152. exact: constraints.deviceId,
  69153. };
  69154. }
  69155. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  69156. if (navigator.mediaDevices) {
  69157. navigator.mediaDevices.getUserMedia({ video: constraints })
  69158. .then(function (stream) {
  69159. if (video.mozSrcObject !== undefined) {
  69160. // hack for Firefox < 19
  69161. video.mozSrcObject = stream;
  69162. }
  69163. else {
  69164. video.srcObject = stream;
  69165. }
  69166. var onPlaying = function () {
  69167. if (onReady) {
  69168. onReady(new VideoTexture("video", video, scene, true, true));
  69169. }
  69170. video.removeEventListener("playing", onPlaying);
  69171. };
  69172. video.addEventListener("playing", onPlaying);
  69173. video.play();
  69174. })
  69175. .catch(function (err) {
  69176. BABYLON.Tools.Error(err.name);
  69177. });
  69178. }
  69179. else {
  69180. navigator.getUserMedia =
  69181. navigator.getUserMedia ||
  69182. navigator.webkitGetUserMedia ||
  69183. navigator.mozGetUserMedia ||
  69184. navigator.msGetUserMedia;
  69185. if (navigator.getUserMedia) {
  69186. navigator.getUserMedia({
  69187. video: {
  69188. deviceId: constraintsDeviceId,
  69189. width: {
  69190. min: (constraints && constraints.minWidth) || 256,
  69191. max: (constraints && constraints.maxWidth) || 640,
  69192. },
  69193. height: {
  69194. min: (constraints && constraints.minHeight) || 256,
  69195. max: (constraints && constraints.maxHeight) || 480,
  69196. },
  69197. },
  69198. }, function (stream) {
  69199. if (video.mozSrcObject !== undefined) {
  69200. // hack for Firefox < 19
  69201. video.mozSrcObject = stream;
  69202. }
  69203. else {
  69204. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  69205. }
  69206. video.play();
  69207. if (onReady) {
  69208. onReady(new VideoTexture("video", video, scene, true, true));
  69209. }
  69210. }, function (e) {
  69211. BABYLON.Tools.Error(e.name);
  69212. });
  69213. }
  69214. }
  69215. };
  69216. return VideoTexture;
  69217. }(BABYLON.Texture));
  69218. BABYLON.VideoTexture = VideoTexture;
  69219. })(BABYLON || (BABYLON = {}));
  69220. //# sourceMappingURL=babylon.videoTexture.js.map
  69221. var BABYLON;
  69222. (function (BABYLON) {
  69223. var RawTexture = /** @class */ (function (_super) {
  69224. __extends(RawTexture, _super);
  69225. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  69226. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69227. if (invertY === void 0) { invertY = false; }
  69228. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69229. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69230. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69231. _this.format = format;
  69232. _this._engine = scene.getEngine();
  69233. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  69234. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69235. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69236. return _this;
  69237. }
  69238. RawTexture.prototype.update = function (data) {
  69239. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69240. };
  69241. // Statics
  69242. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69243. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69244. if (invertY === void 0) { invertY = false; }
  69245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69246. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  69247. };
  69248. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69249. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69250. if (invertY === void 0) { invertY = false; }
  69251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69252. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  69253. };
  69254. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69255. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69256. if (invertY === void 0) { invertY = false; }
  69257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69258. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  69259. };
  69260. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69261. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69262. if (invertY === void 0) { invertY = false; }
  69263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69264. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69265. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  69266. };
  69267. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69268. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69269. if (invertY === void 0) { invertY = false; }
  69270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69271. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69272. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  69273. };
  69274. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69275. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69276. if (invertY === void 0) { invertY = false; }
  69277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69278. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  69279. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  69280. };
  69281. return RawTexture;
  69282. }(BABYLON.Texture));
  69283. BABYLON.RawTexture = RawTexture;
  69284. })(BABYLON || (BABYLON = {}));
  69285. //# sourceMappingURL=babylon.rawTexture.js.map
  69286. var BABYLON;
  69287. (function (BABYLON) {
  69288. /**
  69289. * Class used to store 3D textures containing user data
  69290. */
  69291. var RawTexture3D = /** @class */ (function (_super) {
  69292. __extends(RawTexture3D, _super);
  69293. /**
  69294. * Create a new RawTexture3D
  69295. * @param data defines the data of the texture
  69296. * @param width defines the width of the texture
  69297. * @param height defines the height of the texture
  69298. * @param depth defines the depth of the texture
  69299. * @param format defines the texture format to use
  69300. * @param scene defines the hosting scene
  69301. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  69302. * @param invertY defines if texture must be stored with Y axis inverted
  69303. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  69304. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  69305. */
  69306. function RawTexture3D(data, width, height, depth,
  69307. /** Gets or sets the texture format to use */
  69308. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  69309. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69310. if (invertY === void 0) { invertY = false; }
  69311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69312. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69313. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69314. _this.format = format;
  69315. _this._engine = scene.getEngine();
  69316. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  69317. _this.is3D = true;
  69318. return _this;
  69319. }
  69320. /**
  69321. * Update the texture with new data
  69322. * @param data defines the data to store in the texture
  69323. */
  69324. RawTexture3D.prototype.update = function (data) {
  69325. if (!this._texture) {
  69326. return;
  69327. }
  69328. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69329. };
  69330. return RawTexture3D;
  69331. }(BABYLON.Texture));
  69332. BABYLON.RawTexture3D = RawTexture3D;
  69333. })(BABYLON || (BABYLON = {}));
  69334. //# sourceMappingURL=babylon.rawTexture3D.js.map
  69335. var BABYLON;
  69336. (function (BABYLON) {
  69337. /**
  69338. * PostProcessManager is used to manage one or more post processes or post process pipelines
  69339. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69340. */
  69341. var PostProcessManager = /** @class */ (function () {
  69342. /**
  69343. * Creates a new instance PostProcess
  69344. * @param scene The scene that the post process is associated with.
  69345. */
  69346. function PostProcessManager(scene) {
  69347. this._vertexBuffers = {};
  69348. this._scene = scene;
  69349. }
  69350. PostProcessManager.prototype._prepareBuffers = function () {
  69351. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  69352. return;
  69353. }
  69354. // VBO
  69355. var vertices = [];
  69356. vertices.push(1, 1);
  69357. vertices.push(-1, 1);
  69358. vertices.push(-1, -1);
  69359. vertices.push(1, -1);
  69360. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69361. this._buildIndexBuffer();
  69362. };
  69363. PostProcessManager.prototype._buildIndexBuffer = function () {
  69364. // Indices
  69365. var indices = [];
  69366. indices.push(0);
  69367. indices.push(1);
  69368. indices.push(2);
  69369. indices.push(0);
  69370. indices.push(2);
  69371. indices.push(3);
  69372. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  69373. };
  69374. /**
  69375. * Rebuilds the vertex buffers of the manager.
  69376. * @hidden
  69377. */
  69378. PostProcessManager.prototype._rebuild = function () {
  69379. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69380. if (!vb) {
  69381. return;
  69382. }
  69383. vb._rebuild();
  69384. this._buildIndexBuffer();
  69385. };
  69386. // Methods
  69387. /**
  69388. * Prepares a frame to be run through a post process.
  69389. * @param sourceTexture The input texture to the post procesess. (default: null)
  69390. * @param postProcesses An array of post processes to be run. (default: null)
  69391. * @returns True if the post processes were able to be run.
  69392. * @hidden
  69393. */
  69394. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  69395. if (sourceTexture === void 0) { sourceTexture = null; }
  69396. if (postProcesses === void 0) { postProcesses = null; }
  69397. var camera = this._scene.activeCamera;
  69398. if (!camera) {
  69399. return false;
  69400. }
  69401. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69402. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69403. return false;
  69404. }
  69405. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  69406. return true;
  69407. };
  69408. /**
  69409. * Manually render a set of post processes to a texture.
  69410. * @param postProcesses An array of post processes to be run.
  69411. * @param targetTexture The target texture to render to.
  69412. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  69413. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  69414. * @param lodLevel defines which lod of the texture to render to
  69415. */
  69416. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  69417. if (targetTexture === void 0) { targetTexture = null; }
  69418. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69419. if (faceIndex === void 0) { faceIndex = 0; }
  69420. if (lodLevel === void 0) { lodLevel = 0; }
  69421. var engine = this._scene.getEngine();
  69422. for (var index = 0; index < postProcesses.length; index++) {
  69423. if (index < postProcesses.length - 1) {
  69424. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  69425. }
  69426. else {
  69427. if (targetTexture) {
  69428. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  69429. }
  69430. else {
  69431. engine.restoreDefaultFramebuffer();
  69432. }
  69433. }
  69434. var pp = postProcesses[index];
  69435. var effect = pp.apply();
  69436. if (effect) {
  69437. pp.onBeforeRenderObservable.notifyObservers(effect);
  69438. // VBOs
  69439. this._prepareBuffers();
  69440. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69441. // Draw order
  69442. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69443. pp.onAfterRenderObservable.notifyObservers(effect);
  69444. }
  69445. }
  69446. // Restore depth buffer
  69447. engine.setDepthBuffer(true);
  69448. engine.setDepthWrite(true);
  69449. };
  69450. /**
  69451. * Finalize the result of the output of the postprocesses.
  69452. * @param doNotPresent If true the result will not be displayed to the screen.
  69453. * @param targetTexture The target texture to render to.
  69454. * @param faceIndex The index of the face to bind the target texture to.
  69455. * @param postProcesses The array of post processes to render.
  69456. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  69457. * @hidden
  69458. */
  69459. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  69460. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69461. var camera = this._scene.activeCamera;
  69462. if (!camera) {
  69463. return;
  69464. }
  69465. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69466. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69467. return;
  69468. }
  69469. var engine = this._scene.getEngine();
  69470. for (var index = 0, len = postProcesses.length; index < len; index++) {
  69471. var pp = postProcesses[index];
  69472. if (index < len - 1) {
  69473. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  69474. }
  69475. else {
  69476. if (targetTexture) {
  69477. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  69478. pp._outputTexture = targetTexture;
  69479. }
  69480. else {
  69481. engine.restoreDefaultFramebuffer();
  69482. pp._outputTexture = null;
  69483. }
  69484. }
  69485. if (doNotPresent) {
  69486. break;
  69487. }
  69488. var effect = pp.apply();
  69489. if (effect) {
  69490. pp.onBeforeRenderObservable.notifyObservers(effect);
  69491. // VBOs
  69492. this._prepareBuffers();
  69493. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69494. // Draw order
  69495. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69496. pp.onAfterRenderObservable.notifyObservers(effect);
  69497. }
  69498. }
  69499. // Restore states
  69500. engine.setDepthBuffer(true);
  69501. engine.setDepthWrite(true);
  69502. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69503. };
  69504. /**
  69505. * Disposes of the post process manager.
  69506. */
  69507. PostProcessManager.prototype.dispose = function () {
  69508. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69509. if (buffer) {
  69510. buffer.dispose();
  69511. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69512. }
  69513. if (this._indexBuffer) {
  69514. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69515. this._indexBuffer = null;
  69516. }
  69517. };
  69518. return PostProcessManager;
  69519. }());
  69520. BABYLON.PostProcessManager = PostProcessManager;
  69521. })(BABYLON || (BABYLON = {}));
  69522. //# sourceMappingURL=babylon.postProcessManager.js.map
  69523. var BABYLON;
  69524. (function (BABYLON) {
  69525. /**
  69526. * PostProcess can be used to apply a shader to a texture after it has been rendered
  69527. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69528. */
  69529. var PostProcess = /** @class */ (function () {
  69530. /**
  69531. * Creates a new instance PostProcess
  69532. * @param name The name of the PostProcess.
  69533. * @param fragmentUrl The url of the fragment shader to be used.
  69534. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  69535. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  69536. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69537. * @param camera The camera to apply the render pass to.
  69538. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69539. * @param engine The engine which the post process will be applied. (default: current engine)
  69540. * @param reusable If the post process can be reused on the same frame. (default: false)
  69541. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  69542. * @param textureType Type of textures used when performing the post process. (default: 0)
  69543. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  69544. * @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
  69545. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  69546. */
  69547. function PostProcess(
  69548. /** Name of the PostProcess. */
  69549. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  69550. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  69551. if (defines === void 0) { defines = null; }
  69552. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69553. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  69554. if (blockCompilation === void 0) { blockCompilation = false; }
  69555. this.name = name;
  69556. /**
  69557. * Width of the texture to apply the post process on
  69558. */
  69559. this.width = -1;
  69560. /**
  69561. * Height of the texture to apply the post process on
  69562. */
  69563. this.height = -1;
  69564. /**
  69565. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  69566. * @hidden
  69567. */
  69568. this._outputTexture = null;
  69569. /**
  69570. * If the buffer needs to be cleared before applying the post process. (default: true)
  69571. * Should be set to false if shader will overwrite all previous pixels.
  69572. */
  69573. this.autoClear = true;
  69574. /**
  69575. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  69576. */
  69577. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  69578. /**
  69579. * Animations to be used for the post processing
  69580. */
  69581. this.animations = new Array();
  69582. /**
  69583. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  69584. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  69585. */
  69586. this.enablePixelPerfectMode = false;
  69587. /**
  69588. * Force the postprocess to be applied without taking in account viewport
  69589. */
  69590. this.forceFullscreenViewport = true;
  69591. /**
  69592. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  69593. *
  69594. * | Value | Type | Description |
  69595. * | ----- | ----------------------------------- | ----------- |
  69596. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  69597. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  69598. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  69599. *
  69600. */
  69601. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  69602. /**
  69603. * Force textures to be a power of two (default: false)
  69604. */
  69605. this.alwaysForcePOT = false;
  69606. this._samples = 1;
  69607. /**
  69608. * Modify the scale of the post process to be the same as the viewport (default: false)
  69609. */
  69610. this.adaptScaleToCurrentViewport = false;
  69611. this._reusable = false;
  69612. /**
  69613. * Smart array of input and output textures for the post process.
  69614. * @hidden
  69615. */
  69616. this._textures = new BABYLON.SmartArray(2);
  69617. /**
  69618. * The index in _textures that corresponds to the output texture.
  69619. * @hidden
  69620. */
  69621. this._currentRenderTextureInd = 0;
  69622. this._scaleRatio = new BABYLON.Vector2(1, 1);
  69623. this._texelSize = BABYLON.Vector2.Zero();
  69624. // Events
  69625. /**
  69626. * An event triggered when the postprocess is activated.
  69627. */
  69628. this.onActivateObservable = new BABYLON.Observable();
  69629. /**
  69630. * An event triggered when the postprocess changes its size.
  69631. */
  69632. this.onSizeChangedObservable = new BABYLON.Observable();
  69633. /**
  69634. * An event triggered when the postprocess applies its effect.
  69635. */
  69636. this.onApplyObservable = new BABYLON.Observable();
  69637. /**
  69638. * An event triggered before rendering the postprocess
  69639. */
  69640. this.onBeforeRenderObservable = new BABYLON.Observable();
  69641. /**
  69642. * An event triggered after rendering the postprocess
  69643. */
  69644. this.onAfterRenderObservable = new BABYLON.Observable();
  69645. if (camera != null) {
  69646. this._camera = camera;
  69647. this._scene = camera.getScene();
  69648. camera.attachPostProcess(this);
  69649. this._engine = this._scene.getEngine();
  69650. this._scene.postProcesses.push(this);
  69651. }
  69652. else if (engine) {
  69653. this._engine = engine;
  69654. this._engine.postProcesses.push(this);
  69655. }
  69656. this._options = options;
  69657. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  69658. this._reusable = reusable || false;
  69659. this._textureType = textureType;
  69660. this._samplers = samplers || [];
  69661. this._samplers.push("textureSampler");
  69662. this._fragmentUrl = fragmentUrl;
  69663. this._vertexUrl = vertexUrl;
  69664. this._parameters = parameters || [];
  69665. this._parameters.push("scale");
  69666. this._indexParameters = indexParameters;
  69667. if (!blockCompilation) {
  69668. this.updateEffect(defines);
  69669. }
  69670. }
  69671. Object.defineProperty(PostProcess.prototype, "samples", {
  69672. /**
  69673. * Number of sample textures (default: 1)
  69674. */
  69675. get: function () {
  69676. return this._samples;
  69677. },
  69678. set: function (n) {
  69679. var _this = this;
  69680. this._samples = n;
  69681. this._textures.forEach(function (texture) {
  69682. if (texture.samples !== _this._samples) {
  69683. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  69684. }
  69685. });
  69686. },
  69687. enumerable: true,
  69688. configurable: true
  69689. });
  69690. Object.defineProperty(PostProcess.prototype, "onActivate", {
  69691. /**
  69692. * A function that is added to the onActivateObservable
  69693. */
  69694. set: function (callback) {
  69695. if (this._onActivateObserver) {
  69696. this.onActivateObservable.remove(this._onActivateObserver);
  69697. }
  69698. if (callback) {
  69699. this._onActivateObserver = this.onActivateObservable.add(callback);
  69700. }
  69701. },
  69702. enumerable: true,
  69703. configurable: true
  69704. });
  69705. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  69706. /**
  69707. * A function that is added to the onSizeChangedObservable
  69708. */
  69709. set: function (callback) {
  69710. if (this._onSizeChangedObserver) {
  69711. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  69712. }
  69713. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  69714. },
  69715. enumerable: true,
  69716. configurable: true
  69717. });
  69718. Object.defineProperty(PostProcess.prototype, "onApply", {
  69719. /**
  69720. * A function that is added to the onApplyObservable
  69721. */
  69722. set: function (callback) {
  69723. if (this._onApplyObserver) {
  69724. this.onApplyObservable.remove(this._onApplyObserver);
  69725. }
  69726. this._onApplyObserver = this.onApplyObservable.add(callback);
  69727. },
  69728. enumerable: true,
  69729. configurable: true
  69730. });
  69731. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  69732. /**
  69733. * A function that is added to the onBeforeRenderObservable
  69734. */
  69735. set: function (callback) {
  69736. if (this._onBeforeRenderObserver) {
  69737. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69738. }
  69739. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69740. },
  69741. enumerable: true,
  69742. configurable: true
  69743. });
  69744. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  69745. /**
  69746. * A function that is added to the onAfterRenderObservable
  69747. */
  69748. set: function (callback) {
  69749. if (this._onAfterRenderObserver) {
  69750. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69751. }
  69752. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69753. },
  69754. enumerable: true,
  69755. configurable: true
  69756. });
  69757. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  69758. /**
  69759. * 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
  69760. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  69761. */
  69762. get: function () {
  69763. return this._textures.data[this._currentRenderTextureInd];
  69764. },
  69765. set: function (value) {
  69766. this._forcedOutputTexture = value;
  69767. },
  69768. enumerable: true,
  69769. configurable: true
  69770. });
  69771. /**
  69772. * Gets the camera which post process is applied to.
  69773. * @returns The camera the post process is applied to.
  69774. */
  69775. PostProcess.prototype.getCamera = function () {
  69776. return this._camera;
  69777. };
  69778. Object.defineProperty(PostProcess.prototype, "texelSize", {
  69779. /**
  69780. * Gets the texel size of the postprocess.
  69781. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  69782. */
  69783. get: function () {
  69784. if (this._shareOutputWithPostProcess) {
  69785. return this._shareOutputWithPostProcess.texelSize;
  69786. }
  69787. if (this._forcedOutputTexture) {
  69788. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  69789. }
  69790. return this._texelSize;
  69791. },
  69792. enumerable: true,
  69793. configurable: true
  69794. });
  69795. /**
  69796. * Gets the engine which this post process belongs to.
  69797. * @returns The engine the post process was enabled with.
  69798. */
  69799. PostProcess.prototype.getEngine = function () {
  69800. return this._engine;
  69801. };
  69802. /**
  69803. * The effect that is created when initializing the post process.
  69804. * @returns The created effect corrisponding the the postprocess.
  69805. */
  69806. PostProcess.prototype.getEffect = function () {
  69807. return this._effect;
  69808. };
  69809. /**
  69810. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  69811. * @param postProcess The post process to share the output with.
  69812. * @returns This post process.
  69813. */
  69814. PostProcess.prototype.shareOutputWith = function (postProcess) {
  69815. this._disposeTextures();
  69816. this._shareOutputWithPostProcess = postProcess;
  69817. return this;
  69818. };
  69819. /**
  69820. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  69821. * This should be called if the post process that shares output with this post process is disabled/disposed.
  69822. */
  69823. PostProcess.prototype.useOwnOutput = function () {
  69824. if (this._textures.length == 0) {
  69825. this._textures = new BABYLON.SmartArray(2);
  69826. }
  69827. this._shareOutputWithPostProcess = null;
  69828. };
  69829. /**
  69830. * Updates the effect with the current post process compile time values and recompiles the shader.
  69831. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69832. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69833. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69834. * @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
  69835. * @param onCompiled Called when the shader has been compiled.
  69836. * @param onError Called if there is an error when compiling a shader.
  69837. */
  69838. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69839. if (defines === void 0) { defines = null; }
  69840. if (uniforms === void 0) { uniforms = null; }
  69841. if (samplers === void 0) { samplers = null; }
  69842. 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);
  69843. };
  69844. /**
  69845. * The post process is reusable if it can be used multiple times within one frame.
  69846. * @returns If the post process is reusable
  69847. */
  69848. PostProcess.prototype.isReusable = function () {
  69849. return this._reusable;
  69850. };
  69851. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  69852. PostProcess.prototype.markTextureDirty = function () {
  69853. this.width = -1;
  69854. };
  69855. /**
  69856. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  69857. * 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.
  69858. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  69859. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  69860. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  69861. * @returns The target texture that was bound to be written to.
  69862. */
  69863. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  69864. var _this = this;
  69865. if (sourceTexture === void 0) { sourceTexture = null; }
  69866. camera = camera || this._camera;
  69867. var scene = camera.getScene();
  69868. var engine = scene.getEngine();
  69869. var maxSize = engine.getCaps().maxTextureSize;
  69870. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  69871. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  69872. // 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
  69873. var webVRCamera = camera.parent;
  69874. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  69875. requiredWidth /= 2;
  69876. }
  69877. var desiredWidth = (this._options.width || requiredWidth);
  69878. var desiredHeight = this._options.height || requiredHeight;
  69879. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  69880. if (this.adaptScaleToCurrentViewport) {
  69881. var currentViewport = engine.currentViewport;
  69882. if (currentViewport) {
  69883. desiredWidth *= currentViewport.width;
  69884. desiredHeight *= currentViewport.height;
  69885. }
  69886. }
  69887. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  69888. if (!this._options.width) {
  69889. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  69890. }
  69891. if (!this._options.height) {
  69892. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  69893. }
  69894. }
  69895. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  69896. if (this._textures.length > 0) {
  69897. for (var i = 0; i < this._textures.length; i++) {
  69898. this._engine._releaseTexture(this._textures.data[i]);
  69899. }
  69900. this._textures.reset();
  69901. }
  69902. this.width = desiredWidth;
  69903. this.height = desiredHeight;
  69904. var textureSize = { width: this.width, height: this.height };
  69905. var textureOptions = {
  69906. generateMipMaps: false,
  69907. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  69908. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  69909. samplingMode: this.renderTargetSamplingMode,
  69910. type: this._textureType
  69911. };
  69912. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69913. if (this._reusable) {
  69914. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69915. }
  69916. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  69917. this.onSizeChangedObservable.notifyObservers(this);
  69918. }
  69919. this._textures.forEach(function (texture) {
  69920. if (texture.samples !== _this.samples) {
  69921. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  69922. }
  69923. });
  69924. }
  69925. var target;
  69926. if (this._shareOutputWithPostProcess) {
  69927. target = this._shareOutputWithPostProcess.inputTexture;
  69928. }
  69929. else if (this._forcedOutputTexture) {
  69930. target = this._forcedOutputTexture;
  69931. this.width = this._forcedOutputTexture.width;
  69932. this.height = this._forcedOutputTexture.height;
  69933. }
  69934. else {
  69935. target = this.inputTexture;
  69936. }
  69937. // Bind the input of this post process to be used as the output of the previous post process.
  69938. if (this.enablePixelPerfectMode) {
  69939. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  69940. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  69941. }
  69942. else {
  69943. this._scaleRatio.copyFromFloats(1, 1);
  69944. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  69945. }
  69946. this.onActivateObservable.notifyObservers(camera);
  69947. // Clear
  69948. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  69949. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  69950. }
  69951. if (this._reusable) {
  69952. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  69953. }
  69954. return target;
  69955. };
  69956. Object.defineProperty(PostProcess.prototype, "isSupported", {
  69957. /**
  69958. * If the post process is supported.
  69959. */
  69960. get: function () {
  69961. return this._effect.isSupported;
  69962. },
  69963. enumerable: true,
  69964. configurable: true
  69965. });
  69966. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  69967. /**
  69968. * The aspect ratio of the output texture.
  69969. */
  69970. get: function () {
  69971. if (this._shareOutputWithPostProcess) {
  69972. return this._shareOutputWithPostProcess.aspectRatio;
  69973. }
  69974. if (this._forcedOutputTexture) {
  69975. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  69976. }
  69977. return this.width / this.height;
  69978. },
  69979. enumerable: true,
  69980. configurable: true
  69981. });
  69982. /**
  69983. * Get a value indicating if the post-process is ready to be used
  69984. * @returns true if the post-process is ready (shader is compiled)
  69985. */
  69986. PostProcess.prototype.isReady = function () {
  69987. return this._effect && this._effect.isReady();
  69988. };
  69989. /**
  69990. * Binds all textures and uniforms to the shader, this will be run on every pass.
  69991. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  69992. */
  69993. PostProcess.prototype.apply = function () {
  69994. // Check
  69995. if (!this._effect || !this._effect.isReady())
  69996. return null;
  69997. // States
  69998. this._engine.enableEffect(this._effect);
  69999. this._engine.setState(false);
  70000. this._engine.setDepthBuffer(false);
  70001. this._engine.setDepthWrite(false);
  70002. // Alpha
  70003. this._engine.setAlphaMode(this.alphaMode);
  70004. if (this.alphaConstants) {
  70005. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  70006. }
  70007. // Bind the output texture of the preivous post process as the input to this post process.
  70008. var source;
  70009. if (this._shareOutputWithPostProcess) {
  70010. source = this._shareOutputWithPostProcess.inputTexture;
  70011. }
  70012. else if (this._forcedOutputTexture) {
  70013. source = this._forcedOutputTexture;
  70014. }
  70015. else {
  70016. source = this.inputTexture;
  70017. }
  70018. this._effect._bindTexture("textureSampler", source);
  70019. // Parameters
  70020. this._effect.setVector2("scale", this._scaleRatio);
  70021. this.onApplyObservable.notifyObservers(this._effect);
  70022. return this._effect;
  70023. };
  70024. PostProcess.prototype._disposeTextures = function () {
  70025. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  70026. return;
  70027. }
  70028. if (this._textures.length > 0) {
  70029. for (var i = 0; i < this._textures.length; i++) {
  70030. this._engine._releaseTexture(this._textures.data[i]);
  70031. }
  70032. }
  70033. this._textures.dispose();
  70034. };
  70035. /**
  70036. * Disposes the post process.
  70037. * @param camera The camera to dispose the post process on.
  70038. */
  70039. PostProcess.prototype.dispose = function (camera) {
  70040. camera = camera || this._camera;
  70041. this._disposeTextures();
  70042. if (this._scene) {
  70043. var index_1 = this._scene.postProcesses.indexOf(this);
  70044. if (index_1 !== -1) {
  70045. this._scene.postProcesses.splice(index_1, 1);
  70046. }
  70047. }
  70048. else {
  70049. var index_2 = this._engine.postProcesses.indexOf(this);
  70050. if (index_2 !== -1) {
  70051. this._engine.postProcesses.splice(index_2, 1);
  70052. }
  70053. }
  70054. if (!camera) {
  70055. return;
  70056. }
  70057. camera.detachPostProcess(this);
  70058. var index = camera._postProcesses.indexOf(this);
  70059. if (index === 0 && camera._postProcesses.length > 0) {
  70060. var firstPostProcess = this._camera._getFirstPostProcess();
  70061. if (firstPostProcess) {
  70062. firstPostProcess.markTextureDirty();
  70063. }
  70064. }
  70065. this.onActivateObservable.clear();
  70066. this.onAfterRenderObservable.clear();
  70067. this.onApplyObservable.clear();
  70068. this.onBeforeRenderObservable.clear();
  70069. this.onSizeChangedObservable.clear();
  70070. };
  70071. return PostProcess;
  70072. }());
  70073. BABYLON.PostProcess = PostProcess;
  70074. })(BABYLON || (BABYLON = {}));
  70075. //# sourceMappingURL=babylon.postProcess.js.map
  70076. var BABYLON;
  70077. (function (BABYLON) {
  70078. var PassPostProcess = /** @class */ (function (_super) {
  70079. __extends(PassPostProcess, _super);
  70080. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70081. if (camera === void 0) { camera = null; }
  70082. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70083. if (blockCompilation === void 0) { blockCompilation = false; }
  70084. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  70085. }
  70086. return PassPostProcess;
  70087. }(BABYLON.PostProcess));
  70088. BABYLON.PassPostProcess = PassPostProcess;
  70089. })(BABYLON || (BABYLON = {}));
  70090. //# sourceMappingURL=babylon.passPostProcess.js.map
  70091. var __assign = (this && this.__assign) || function () {
  70092. __assign = Object.assign || function(t) {
  70093. for (var s, i = 1, n = arguments.length; i < n; i++) {
  70094. s = arguments[i];
  70095. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  70096. t[p] = s[p];
  70097. }
  70098. return t;
  70099. };
  70100. return __assign.apply(this, arguments);
  70101. };
  70102. var BABYLON;
  70103. (function (BABYLON) {
  70104. /**
  70105. * Default implementation IShadowGenerator.
  70106. * This is the main object responsible of generating shadows in the framework.
  70107. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  70108. */
  70109. var ShadowGenerator = /** @class */ (function () {
  70110. /**
  70111. * Creates a ShadowGenerator object.
  70112. * A ShadowGenerator is the required tool to use the shadows.
  70113. * Each light casting shadows needs to use its own ShadowGenerator.
  70114. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  70115. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  70116. * @param light The light object generating the shadows.
  70117. * @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.
  70118. */
  70119. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  70120. this._bias = 0.00005;
  70121. this._normalBias = 0;
  70122. this._blurBoxOffset = 1;
  70123. this._blurScale = 2;
  70124. this._blurKernel = 1;
  70125. this._useKernelBlur = false;
  70126. this._filter = ShadowGenerator.FILTER_NONE;
  70127. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  70128. this._contactHardeningLightSizeUVRatio = 0.1;
  70129. this._darkness = 0;
  70130. this._transparencyShadow = false;
  70131. /**
  70132. * Controls the extent to which the shadows fade out at the edge of the frustum
  70133. * Used only by directionals and spots
  70134. */
  70135. this.frustumEdgeFalloff = 0;
  70136. /**
  70137. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  70138. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  70139. * It might on the other hand introduce peter panning.
  70140. */
  70141. this.forceBackFacesOnly = false;
  70142. this._lightDirection = BABYLON.Vector3.Zero();
  70143. this._viewMatrix = BABYLON.Matrix.Zero();
  70144. this._projectionMatrix = BABYLON.Matrix.Zero();
  70145. this._transformMatrix = BABYLON.Matrix.Zero();
  70146. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70147. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70148. this._currentFaceIndex = 0;
  70149. this._currentFaceIndexCache = 0;
  70150. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  70151. this._mapSize = mapSize;
  70152. this._light = light;
  70153. this._scene = light.getScene();
  70154. light._shadowGenerator = this;
  70155. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  70156. if (!component) {
  70157. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  70158. this._scene._addComponent(component);
  70159. }
  70160. // Texture type fallback from float to int if not supported.
  70161. var caps = this._scene.getEngine().getCaps();
  70162. if (!useFullFloatFirst) {
  70163. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  70164. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70165. }
  70166. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  70167. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70168. }
  70169. else {
  70170. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70171. }
  70172. }
  70173. else {
  70174. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  70175. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70176. }
  70177. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  70178. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70179. }
  70180. else {
  70181. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70182. }
  70183. }
  70184. this._initializeGenerator();
  70185. this._applyFilterValues();
  70186. }
  70187. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  70188. /**
  70189. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  70190. */
  70191. get: function () {
  70192. return this._bias;
  70193. },
  70194. /**
  70195. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  70196. */
  70197. set: function (bias) {
  70198. this._bias = bias;
  70199. },
  70200. enumerable: true,
  70201. configurable: true
  70202. });
  70203. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  70204. /**
  70205. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  70206. */
  70207. get: function () {
  70208. return this._normalBias;
  70209. },
  70210. /**
  70211. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  70212. */
  70213. set: function (normalBias) {
  70214. this._normalBias = normalBias;
  70215. },
  70216. enumerable: true,
  70217. configurable: true
  70218. });
  70219. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  70220. /**
  70221. * Gets the blur box offset: offset applied during the blur pass.
  70222. * Only usefull if useKernelBlur = false
  70223. */
  70224. get: function () {
  70225. return this._blurBoxOffset;
  70226. },
  70227. /**
  70228. * Sets the blur box offset: offset applied during the blur pass.
  70229. * Only usefull if useKernelBlur = false
  70230. */
  70231. set: function (value) {
  70232. if (this._blurBoxOffset === value) {
  70233. return;
  70234. }
  70235. this._blurBoxOffset = value;
  70236. this._disposeBlurPostProcesses();
  70237. },
  70238. enumerable: true,
  70239. configurable: true
  70240. });
  70241. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  70242. /**
  70243. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  70244. * 2 means half of the size.
  70245. */
  70246. get: function () {
  70247. return this._blurScale;
  70248. },
  70249. /**
  70250. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  70251. * 2 means half of the size.
  70252. */
  70253. set: function (value) {
  70254. if (this._blurScale === value) {
  70255. return;
  70256. }
  70257. this._blurScale = value;
  70258. this._disposeBlurPostProcesses();
  70259. },
  70260. enumerable: true,
  70261. configurable: true
  70262. });
  70263. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  70264. /**
  70265. * Gets the blur kernel: kernel size of the blur pass.
  70266. * Only usefull if useKernelBlur = true
  70267. */
  70268. get: function () {
  70269. return this._blurKernel;
  70270. },
  70271. /**
  70272. * Sets the blur kernel: kernel size of the blur pass.
  70273. * Only usefull if useKernelBlur = true
  70274. */
  70275. set: function (value) {
  70276. if (this._blurKernel === value) {
  70277. return;
  70278. }
  70279. this._blurKernel = value;
  70280. this._disposeBlurPostProcesses();
  70281. },
  70282. enumerable: true,
  70283. configurable: true
  70284. });
  70285. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  70286. /**
  70287. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  70288. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70289. */
  70290. get: function () {
  70291. return this._useKernelBlur;
  70292. },
  70293. /**
  70294. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  70295. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70296. */
  70297. set: function (value) {
  70298. if (this._useKernelBlur === value) {
  70299. return;
  70300. }
  70301. this._useKernelBlur = value;
  70302. this._disposeBlurPostProcesses();
  70303. },
  70304. enumerable: true,
  70305. configurable: true
  70306. });
  70307. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  70308. /**
  70309. * Gets the depth scale used in ESM mode.
  70310. */
  70311. get: function () {
  70312. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  70313. },
  70314. /**
  70315. * Sets the depth scale used in ESM mode.
  70316. * This can override the scale stored on the light.
  70317. */
  70318. set: function (value) {
  70319. this._depthScale = value;
  70320. },
  70321. enumerable: true,
  70322. configurable: true
  70323. });
  70324. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  70325. /**
  70326. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  70327. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70328. */
  70329. get: function () {
  70330. return this._filter;
  70331. },
  70332. /**
  70333. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  70334. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70335. */
  70336. set: function (value) {
  70337. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  70338. if (this._light.needCube()) {
  70339. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70340. this.useExponentialShadowMap = true;
  70341. return;
  70342. }
  70343. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70344. this.useCloseExponentialShadowMap = true;
  70345. return;
  70346. }
  70347. // PCF on cubemap would also be expensive
  70348. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70349. this.usePoissonSampling = true;
  70350. return;
  70351. }
  70352. }
  70353. // Weblg1 fallback for PCF.
  70354. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70355. if (this._scene.getEngine().webGLVersion === 1) {
  70356. this.usePoissonSampling = true;
  70357. return;
  70358. }
  70359. }
  70360. if (this._filter === value) {
  70361. return;
  70362. }
  70363. this._filter = value;
  70364. this._disposeBlurPostProcesses();
  70365. this._applyFilterValues();
  70366. this._light._markMeshesAsLightDirty();
  70367. },
  70368. enumerable: true,
  70369. configurable: true
  70370. });
  70371. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  70372. /**
  70373. * Gets if the current filter is set to Poisson Sampling.
  70374. */
  70375. get: function () {
  70376. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  70377. },
  70378. /**
  70379. * Sets the current filter to Poisson Sampling.
  70380. */
  70381. set: function (value) {
  70382. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  70383. return;
  70384. }
  70385. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  70386. },
  70387. enumerable: true,
  70388. configurable: true
  70389. });
  70390. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  70391. /**
  70392. * Gets if the current filter is set to VSM.
  70393. * DEPRECATED. Should use useExponentialShadowMap instead.
  70394. */
  70395. get: function () {
  70396. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70397. return this.useExponentialShadowMap;
  70398. },
  70399. /**
  70400. * Sets the current filter is to VSM.
  70401. * DEPRECATED. Should use useExponentialShadowMap instead.
  70402. */
  70403. set: function (value) {
  70404. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70405. this.useExponentialShadowMap = value;
  70406. },
  70407. enumerable: true,
  70408. configurable: true
  70409. });
  70410. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  70411. /**
  70412. * Gets if the current filter is set to blurred VSM.
  70413. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70414. */
  70415. get: function () {
  70416. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70417. return this.useBlurExponentialShadowMap;
  70418. },
  70419. /**
  70420. * Sets the current filter is to blurred VSM.
  70421. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70422. */
  70423. set: function (value) {
  70424. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70425. this.useBlurExponentialShadowMap = value;
  70426. },
  70427. enumerable: true,
  70428. configurable: true
  70429. });
  70430. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  70431. /**
  70432. * Gets if the current filter is set to ESM.
  70433. */
  70434. get: function () {
  70435. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  70436. },
  70437. /**
  70438. * Sets the current filter is to ESM.
  70439. */
  70440. set: function (value) {
  70441. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  70442. return;
  70443. }
  70444. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70445. },
  70446. enumerable: true,
  70447. configurable: true
  70448. });
  70449. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  70450. /**
  70451. * Gets if the current filter is set to filtered ESM.
  70452. */
  70453. get: function () {
  70454. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  70455. },
  70456. /**
  70457. * Gets if the current filter is set to filtered ESM.
  70458. */
  70459. set: function (value) {
  70460. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70461. return;
  70462. }
  70463. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70464. },
  70465. enumerable: true,
  70466. configurable: true
  70467. });
  70468. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  70469. /**
  70470. * Gets if the current filter is set to "close ESM" (using the inverse of the
  70471. * exponential to prevent steep falloff artifacts).
  70472. */
  70473. get: function () {
  70474. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  70475. },
  70476. /**
  70477. * Sets the current filter to "close ESM" (using the inverse of the
  70478. * exponential to prevent steep falloff artifacts).
  70479. */
  70480. set: function (value) {
  70481. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  70482. return;
  70483. }
  70484. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70485. },
  70486. enumerable: true,
  70487. configurable: true
  70488. });
  70489. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  70490. /**
  70491. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  70492. * exponential to prevent steep falloff artifacts).
  70493. */
  70494. get: function () {
  70495. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  70496. },
  70497. /**
  70498. * Sets the current filter to filtered "close ESM" (using the inverse of the
  70499. * exponential to prevent steep falloff artifacts).
  70500. */
  70501. set: function (value) {
  70502. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70503. return;
  70504. }
  70505. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70506. },
  70507. enumerable: true,
  70508. configurable: true
  70509. });
  70510. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  70511. /**
  70512. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  70513. */
  70514. get: function () {
  70515. return this.filter === ShadowGenerator.FILTER_PCF;
  70516. },
  70517. /**
  70518. * Sets the current filter to "PCF" (percentage closer filtering).
  70519. */
  70520. set: function (value) {
  70521. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  70522. return;
  70523. }
  70524. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  70525. },
  70526. enumerable: true,
  70527. configurable: true
  70528. });
  70529. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  70530. /**
  70531. * Gets the PCF or PCSS Quality.
  70532. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70533. */
  70534. get: function () {
  70535. return this._filteringQuality;
  70536. },
  70537. /**
  70538. * Sets the PCF or PCSS Quality.
  70539. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70540. */
  70541. set: function (filteringQuality) {
  70542. this._filteringQuality = filteringQuality;
  70543. },
  70544. enumerable: true,
  70545. configurable: true
  70546. });
  70547. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  70548. /**
  70549. * Gets if the current filter is set to "PCSS" (contact hardening).
  70550. */
  70551. get: function () {
  70552. return this.filter === ShadowGenerator.FILTER_PCSS;
  70553. },
  70554. /**
  70555. * Sets the current filter to "PCSS" (contact hardening).
  70556. */
  70557. set: function (value) {
  70558. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  70559. return;
  70560. }
  70561. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  70562. },
  70563. enumerable: true,
  70564. configurable: true
  70565. });
  70566. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  70567. /**
  70568. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70569. * Using a ratio helps keeping shape stability independently of the map size.
  70570. *
  70571. * It does not account for the light projection as it was having too much
  70572. * instability during the light setup or during light position changes.
  70573. *
  70574. * Only valid if useContactHardeningShadow is true.
  70575. */
  70576. get: function () {
  70577. return this._contactHardeningLightSizeUVRatio;
  70578. },
  70579. /**
  70580. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70581. * Using a ratio helps keeping shape stability independently of the map size.
  70582. *
  70583. * It does not account for the light projection as it was having too much
  70584. * instability during the light setup or during light position changes.
  70585. *
  70586. * Only valid if useContactHardeningShadow is true.
  70587. */
  70588. set: function (contactHardeningLightSizeUVRatio) {
  70589. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  70590. },
  70591. enumerable: true,
  70592. configurable: true
  70593. });
  70594. /**
  70595. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  70596. * 0 means strongest and 1 would means no shadow.
  70597. * @returns the darkness.
  70598. */
  70599. ShadowGenerator.prototype.getDarkness = function () {
  70600. return this._darkness;
  70601. };
  70602. /**
  70603. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  70604. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  70605. * @returns the shadow generator allowing fluent coding.
  70606. */
  70607. ShadowGenerator.prototype.setDarkness = function (darkness) {
  70608. if (darkness >= 1.0)
  70609. this._darkness = 1.0;
  70610. else if (darkness <= 0.0)
  70611. this._darkness = 0.0;
  70612. else
  70613. this._darkness = darkness;
  70614. return this;
  70615. };
  70616. /**
  70617. * Sets the ability to have transparent shadow (boolean).
  70618. * @param transparent True if transparent else False
  70619. * @returns the shadow generator allowing fluent coding
  70620. */
  70621. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  70622. this._transparencyShadow = transparent;
  70623. return this;
  70624. };
  70625. /**
  70626. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  70627. * @returns The render target texture if present otherwise, null
  70628. */
  70629. ShadowGenerator.prototype.getShadowMap = function () {
  70630. return this._shadowMap;
  70631. };
  70632. /**
  70633. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  70634. * @returns The render target texture if the shadow map is present otherwise, null
  70635. */
  70636. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  70637. if (this._shadowMap2) {
  70638. return this._shadowMap2;
  70639. }
  70640. return this._shadowMap;
  70641. };
  70642. /**
  70643. * Helper function to add a mesh and its descendants to the list of shadow casters.
  70644. * @param mesh Mesh to add
  70645. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  70646. * @returns the Shadow Generator itself
  70647. */
  70648. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  70649. if (includeDescendants === void 0) { includeDescendants = true; }
  70650. var _a;
  70651. if (!this._shadowMap) {
  70652. return this;
  70653. }
  70654. if (!this._shadowMap.renderList) {
  70655. this._shadowMap.renderList = [];
  70656. }
  70657. this._shadowMap.renderList.push(mesh);
  70658. if (includeDescendants) {
  70659. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  70660. }
  70661. return this;
  70662. };
  70663. /**
  70664. * Helper function to remove a mesh and its descendants from the list of shadow casters
  70665. * @param mesh Mesh to remove
  70666. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  70667. * @returns the Shadow Generator itself
  70668. */
  70669. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  70670. if (includeDescendants === void 0) { includeDescendants = true; }
  70671. if (!this._shadowMap || !this._shadowMap.renderList) {
  70672. return this;
  70673. }
  70674. var index = this._shadowMap.renderList.indexOf(mesh);
  70675. if (index !== -1) {
  70676. this._shadowMap.renderList.splice(index, 1);
  70677. }
  70678. if (includeDescendants) {
  70679. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  70680. var child = _a[_i];
  70681. this.removeShadowCaster(child);
  70682. }
  70683. }
  70684. return this;
  70685. };
  70686. /**
  70687. * Returns the associated light object.
  70688. * @returns the light generating the shadow
  70689. */
  70690. ShadowGenerator.prototype.getLight = function () {
  70691. return this._light;
  70692. };
  70693. ShadowGenerator.prototype._initializeGenerator = function () {
  70694. this._light._markMeshesAsLightDirty();
  70695. this._initializeShadowMap();
  70696. };
  70697. ShadowGenerator.prototype._initializeShadowMap = function () {
  70698. var _this = this;
  70699. // Render target
  70700. var engine = this._scene.getEngine();
  70701. if (engine.webGLVersion > 1) {
  70702. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  70703. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  70704. }
  70705. else {
  70706. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  70707. }
  70708. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70709. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70710. this._shadowMap.anisotropicFilteringLevel = 1;
  70711. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70712. this._shadowMap.renderParticles = false;
  70713. this._shadowMap.ignoreCameraViewport = true;
  70714. // Record Face Index before render.
  70715. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  70716. _this._currentFaceIndex = faceIndex;
  70717. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70718. engine.setColorWrite(false);
  70719. }
  70720. });
  70721. // Custom render function.
  70722. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  70723. // Blur if required afer render.
  70724. this._shadowMap.onAfterUnbindObservable.add(function () {
  70725. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70726. engine.setColorWrite(true);
  70727. }
  70728. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  70729. return;
  70730. }
  70731. var shadowMap = _this.getShadowMapForRendering();
  70732. if (shadowMap) {
  70733. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  70734. }
  70735. });
  70736. // Clear according to the chosen filter.
  70737. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  70738. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  70739. this._shadowMap.onClearObservable.add(function (engine) {
  70740. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70741. engine.clear(clearOne, false, true, false);
  70742. }
  70743. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  70744. engine.clear(clearZero, true, true, false);
  70745. }
  70746. else {
  70747. engine.clear(clearOne, true, true, false);
  70748. }
  70749. });
  70750. };
  70751. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  70752. var _this = this;
  70753. var engine = this._scene.getEngine();
  70754. var targetSize = this._mapSize / this.blurScale;
  70755. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  70756. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  70757. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70758. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70759. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70760. }
  70761. if (this.useKernelBlur) {
  70762. 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);
  70763. this._kernelBlurXPostprocess.width = targetSize;
  70764. this._kernelBlurXPostprocess.height = targetSize;
  70765. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  70766. effect.setTexture("textureSampler", _this._shadowMap);
  70767. });
  70768. 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);
  70769. this._kernelBlurXPostprocess.autoClear = false;
  70770. this._kernelBlurYPostprocess.autoClear = false;
  70771. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70772. this._kernelBlurXPostprocess.packedFloat = true;
  70773. this._kernelBlurYPostprocess.packedFloat = true;
  70774. }
  70775. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  70776. }
  70777. else {
  70778. 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);
  70779. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  70780. effect.setFloat2("screenSize", targetSize, targetSize);
  70781. effect.setTexture("textureSampler", _this._shadowMap);
  70782. });
  70783. this._boxBlurPostprocess.autoClear = false;
  70784. this._blurPostProcesses = [this._boxBlurPostprocess];
  70785. }
  70786. };
  70787. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70788. var index;
  70789. var engine = this._scene.getEngine();
  70790. if (depthOnlySubMeshes.length) {
  70791. engine.setColorWrite(false);
  70792. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70793. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  70794. }
  70795. engine.setColorWrite(true);
  70796. }
  70797. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70798. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  70799. }
  70800. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70801. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  70802. }
  70803. if (this._transparencyShadow) {
  70804. for (index = 0; index < transparentSubMeshes.length; index++) {
  70805. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  70806. }
  70807. }
  70808. };
  70809. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  70810. var _this = this;
  70811. var mesh = subMesh.getRenderingMesh();
  70812. var scene = this._scene;
  70813. var engine = scene.getEngine();
  70814. var material = subMesh.getMaterial();
  70815. if (!material) {
  70816. return;
  70817. }
  70818. // Culling
  70819. engine.setState(material.backFaceCulling);
  70820. // Managing instances
  70821. var batch = mesh._getInstancesRenderList(subMesh._id);
  70822. if (batch.mustReturn) {
  70823. return;
  70824. }
  70825. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70826. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  70827. engine.enableEffect(this._effect);
  70828. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  70829. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  70830. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  70831. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70832. this._effect.setVector3("lightData", this._cachedDirection);
  70833. }
  70834. else {
  70835. this._effect.setVector3("lightData", this._cachedPosition);
  70836. }
  70837. if (scene.activeCamera) {
  70838. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  70839. }
  70840. // Alpha test
  70841. if (material && material.needAlphaTesting()) {
  70842. var alphaTexture = material.getAlphaTestTexture();
  70843. if (alphaTexture) {
  70844. this._effect.setTexture("diffuseSampler", alphaTexture);
  70845. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  70846. }
  70847. }
  70848. // Bones
  70849. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70850. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  70851. }
  70852. // Morph targets
  70853. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  70854. if (this.forceBackFacesOnly) {
  70855. engine.setState(true, 0, false, true);
  70856. }
  70857. // Draw
  70858. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70859. if (this.forceBackFacesOnly) {
  70860. engine.setState(true, 0, false, false);
  70861. }
  70862. }
  70863. else {
  70864. // Need to reset refresh rate of the shadowMap
  70865. if (this._shadowMap) {
  70866. this._shadowMap.resetRefreshCounter();
  70867. }
  70868. }
  70869. };
  70870. ShadowGenerator.prototype._applyFilterValues = function () {
  70871. if (!this._shadowMap) {
  70872. return;
  70873. }
  70874. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  70875. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  70876. }
  70877. else {
  70878. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70879. }
  70880. };
  70881. /**
  70882. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70883. * @param onCompiled Callback triggered at the and of the effects compilation
  70884. * @param options Sets of optional options forcing the compilation with different modes
  70885. */
  70886. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  70887. var _this = this;
  70888. var localOptions = __assign({ useInstances: false }, options);
  70889. var shadowMap = this.getShadowMap();
  70890. if (!shadowMap) {
  70891. if (onCompiled) {
  70892. onCompiled(this);
  70893. }
  70894. return;
  70895. }
  70896. var renderList = shadowMap.renderList;
  70897. if (!renderList) {
  70898. if (onCompiled) {
  70899. onCompiled(this);
  70900. }
  70901. return;
  70902. }
  70903. var subMeshes = new Array();
  70904. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  70905. var mesh = renderList_1[_i];
  70906. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  70907. }
  70908. if (subMeshes.length === 0) {
  70909. if (onCompiled) {
  70910. onCompiled(this);
  70911. }
  70912. return;
  70913. }
  70914. var currentIndex = 0;
  70915. var checkReady = function () {
  70916. if (!_this._scene || !_this._scene.getEngine()) {
  70917. return;
  70918. }
  70919. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  70920. currentIndex++;
  70921. if (currentIndex >= subMeshes.length) {
  70922. if (onCompiled) {
  70923. onCompiled(_this);
  70924. }
  70925. return;
  70926. }
  70927. }
  70928. setTimeout(checkReady, 16);
  70929. };
  70930. checkReady();
  70931. };
  70932. /**
  70933. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70934. * @param options Sets of optional options forcing the compilation with different modes
  70935. * @returns A promise that resolves when the compilation completes
  70936. */
  70937. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  70938. var _this = this;
  70939. return new Promise(function (resolve) {
  70940. _this.forceCompilation(function () {
  70941. resolve();
  70942. }, options);
  70943. });
  70944. };
  70945. /**
  70946. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  70947. * @param subMesh The submesh we want to render in the shadow map
  70948. * @param useInstances Defines wether will draw in the map using instances
  70949. * @returns true if ready otherwise, false
  70950. */
  70951. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  70952. var defines = [];
  70953. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70954. defines.push("#define FLOAT");
  70955. }
  70956. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70957. defines.push("#define ESM");
  70958. }
  70959. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  70960. defines.push("#define DEPTHTEXTURE");
  70961. }
  70962. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70963. var mesh = subMesh.getMesh();
  70964. var material = subMesh.getMaterial();
  70965. // Normal bias.
  70966. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70967. attribs.push(BABYLON.VertexBuffer.NormalKind);
  70968. defines.push("#define NORMAL");
  70969. if (mesh.nonUniformScaling) {
  70970. defines.push("#define NONUNIFORMSCALING");
  70971. }
  70972. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70973. defines.push("#define DIRECTIONINLIGHTDATA");
  70974. }
  70975. }
  70976. // Alpha test
  70977. if (material && material.needAlphaTesting()) {
  70978. var alphaTexture = material.getAlphaTestTexture();
  70979. if (alphaTexture) {
  70980. defines.push("#define ALPHATEST");
  70981. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70982. attribs.push(BABYLON.VertexBuffer.UVKind);
  70983. defines.push("#define UV1");
  70984. }
  70985. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70986. if (alphaTexture.coordinatesIndex === 1) {
  70987. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70988. defines.push("#define UV2");
  70989. }
  70990. }
  70991. }
  70992. }
  70993. // Bones
  70994. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70995. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70996. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70997. if (mesh.numBoneInfluencers > 4) {
  70998. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70999. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71000. }
  71001. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71002. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  71003. }
  71004. else {
  71005. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71006. }
  71007. // Morph targets
  71008. var manager = mesh.morphTargetManager;
  71009. var morphInfluencers = 0;
  71010. if (manager) {
  71011. if (manager.numInfluencers > 0) {
  71012. defines.push("#define MORPHTARGETS");
  71013. morphInfluencers = manager.numInfluencers;
  71014. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  71015. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  71016. }
  71017. }
  71018. // Instances
  71019. if (useInstances) {
  71020. defines.push("#define INSTANCES");
  71021. attribs.push("world0");
  71022. attribs.push("world1");
  71023. attribs.push("world2");
  71024. attribs.push("world3");
  71025. }
  71026. // Get correct effect
  71027. var join = defines.join("\n");
  71028. if (this._cachedDefines !== join) {
  71029. this._cachedDefines = join;
  71030. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  71031. }
  71032. if (!this._effect.isReady()) {
  71033. return false;
  71034. }
  71035. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  71036. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  71037. this._initializeBlurRTTAndPostProcesses();
  71038. }
  71039. }
  71040. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  71041. return false;
  71042. }
  71043. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  71044. return false;
  71045. }
  71046. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  71047. return false;
  71048. }
  71049. return true;
  71050. };
  71051. /**
  71052. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  71053. * @param defines Defines of the material we want to update
  71054. * @param lightIndex Index of the light in the enabled light list of the material
  71055. */
  71056. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  71057. var scene = this._scene;
  71058. var light = this._light;
  71059. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  71060. return;
  71061. }
  71062. defines["SHADOW" + lightIndex] = true;
  71063. if (this.useContactHardeningShadow) {
  71064. defines["SHADOWPCSS" + lightIndex] = true;
  71065. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  71066. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  71067. }
  71068. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  71069. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  71070. }
  71071. // else default to high.
  71072. }
  71073. if (this.usePercentageCloserFiltering) {
  71074. defines["SHADOWPCF" + lightIndex] = true;
  71075. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  71076. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  71077. }
  71078. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  71079. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  71080. }
  71081. // else default to high.
  71082. }
  71083. else if (this.usePoissonSampling) {
  71084. defines["SHADOWPOISSON" + lightIndex] = true;
  71085. }
  71086. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  71087. defines["SHADOWESM" + lightIndex] = true;
  71088. }
  71089. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  71090. defines["SHADOWCLOSEESM" + lightIndex] = true;
  71091. }
  71092. if (light.needCube()) {
  71093. defines["SHADOWCUBE" + lightIndex] = true;
  71094. }
  71095. };
  71096. /**
  71097. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  71098. * defined in the generator but impacting the effect).
  71099. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  71100. * @param effect The effect we are binfing the information for
  71101. */
  71102. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  71103. var light = this._light;
  71104. var scene = this._scene;
  71105. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  71106. return;
  71107. }
  71108. var camera = scene.activeCamera;
  71109. if (!camera) {
  71110. return;
  71111. }
  71112. var shadowMap = this.getShadowMap();
  71113. if (!shadowMap) {
  71114. return;
  71115. }
  71116. if (!light.needCube()) {
  71117. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  71118. }
  71119. // Only PCF uses depth stencil texture.
  71120. if (this._filter === ShadowGenerator.FILTER_PCF) {
  71121. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71122. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  71123. }
  71124. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  71125. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71126. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  71127. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  71128. }
  71129. else {
  71130. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71131. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  71132. }
  71133. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  71134. };
  71135. /**
  71136. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  71137. * (eq to shadow prjection matrix * light transform matrix)
  71138. * @returns The transform matrix used to create the shadow map
  71139. */
  71140. ShadowGenerator.prototype.getTransformMatrix = function () {
  71141. var scene = this._scene;
  71142. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  71143. return this._transformMatrix;
  71144. }
  71145. this._currentRenderID = scene.getRenderId();
  71146. this._currentFaceIndexCache = this._currentFaceIndex;
  71147. var lightPosition = this._light.position;
  71148. if (this._light.computeTransformedInformation()) {
  71149. lightPosition = this._light.transformedPosition;
  71150. }
  71151. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  71152. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  71153. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  71154. }
  71155. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  71156. this._cachedPosition.copyFrom(lightPosition);
  71157. this._cachedDirection.copyFrom(this._lightDirection);
  71158. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  71159. var shadowMap = this.getShadowMap();
  71160. if (shadowMap) {
  71161. var renderList = shadowMap.renderList;
  71162. if (renderList) {
  71163. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  71164. }
  71165. }
  71166. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  71167. }
  71168. return this._transformMatrix;
  71169. };
  71170. /**
  71171. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  71172. * Cube and 2D textures for instance.
  71173. */
  71174. ShadowGenerator.prototype.recreateShadowMap = function () {
  71175. var shadowMap = this._shadowMap;
  71176. if (!shadowMap) {
  71177. return;
  71178. }
  71179. // Track render list.
  71180. var renderList = shadowMap.renderList;
  71181. // Clean up existing data.
  71182. this._disposeRTTandPostProcesses();
  71183. // Reinitializes.
  71184. this._initializeGenerator();
  71185. // Reaffect the filter to ensure a correct fallback if necessary.
  71186. this.filter = this.filter;
  71187. // Reaffect the filter.
  71188. this._applyFilterValues();
  71189. // Reaffect Render List.
  71190. this._shadowMap.renderList = renderList;
  71191. };
  71192. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  71193. if (this._shadowMap2) {
  71194. this._shadowMap2.dispose();
  71195. this._shadowMap2 = null;
  71196. }
  71197. if (this._boxBlurPostprocess) {
  71198. this._boxBlurPostprocess.dispose();
  71199. this._boxBlurPostprocess = null;
  71200. }
  71201. if (this._kernelBlurXPostprocess) {
  71202. this._kernelBlurXPostprocess.dispose();
  71203. this._kernelBlurXPostprocess = null;
  71204. }
  71205. if (this._kernelBlurYPostprocess) {
  71206. this._kernelBlurYPostprocess.dispose();
  71207. this._kernelBlurYPostprocess = null;
  71208. }
  71209. this._blurPostProcesses = [];
  71210. };
  71211. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  71212. if (this._shadowMap) {
  71213. this._shadowMap.dispose();
  71214. this._shadowMap = null;
  71215. }
  71216. this._disposeBlurPostProcesses();
  71217. };
  71218. /**
  71219. * Disposes the ShadowGenerator.
  71220. * Returns nothing.
  71221. */
  71222. ShadowGenerator.prototype.dispose = function () {
  71223. this._disposeRTTandPostProcesses();
  71224. if (this._light) {
  71225. this._light._shadowGenerator = null;
  71226. this._light._markMeshesAsLightDirty();
  71227. }
  71228. };
  71229. /**
  71230. * Serializes the shadow generator setup to a json object.
  71231. * @returns The serialized JSON object
  71232. */
  71233. ShadowGenerator.prototype.serialize = function () {
  71234. var serializationObject = {};
  71235. var shadowMap = this.getShadowMap();
  71236. if (!shadowMap) {
  71237. return serializationObject;
  71238. }
  71239. serializationObject.lightId = this._light.id;
  71240. serializationObject.mapSize = shadowMap.getRenderSize();
  71241. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  71242. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  71243. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  71244. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  71245. serializationObject.usePoissonSampling = this.usePoissonSampling;
  71246. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  71247. serializationObject.depthScale = this.depthScale;
  71248. serializationObject.darkness = this.getDarkness();
  71249. serializationObject.blurBoxOffset = this.blurBoxOffset;
  71250. serializationObject.blurKernel = this.blurKernel;
  71251. serializationObject.blurScale = this.blurScale;
  71252. serializationObject.useKernelBlur = this.useKernelBlur;
  71253. serializationObject.transparencyShadow = this._transparencyShadow;
  71254. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  71255. serializationObject.bias = this.bias;
  71256. serializationObject.normalBias = this.normalBias;
  71257. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  71258. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  71259. serializationObject.filteringQuality = this.filteringQuality;
  71260. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  71261. serializationObject.renderList = [];
  71262. if (shadowMap.renderList) {
  71263. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  71264. var mesh = shadowMap.renderList[meshIndex];
  71265. serializationObject.renderList.push(mesh.id);
  71266. }
  71267. }
  71268. return serializationObject;
  71269. };
  71270. /**
  71271. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  71272. * @param parsedShadowGenerator The JSON object to parse
  71273. * @param scene The scene to create the shadow map for
  71274. * @returns The parsed shadow generator
  71275. */
  71276. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  71277. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  71278. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  71279. var shadowMap = shadowGenerator.getShadowMap();
  71280. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  71281. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  71282. meshes.forEach(function (mesh) {
  71283. if (!shadowMap) {
  71284. return;
  71285. }
  71286. if (!shadowMap.renderList) {
  71287. shadowMap.renderList = [];
  71288. }
  71289. shadowMap.renderList.push(mesh);
  71290. });
  71291. }
  71292. if (parsedShadowGenerator.usePoissonSampling) {
  71293. shadowGenerator.usePoissonSampling = true;
  71294. }
  71295. else if (parsedShadowGenerator.useExponentialShadowMap) {
  71296. shadowGenerator.useExponentialShadowMap = true;
  71297. }
  71298. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  71299. shadowGenerator.useBlurExponentialShadowMap = true;
  71300. }
  71301. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  71302. shadowGenerator.useCloseExponentialShadowMap = true;
  71303. }
  71304. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  71305. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  71306. }
  71307. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  71308. shadowGenerator.usePercentageCloserFiltering = true;
  71309. }
  71310. else if (parsedShadowGenerator.useContactHardeningShadow) {
  71311. shadowGenerator.useContactHardeningShadow = true;
  71312. }
  71313. if (parsedShadowGenerator.filteringQuality) {
  71314. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  71315. }
  71316. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  71317. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  71318. }
  71319. // Backward compat
  71320. else if (parsedShadowGenerator.useVarianceShadowMap) {
  71321. shadowGenerator.useExponentialShadowMap = true;
  71322. }
  71323. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  71324. shadowGenerator.useBlurExponentialShadowMap = true;
  71325. }
  71326. if (parsedShadowGenerator.depthScale) {
  71327. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  71328. }
  71329. if (parsedShadowGenerator.blurScale) {
  71330. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  71331. }
  71332. if (parsedShadowGenerator.blurBoxOffset) {
  71333. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  71334. }
  71335. if (parsedShadowGenerator.useKernelBlur) {
  71336. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  71337. }
  71338. if (parsedShadowGenerator.blurKernel) {
  71339. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  71340. }
  71341. if (parsedShadowGenerator.bias !== undefined) {
  71342. shadowGenerator.bias = parsedShadowGenerator.bias;
  71343. }
  71344. if (parsedShadowGenerator.normalBias !== undefined) {
  71345. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  71346. }
  71347. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  71348. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  71349. }
  71350. if (parsedShadowGenerator.darkness) {
  71351. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  71352. }
  71353. if (parsedShadowGenerator.transparencyShadow) {
  71354. shadowGenerator.setTransparencyShadow(true);
  71355. }
  71356. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  71357. return shadowGenerator;
  71358. };
  71359. /**
  71360. * Shadow generator mode None: no filtering applied.
  71361. */
  71362. ShadowGenerator.FILTER_NONE = 0;
  71363. /**
  71364. * Shadow generator mode ESM: Exponential Shadow Mapping.
  71365. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71366. */
  71367. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  71368. /**
  71369. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  71370. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  71371. */
  71372. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  71373. /**
  71374. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  71375. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71376. */
  71377. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  71378. /**
  71379. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  71380. * edge artifacts on steep falloff.
  71381. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71382. */
  71383. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  71384. /**
  71385. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  71386. * edge artifacts on steep falloff.
  71387. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71388. */
  71389. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  71390. /**
  71391. * Shadow generator mode PCF: Percentage Closer Filtering
  71392. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71393. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  71394. */
  71395. ShadowGenerator.FILTER_PCF = 6;
  71396. /**
  71397. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  71398. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71399. * Contact Hardening
  71400. */
  71401. ShadowGenerator.FILTER_PCSS = 7;
  71402. /**
  71403. * Reserved for PCF and PCSS
  71404. * Highest Quality.
  71405. *
  71406. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  71407. *
  71408. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  71409. */
  71410. ShadowGenerator.QUALITY_HIGH = 0;
  71411. /**
  71412. * Reserved for PCF and PCSS
  71413. * Good tradeoff for quality/perf cross devices
  71414. *
  71415. * Execute PCF on a 3*3 kernel.
  71416. *
  71417. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  71418. */
  71419. ShadowGenerator.QUALITY_MEDIUM = 1;
  71420. /**
  71421. * Reserved for PCF and PCSS
  71422. * The lowest quality but the fastest.
  71423. *
  71424. * Execute PCF on a 1*1 kernel.
  71425. *
  71426. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  71427. */
  71428. ShadowGenerator.QUALITY_LOW = 2;
  71429. return ShadowGenerator;
  71430. }());
  71431. BABYLON.ShadowGenerator = ShadowGenerator;
  71432. })(BABYLON || (BABYLON = {}));
  71433. //# sourceMappingURL=babylon.shadowGenerator.js.map
  71434. var BABYLON;
  71435. (function (BABYLON) {
  71436. // Adds the parser to the scene parsers.
  71437. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  71438. // Shadows
  71439. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71440. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71441. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71442. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71443. // SG would be available on their associated lights
  71444. }
  71445. }
  71446. });
  71447. /**
  71448. * Defines the shadow generator component responsible to manage any shadow generators
  71449. * in a given scene.
  71450. */
  71451. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  71452. /**
  71453. * Creates a new instance of the component for the given scene
  71454. * @param scene Defines the scene to register the component in
  71455. */
  71456. function ShadowGeneratorSceneComponent(scene) {
  71457. /**
  71458. * The component name helpfull to identify the component in the list of scene components.
  71459. */
  71460. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  71461. this.scene = scene;
  71462. }
  71463. /**
  71464. * Registers the component in a given scene
  71465. */
  71466. ShadowGeneratorSceneComponent.prototype.register = function () {
  71467. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  71468. };
  71469. /**
  71470. * Rebuilds the elements related to this component in case of
  71471. * context lost for instance.
  71472. */
  71473. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  71474. // Nothing To Do Here.
  71475. };
  71476. /**
  71477. * Serializes the component data to the specified json object
  71478. * @param serializationObject The object to serialize to
  71479. */
  71480. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  71481. // Shadows
  71482. serializationObject.shadowGenerators = [];
  71483. var lights = this.scene.lights;
  71484. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  71485. var light = lights_1[_i];
  71486. var shadowGenerator = light.getShadowGenerator();
  71487. if (shadowGenerator) {
  71488. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71489. }
  71490. }
  71491. };
  71492. /**
  71493. * Adds all the element from the container to the scene
  71494. * @param container the container holding the elements
  71495. */
  71496. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  71497. // Nothing To Do Here. (directly attached to a light)
  71498. };
  71499. /**
  71500. * Removes all the elements in the container from the scene
  71501. * @param container contains the elements to remove
  71502. */
  71503. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  71504. // Nothing To Do Here. (directly attached to a light)
  71505. };
  71506. /**
  71507. * Rebuilds the elements related to this component in case of
  71508. * context lost for instance.
  71509. */
  71510. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  71511. // Nothing To Do Here.
  71512. };
  71513. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  71514. // Shadows
  71515. var scene = this.scene;
  71516. if (this.scene.shadowsEnabled) {
  71517. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  71518. var light = scene.lights[lightIndex];
  71519. var shadowGenerator = light.getShadowGenerator();
  71520. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  71521. var shadowMap = (shadowGenerator.getShadowMap());
  71522. if (scene.textures.indexOf(shadowMap) !== -1) {
  71523. renderTargets.push(shadowMap);
  71524. }
  71525. }
  71526. }
  71527. }
  71528. };
  71529. return ShadowGeneratorSceneComponent;
  71530. }());
  71531. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  71532. })(BABYLON || (BABYLON = {}));
  71533. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  71534. var BABYLON;
  71535. (function (BABYLON) {
  71536. var DefaultLoadingScreen = /** @class */ (function () {
  71537. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  71538. if (_loadingText === void 0) { _loadingText = ""; }
  71539. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  71540. var _this = this;
  71541. this._renderingCanvas = _renderingCanvas;
  71542. this._loadingText = _loadingText;
  71543. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  71544. // Resize
  71545. this._resizeLoadingUI = function () {
  71546. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  71547. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  71548. if (!_this._loadingDiv) {
  71549. return;
  71550. }
  71551. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  71552. _this._loadingDiv.style.left = canvasRect.left + "px";
  71553. _this._loadingDiv.style.top = canvasRect.top + "px";
  71554. _this._loadingDiv.style.width = canvasRect.width + "px";
  71555. _this._loadingDiv.style.height = canvasRect.height + "px";
  71556. };
  71557. }
  71558. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  71559. if (this._loadingDiv) {
  71560. // Do not add a loading screen if there is already one
  71561. return;
  71562. }
  71563. this._loadingDiv = document.createElement("div");
  71564. this._loadingDiv.id = "babylonjsLoadingDiv";
  71565. this._loadingDiv.style.opacity = "0";
  71566. this._loadingDiv.style.transition = "opacity 1.5s ease";
  71567. this._loadingDiv.style.pointerEvents = "none";
  71568. // Loading text
  71569. this._loadingTextDiv = document.createElement("div");
  71570. this._loadingTextDiv.style.position = "absolute";
  71571. this._loadingTextDiv.style.left = "0";
  71572. this._loadingTextDiv.style.top = "50%";
  71573. this._loadingTextDiv.style.marginTop = "80px";
  71574. this._loadingTextDiv.style.width = "100%";
  71575. this._loadingTextDiv.style.height = "20px";
  71576. this._loadingTextDiv.style.fontFamily = "Arial";
  71577. this._loadingTextDiv.style.fontSize = "14px";
  71578. this._loadingTextDiv.style.color = "white";
  71579. this._loadingTextDiv.style.textAlign = "center";
  71580. this._loadingTextDiv.innerHTML = "Loading";
  71581. this._loadingDiv.appendChild(this._loadingTextDiv);
  71582. //set the predefined text
  71583. this._loadingTextDiv.innerHTML = this._loadingText;
  71584. // Generating keyframes
  71585. var style = document.createElement('style');
  71586. style.type = 'text/css';
  71587. 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 }";
  71588. style.innerHTML = keyFrames;
  71589. document.getElementsByTagName('head')[0].appendChild(style);
  71590. // Loading img
  71591. var imgBack = new Image();
  71592. 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";
  71593. imgBack.style.position = "absolute";
  71594. imgBack.style.left = "50%";
  71595. imgBack.style.top = "50%";
  71596. imgBack.style.marginLeft = "-60px";
  71597. imgBack.style.marginTop = "-60px";
  71598. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  71599. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  71600. imgBack.style.transformOrigin = "50% 50%";
  71601. imgBack.style.webkitTransformOrigin = "50% 50%";
  71602. this._loadingDiv.appendChild(imgBack);
  71603. this._resizeLoadingUI();
  71604. window.addEventListener("resize", this._resizeLoadingUI);
  71605. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71606. document.body.appendChild(this._loadingDiv);
  71607. this._loadingDiv.style.opacity = "1";
  71608. };
  71609. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  71610. var _this = this;
  71611. if (!this._loadingDiv) {
  71612. return;
  71613. }
  71614. var onTransitionEnd = function () {
  71615. if (!_this._loadingDiv) {
  71616. return;
  71617. }
  71618. document.body.removeChild(_this._loadingDiv);
  71619. window.removeEventListener("resize", _this._resizeLoadingUI);
  71620. _this._loadingDiv = null;
  71621. };
  71622. this._loadingDiv.style.opacity = "0";
  71623. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  71624. };
  71625. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  71626. set: function (text) {
  71627. this._loadingText = text;
  71628. if (this._loadingTextDiv) {
  71629. this._loadingTextDiv.innerHTML = this._loadingText;
  71630. }
  71631. },
  71632. enumerable: true,
  71633. configurable: true
  71634. });
  71635. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  71636. get: function () {
  71637. return this._loadingDivBackgroundColor;
  71638. },
  71639. set: function (color) {
  71640. this._loadingDivBackgroundColor = color;
  71641. if (!this._loadingDiv) {
  71642. return;
  71643. }
  71644. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71645. },
  71646. enumerable: true,
  71647. configurable: true
  71648. });
  71649. return DefaultLoadingScreen;
  71650. }());
  71651. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  71652. })(BABYLON || (BABYLON = {}));
  71653. //# sourceMappingURL=babylon.loadingScreen.js.map
  71654. var BABYLON;
  71655. (function (BABYLON) {
  71656. var SceneLoaderProgressEvent = /** @class */ (function () {
  71657. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  71658. this.lengthComputable = lengthComputable;
  71659. this.loaded = loaded;
  71660. this.total = total;
  71661. }
  71662. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  71663. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  71664. };
  71665. return SceneLoaderProgressEvent;
  71666. }());
  71667. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  71668. var SceneLoader = /** @class */ (function () {
  71669. function SceneLoader() {
  71670. }
  71671. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  71672. get: function () {
  71673. return 0;
  71674. },
  71675. enumerable: true,
  71676. configurable: true
  71677. });
  71678. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  71679. get: function () {
  71680. return 1;
  71681. },
  71682. enumerable: true,
  71683. configurable: true
  71684. });
  71685. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  71686. get: function () {
  71687. return 2;
  71688. },
  71689. enumerable: true,
  71690. configurable: true
  71691. });
  71692. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  71693. get: function () {
  71694. return 3;
  71695. },
  71696. enumerable: true,
  71697. configurable: true
  71698. });
  71699. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  71700. get: function () {
  71701. return SceneLoader._ForceFullSceneLoadingForIncremental;
  71702. },
  71703. set: function (value) {
  71704. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  71705. },
  71706. enumerable: true,
  71707. configurable: true
  71708. });
  71709. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  71710. get: function () {
  71711. return SceneLoader._ShowLoadingScreen;
  71712. },
  71713. set: function (value) {
  71714. SceneLoader._ShowLoadingScreen = value;
  71715. },
  71716. enumerable: true,
  71717. configurable: true
  71718. });
  71719. Object.defineProperty(SceneLoader, "loggingLevel", {
  71720. get: function () {
  71721. return SceneLoader._loggingLevel;
  71722. },
  71723. set: function (value) {
  71724. SceneLoader._loggingLevel = value;
  71725. },
  71726. enumerable: true,
  71727. configurable: true
  71728. });
  71729. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  71730. get: function () {
  71731. return SceneLoader._CleanBoneMatrixWeights;
  71732. },
  71733. set: function (value) {
  71734. SceneLoader._CleanBoneMatrixWeights = value;
  71735. },
  71736. enumerable: true,
  71737. configurable: true
  71738. });
  71739. SceneLoader._getDefaultPlugin = function () {
  71740. return SceneLoader._registeredPlugins[".babylon"];
  71741. };
  71742. SceneLoader._getPluginForExtension = function (extension) {
  71743. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  71744. if (registeredPlugin) {
  71745. return registeredPlugin;
  71746. }
  71747. 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");
  71748. return SceneLoader._getDefaultPlugin();
  71749. };
  71750. SceneLoader._getPluginForDirectLoad = function (data) {
  71751. for (var extension in SceneLoader._registeredPlugins) {
  71752. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  71753. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  71754. return SceneLoader._registeredPlugins[extension];
  71755. }
  71756. }
  71757. return SceneLoader._getDefaultPlugin();
  71758. };
  71759. SceneLoader._getPluginForFilename = function (sceneFilename) {
  71760. var queryStringPosition = sceneFilename.indexOf("?");
  71761. if (queryStringPosition !== -1) {
  71762. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  71763. }
  71764. var dotPosition = sceneFilename.lastIndexOf(".");
  71765. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  71766. return SceneLoader._getPluginForExtension(extension);
  71767. };
  71768. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  71769. SceneLoader._getDirectLoad = function (sceneFilename) {
  71770. if (sceneFilename.substr(0, 5) === "data:") {
  71771. return sceneFilename.substr(5);
  71772. }
  71773. return null;
  71774. };
  71775. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  71776. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  71777. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  71778. var plugin;
  71779. if (registeredPlugin.plugin.createPlugin) {
  71780. plugin = registeredPlugin.plugin.createPlugin();
  71781. }
  71782. else {
  71783. plugin = registeredPlugin.plugin;
  71784. }
  71785. var useArrayBuffer = registeredPlugin.isBinary;
  71786. var database;
  71787. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  71788. var dataCallback = function (data, responseURL) {
  71789. if (scene.isDisposed) {
  71790. onError("Scene has been disposed");
  71791. return;
  71792. }
  71793. scene.database = database;
  71794. onSuccess(plugin, data, responseURL);
  71795. };
  71796. var request = null;
  71797. var pluginDisposed = false;
  71798. var onDisposeObservable = plugin.onDisposeObservable;
  71799. if (onDisposeObservable) {
  71800. onDisposeObservable.add(function () {
  71801. pluginDisposed = true;
  71802. if (request) {
  71803. request.abort();
  71804. request = null;
  71805. }
  71806. onDispose();
  71807. });
  71808. }
  71809. var manifestChecked = function () {
  71810. if (pluginDisposed) {
  71811. return;
  71812. }
  71813. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  71814. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  71815. } : undefined, database, useArrayBuffer, function (request, exception) {
  71816. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  71817. });
  71818. };
  71819. if (directLoad) {
  71820. dataCallback(directLoad);
  71821. return plugin;
  71822. }
  71823. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  71824. var engine = scene.getEngine();
  71825. var canUseOfflineSupport = engine.enableOfflineSupport;
  71826. if (canUseOfflineSupport) {
  71827. // Also check for exceptions
  71828. var exceptionFound = false;
  71829. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  71830. var regex = _a[_i];
  71831. if (regex.test(fileInfo.url)) {
  71832. exceptionFound = true;
  71833. break;
  71834. }
  71835. }
  71836. canUseOfflineSupport = !exceptionFound;
  71837. }
  71838. if (canUseOfflineSupport) {
  71839. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  71840. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  71841. }
  71842. else {
  71843. manifestChecked();
  71844. }
  71845. }
  71846. // Loading file from disk via input file or drag'n'drop
  71847. else {
  71848. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  71849. if (file) {
  71850. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  71851. }
  71852. else {
  71853. onError("Unable to find file named " + fileInfo.name);
  71854. }
  71855. }
  71856. return plugin;
  71857. };
  71858. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  71859. var url;
  71860. var name;
  71861. if (!sceneFilename) {
  71862. url = rootUrl;
  71863. name = BABYLON.Tools.GetFilename(rootUrl);
  71864. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71865. }
  71866. else {
  71867. if (sceneFilename.substr(0, 1) === "/") {
  71868. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71869. return null;
  71870. }
  71871. url = rootUrl + sceneFilename;
  71872. name = sceneFilename;
  71873. }
  71874. ;
  71875. return {
  71876. url: url,
  71877. rootUrl: rootUrl,
  71878. name: name
  71879. };
  71880. };
  71881. // Public functions
  71882. SceneLoader.GetPluginForExtension = function (extension) {
  71883. return SceneLoader._getPluginForExtension(extension).plugin;
  71884. };
  71885. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  71886. return !!SceneLoader._registeredPlugins[extension];
  71887. };
  71888. SceneLoader.RegisterPlugin = function (plugin) {
  71889. if (typeof plugin.extensions === "string") {
  71890. var extension = plugin.extensions;
  71891. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71892. plugin: plugin,
  71893. isBinary: false
  71894. };
  71895. }
  71896. else {
  71897. var extensions = plugin.extensions;
  71898. Object.keys(extensions).forEach(function (extension) {
  71899. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71900. plugin: plugin,
  71901. isBinary: extensions[extension].isBinary
  71902. };
  71903. });
  71904. }
  71905. };
  71906. /**
  71907. * Import meshes into a scene
  71908. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71909. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  71910. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  71911. * @param scene the instance of BABYLON.Scene to append to
  71912. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  71913. * @param onProgress a callback with a progress event for each file being loaded
  71914. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71915. * @param pluginExtension the extension used to determine the plugin
  71916. * @returns The loaded plugin
  71917. */
  71918. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71919. if (sceneFilename === void 0) { sceneFilename = ""; }
  71920. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71921. if (onSuccess === void 0) { onSuccess = null; }
  71922. if (onProgress === void 0) { onProgress = null; }
  71923. if (onError === void 0) { onError = null; }
  71924. if (pluginExtension === void 0) { pluginExtension = null; }
  71925. if (!scene) {
  71926. BABYLON.Tools.Error("No scene available to import mesh to");
  71927. return null;
  71928. }
  71929. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  71930. if (!fileInfo) {
  71931. return null;
  71932. }
  71933. var loadingToken = {};
  71934. scene._addPendingData(loadingToken);
  71935. var disposeHandler = function () {
  71936. scene._removePendingData(loadingToken);
  71937. };
  71938. var errorHandler = function (message, exception) {
  71939. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  71940. if (onError) {
  71941. onError(scene, errorMessage, exception);
  71942. }
  71943. else {
  71944. BABYLON.Tools.Error(errorMessage);
  71945. // should the exception be thrown?
  71946. }
  71947. disposeHandler();
  71948. };
  71949. var progressHandler = onProgress ? function (event) {
  71950. try {
  71951. onProgress(event);
  71952. }
  71953. catch (e) {
  71954. errorHandler("Error in onProgress callback", e);
  71955. }
  71956. } : undefined;
  71957. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  71958. scene.importedMeshesFiles.push(fileInfo.url);
  71959. if (onSuccess) {
  71960. try {
  71961. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  71962. }
  71963. catch (e) {
  71964. errorHandler("Error in onSuccess callback", e);
  71965. }
  71966. }
  71967. scene._removePendingData(loadingToken);
  71968. };
  71969. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  71970. if (plugin.rewriteRootURL) {
  71971. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  71972. }
  71973. if (plugin.importMesh) {
  71974. var syncedPlugin = plugin;
  71975. var meshes = new Array();
  71976. var particleSystems = new Array();
  71977. var skeletons = new Array();
  71978. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  71979. return;
  71980. }
  71981. scene.loadingPluginName = plugin.name;
  71982. successHandler(meshes, particleSystems, skeletons, []);
  71983. }
  71984. else {
  71985. var asyncedPlugin = plugin;
  71986. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  71987. scene.loadingPluginName = plugin.name;
  71988. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  71989. }).catch(function (error) {
  71990. errorHandler(error.message, error);
  71991. });
  71992. }
  71993. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71994. };
  71995. /**
  71996. * Import meshes into a scene
  71997. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71998. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  71999. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72000. * @param scene the instance of BABYLON.Scene to append to
  72001. * @param onProgress a callback with a progress event for each file being loaded
  72002. * @param pluginExtension the extension used to determine the plugin
  72003. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  72004. */
  72005. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72006. if (sceneFilename === void 0) { sceneFilename = ""; }
  72007. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72008. if (onProgress === void 0) { onProgress = null; }
  72009. if (pluginExtension === void 0) { pluginExtension = null; }
  72010. return new Promise(function (resolve, reject) {
  72011. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  72012. resolve({
  72013. meshes: meshes,
  72014. particleSystems: particleSystems,
  72015. skeletons: skeletons,
  72016. animationGroups: animationGroups
  72017. });
  72018. }, onProgress, function (scene, message, exception) {
  72019. reject(exception || new Error(message));
  72020. }, pluginExtension);
  72021. });
  72022. };
  72023. /**
  72024. * Load a scene
  72025. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72026. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72027. * @param engine is the instance of BABYLON.Engine to use to create the scene
  72028. * @param onSuccess a callback with the scene when import succeeds
  72029. * @param onProgress a callback with a progress event for each file being loaded
  72030. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72031. * @param pluginExtension the extension used to determine the plugin
  72032. * @returns The loaded plugin
  72033. */
  72034. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  72035. if (onSuccess === void 0) { onSuccess = null; }
  72036. if (onProgress === void 0) { onProgress = null; }
  72037. if (onError === void 0) { onError = null; }
  72038. if (pluginExtension === void 0) { pluginExtension = null; }
  72039. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  72040. };
  72041. /**
  72042. * Load a scene
  72043. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72044. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72045. * @param engine is the instance of BABYLON.Engine to use to create the scene
  72046. * @param onProgress a callback with a progress event for each file being loaded
  72047. * @param pluginExtension the extension used to determine the plugin
  72048. * @returns The loaded scene
  72049. */
  72050. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  72051. if (onProgress === void 0) { onProgress = null; }
  72052. if (pluginExtension === void 0) { pluginExtension = null; }
  72053. return new Promise(function (resolve, reject) {
  72054. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  72055. resolve(scene);
  72056. }, onProgress, function (scene, message, exception) {
  72057. reject(exception || new Error(message));
  72058. }, pluginExtension);
  72059. });
  72060. };
  72061. /**
  72062. * Append a scene
  72063. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72064. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72065. * @param scene is the instance of BABYLON.Scene to append to
  72066. * @param onSuccess a callback with the scene when import succeeds
  72067. * @param onProgress a callback with a progress event for each file being loaded
  72068. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72069. * @param pluginExtension the extension used to determine the plugin
  72070. * @returns The loaded plugin
  72071. */
  72072. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72073. if (sceneFilename === void 0) { sceneFilename = ""; }
  72074. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72075. if (onSuccess === void 0) { onSuccess = null; }
  72076. if (onProgress === void 0) { onProgress = null; }
  72077. if (onError === void 0) { onError = null; }
  72078. if (pluginExtension === void 0) { pluginExtension = null; }
  72079. if (!scene) {
  72080. BABYLON.Tools.Error("No scene available to append to");
  72081. return null;
  72082. }
  72083. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72084. if (!fileInfo) {
  72085. return null;
  72086. }
  72087. if (SceneLoader.ShowLoadingScreen) {
  72088. scene.getEngine().displayLoadingUI();
  72089. }
  72090. var loadingToken = {};
  72091. scene._addPendingData(loadingToken);
  72092. var disposeHandler = function () {
  72093. scene._removePendingData(loadingToken);
  72094. scene.getEngine().hideLoadingUI();
  72095. };
  72096. var errorHandler = function (message, exception) {
  72097. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  72098. if (onError) {
  72099. onError(scene, errorMessage, exception);
  72100. }
  72101. else {
  72102. BABYLON.Tools.Error(errorMessage);
  72103. // should the exception be thrown?
  72104. }
  72105. disposeHandler();
  72106. };
  72107. var progressHandler = onProgress ? function (event) {
  72108. try {
  72109. onProgress(event);
  72110. }
  72111. catch (e) {
  72112. errorHandler("Error in onProgress callback", e);
  72113. }
  72114. } : undefined;
  72115. var successHandler = function () {
  72116. if (onSuccess) {
  72117. try {
  72118. onSuccess(scene);
  72119. }
  72120. catch (e) {
  72121. errorHandler("Error in onSuccess callback", e);
  72122. }
  72123. }
  72124. scene._removePendingData(loadingToken);
  72125. };
  72126. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72127. if (plugin.load) {
  72128. var syncedPlugin = plugin;
  72129. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  72130. return;
  72131. }
  72132. scene.loadingPluginName = plugin.name;
  72133. successHandler();
  72134. }
  72135. else {
  72136. var asyncedPlugin = plugin;
  72137. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  72138. scene.loadingPluginName = plugin.name;
  72139. successHandler();
  72140. }).catch(function (error) {
  72141. errorHandler(error.message, error);
  72142. });
  72143. }
  72144. if (SceneLoader.ShowLoadingScreen) {
  72145. scene.executeWhenReady(function () {
  72146. scene.getEngine().hideLoadingUI();
  72147. });
  72148. }
  72149. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72150. };
  72151. /**
  72152. * Append a scene
  72153. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72154. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72155. * @param scene is the instance of BABYLON.Scene to append to
  72156. * @param onProgress a callback with a progress event for each file being loaded
  72157. * @param pluginExtension the extension used to determine the plugin
  72158. * @returns The given scene
  72159. */
  72160. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72161. if (sceneFilename === void 0) { sceneFilename = ""; }
  72162. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72163. if (onProgress === void 0) { onProgress = null; }
  72164. if (pluginExtension === void 0) { pluginExtension = null; }
  72165. return new Promise(function (resolve, reject) {
  72166. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  72167. resolve(scene);
  72168. }, onProgress, function (scene, message, exception) {
  72169. reject(exception || new Error(message));
  72170. }, pluginExtension);
  72171. });
  72172. };
  72173. /**
  72174. * Load a scene into an asset container
  72175. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72176. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72177. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  72178. * @param onSuccess a callback with the scene when import succeeds
  72179. * @param onProgress a callback with a progress event for each file being loaded
  72180. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72181. * @param pluginExtension the extension used to determine the plugin
  72182. * @returns The loaded plugin
  72183. */
  72184. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72185. if (sceneFilename === void 0) { sceneFilename = ""; }
  72186. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72187. if (onSuccess === void 0) { onSuccess = null; }
  72188. if (onProgress === void 0) { onProgress = null; }
  72189. if (onError === void 0) { onError = null; }
  72190. if (pluginExtension === void 0) { pluginExtension = null; }
  72191. if (!scene) {
  72192. BABYLON.Tools.Error("No scene available to load asset container to");
  72193. return null;
  72194. }
  72195. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72196. if (!fileInfo) {
  72197. return null;
  72198. }
  72199. var loadingToken = {};
  72200. scene._addPendingData(loadingToken);
  72201. var disposeHandler = function () {
  72202. scene._removePendingData(loadingToken);
  72203. };
  72204. var errorHandler = function (message, exception) {
  72205. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  72206. if (onError) {
  72207. onError(scene, errorMessage, exception);
  72208. }
  72209. else {
  72210. BABYLON.Tools.Error(errorMessage);
  72211. // should the exception be thrown?
  72212. }
  72213. disposeHandler();
  72214. };
  72215. var progressHandler = onProgress ? function (event) {
  72216. try {
  72217. onProgress(event);
  72218. }
  72219. catch (e) {
  72220. errorHandler("Error in onProgress callback", e);
  72221. }
  72222. } : undefined;
  72223. var successHandler = function (assets) {
  72224. if (onSuccess) {
  72225. try {
  72226. onSuccess(assets);
  72227. }
  72228. catch (e) {
  72229. errorHandler("Error in onSuccess callback", e);
  72230. }
  72231. }
  72232. scene._removePendingData(loadingToken);
  72233. };
  72234. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72235. if (plugin.loadAssetContainer) {
  72236. var syncedPlugin = plugin;
  72237. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  72238. if (!assetContainer) {
  72239. return;
  72240. }
  72241. scene.loadingPluginName = plugin.name;
  72242. successHandler(assetContainer);
  72243. }
  72244. else if (plugin.loadAssetContainerAsync) {
  72245. var asyncedPlugin = plugin;
  72246. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  72247. scene.loadingPluginName = plugin.name;
  72248. successHandler(assetContainer);
  72249. }).catch(function (error) {
  72250. errorHandler(error.message, error);
  72251. });
  72252. }
  72253. else {
  72254. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  72255. }
  72256. if (SceneLoader.ShowLoadingScreen) {
  72257. scene.executeWhenReady(function () {
  72258. scene.getEngine().hideLoadingUI();
  72259. });
  72260. }
  72261. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72262. };
  72263. /**
  72264. * Load a scene into an asset container
  72265. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72266. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72267. * @param scene is the instance of BABYLON.Scene to append to
  72268. * @param onProgress a callback with a progress event for each file being loaded
  72269. * @param pluginExtension the extension used to determine the plugin
  72270. * @returns The loaded asset container
  72271. */
  72272. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72273. if (sceneFilename === void 0) { sceneFilename = ""; }
  72274. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72275. if (onProgress === void 0) { onProgress = null; }
  72276. if (pluginExtension === void 0) { pluginExtension = null; }
  72277. return new Promise(function (resolve, reject) {
  72278. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  72279. resolve(assetContainer);
  72280. }, onProgress, function (scene, message, exception) {
  72281. reject(exception || new Error(message));
  72282. }, pluginExtension);
  72283. });
  72284. };
  72285. // Flags
  72286. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  72287. SceneLoader._ShowLoadingScreen = true;
  72288. SceneLoader._CleanBoneMatrixWeights = false;
  72289. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  72290. // Members
  72291. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  72292. SceneLoader._registeredPlugins = {};
  72293. return SceneLoader;
  72294. }());
  72295. BABYLON.SceneLoader = SceneLoader;
  72296. ;
  72297. })(BABYLON || (BABYLON = {}));
  72298. //# sourceMappingURL=babylon.sceneLoader.js.map
  72299. var BABYLON;
  72300. (function (BABYLON) {
  72301. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  72302. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72303. var parsedMaterial = parsedData.materials[index];
  72304. if (parsedMaterial.id === id) {
  72305. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72306. }
  72307. }
  72308. return null;
  72309. };
  72310. var isDescendantOf = function (mesh, names, hierarchyIds) {
  72311. for (var i in names) {
  72312. if (mesh.name === names[i]) {
  72313. hierarchyIds.push(mesh.id);
  72314. return true;
  72315. }
  72316. }
  72317. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  72318. hierarchyIds.push(mesh.id);
  72319. return true;
  72320. }
  72321. return false;
  72322. };
  72323. var logOperation = function (operation, producer) {
  72324. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  72325. };
  72326. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  72327. if (addToScene === void 0) { addToScene = false; }
  72328. var container = new BABYLON.AssetContainer(scene);
  72329. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72330. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72331. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72332. // and avoid problems with multiple concurrent .babylon loads.
  72333. var log = "importScene has failed JSON parse";
  72334. try {
  72335. var parsedData = JSON.parse(data);
  72336. log = "";
  72337. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72338. var index;
  72339. var cache;
  72340. // Lights
  72341. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  72342. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  72343. var parsedLight = parsedData.lights[index];
  72344. var light = BABYLON.Light.Parse(parsedLight, scene);
  72345. if (light) {
  72346. container.lights.push(light);
  72347. log += (index === 0 ? "\n\tLights:" : "");
  72348. log += "\n\t\t" + light.toString(fullDetails);
  72349. }
  72350. }
  72351. }
  72352. // Animations
  72353. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  72354. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  72355. var parsedAnimation = parsedData.animations[index];
  72356. var animation = BABYLON.Animation.Parse(parsedAnimation);
  72357. scene.animations.push(animation);
  72358. container.animations.push(animation);
  72359. log += (index === 0 ? "\n\tAnimations:" : "");
  72360. log += "\n\t\t" + animation.toString(fullDetails);
  72361. }
  72362. }
  72363. // Materials
  72364. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  72365. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72366. var parsedMaterial = parsedData.materials[index];
  72367. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72368. container.materials.push(mat);
  72369. log += (index === 0 ? "\n\tMaterials:" : "");
  72370. log += "\n\t\t" + mat.toString(fullDetails);
  72371. }
  72372. }
  72373. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72374. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  72375. var parsedMultiMaterial = parsedData.multiMaterials[index];
  72376. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72377. container.multiMaterials.push(mmat);
  72378. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  72379. log += "\n\t\t" + mmat.toString(fullDetails);
  72380. }
  72381. }
  72382. // Morph targets
  72383. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72384. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72385. var managerData = _a[_i];
  72386. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  72387. }
  72388. }
  72389. // Skeletons
  72390. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72391. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  72392. var parsedSkeleton = parsedData.skeletons[index];
  72393. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72394. container.skeletons.push(skeleton);
  72395. log += (index === 0 ? "\n\tSkeletons:" : "");
  72396. log += "\n\t\t" + skeleton.toString(fullDetails);
  72397. }
  72398. }
  72399. // Geometries
  72400. var geometries = parsedData.geometries;
  72401. if (geometries !== undefined && geometries !== null) {
  72402. var addedGeometry = new Array();
  72403. // Boxes
  72404. var boxes = geometries.boxes;
  72405. if (boxes !== undefined && boxes !== null) {
  72406. for (index = 0, cache = boxes.length; index < cache; index++) {
  72407. var parsedBox = boxes[index];
  72408. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  72409. }
  72410. }
  72411. // Spheres
  72412. var spheres = geometries.spheres;
  72413. if (spheres !== undefined && spheres !== null) {
  72414. for (index = 0, cache = spheres.length; index < cache; index++) {
  72415. var parsedSphere = spheres[index];
  72416. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  72417. }
  72418. }
  72419. // Cylinders
  72420. var cylinders = geometries.cylinders;
  72421. if (cylinders !== undefined && cylinders !== null) {
  72422. for (index = 0, cache = cylinders.length; index < cache; index++) {
  72423. var parsedCylinder = cylinders[index];
  72424. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  72425. }
  72426. }
  72427. // Toruses
  72428. var toruses = geometries.toruses;
  72429. if (toruses !== undefined && toruses !== null) {
  72430. for (index = 0, cache = toruses.length; index < cache; index++) {
  72431. var parsedTorus = toruses[index];
  72432. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  72433. }
  72434. }
  72435. // Grounds
  72436. var grounds = geometries.grounds;
  72437. if (grounds !== undefined && grounds !== null) {
  72438. for (index = 0, cache = grounds.length; index < cache; index++) {
  72439. var parsedGround = grounds[index];
  72440. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  72441. }
  72442. }
  72443. // Planes
  72444. var planes = geometries.planes;
  72445. if (planes !== undefined && planes !== null) {
  72446. for (index = 0, cache = planes.length; index < cache; index++) {
  72447. var parsedPlane = planes[index];
  72448. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  72449. }
  72450. }
  72451. // TorusKnots
  72452. var torusKnots = geometries.torusKnots;
  72453. if (torusKnots !== undefined && torusKnots !== null) {
  72454. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  72455. var parsedTorusKnot = torusKnots[index];
  72456. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  72457. }
  72458. }
  72459. // VertexData
  72460. var vertexData = geometries.vertexData;
  72461. if (vertexData !== undefined && vertexData !== null) {
  72462. for (index = 0, cache = vertexData.length; index < cache; index++) {
  72463. var parsedVertexData = vertexData[index];
  72464. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  72465. }
  72466. }
  72467. addedGeometry.forEach(function (g) {
  72468. if (g) {
  72469. container.geometries.push(g);
  72470. }
  72471. });
  72472. }
  72473. // Transform nodes
  72474. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  72475. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  72476. var parsedTransformNode = parsedData.transformNodes[index];
  72477. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  72478. container.transformNodes.push(node);
  72479. }
  72480. }
  72481. // Meshes
  72482. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72483. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72484. var parsedMesh = parsedData.meshes[index];
  72485. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72486. container.meshes.push(mesh);
  72487. log += (index === 0 ? "\n\tMeshes:" : "");
  72488. log += "\n\t\t" + mesh.toString(fullDetails);
  72489. }
  72490. }
  72491. // Cameras
  72492. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  72493. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  72494. var parsedCamera = parsedData.cameras[index];
  72495. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  72496. container.cameras.push(camera);
  72497. log += (index === 0 ? "\n\tCameras:" : "");
  72498. log += "\n\t\t" + camera.toString(fullDetails);
  72499. }
  72500. }
  72501. // Animation Groups
  72502. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  72503. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  72504. var parsedAnimationGroup = parsedData.animationGroups[index];
  72505. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  72506. container.animationGroups.push(animationGroup);
  72507. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  72508. log += "\n\t\t" + animationGroup.toString(fullDetails);
  72509. }
  72510. }
  72511. // Browsing all the graph to connect the dots
  72512. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  72513. var camera = scene.cameras[index];
  72514. if (camera._waitingParentId) {
  72515. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  72516. camera._waitingParentId = null;
  72517. }
  72518. }
  72519. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72520. var light_1 = scene.lights[index];
  72521. if (light_1 && light_1._waitingParentId) {
  72522. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  72523. light_1._waitingParentId = null;
  72524. }
  72525. }
  72526. // Connect parents & children and parse actions
  72527. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  72528. var transformNode = scene.transformNodes[index];
  72529. if (transformNode._waitingParentId) {
  72530. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  72531. transformNode._waitingParentId = null;
  72532. }
  72533. }
  72534. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72535. var mesh = scene.meshes[index];
  72536. if (mesh._waitingParentId) {
  72537. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  72538. mesh._waitingParentId = null;
  72539. }
  72540. if (mesh._waitingActions) {
  72541. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  72542. mesh._waitingActions = null;
  72543. }
  72544. }
  72545. // freeze world matrix application
  72546. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72547. var currentMesh = scene.meshes[index];
  72548. if (currentMesh._waitingFreezeWorldMatrix) {
  72549. currentMesh.freezeWorldMatrix();
  72550. currentMesh._waitingFreezeWorldMatrix = null;
  72551. }
  72552. else {
  72553. currentMesh.computeWorldMatrix(true);
  72554. }
  72555. }
  72556. // Lights exclusions / inclusions
  72557. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72558. var light_2 = scene.lights[index];
  72559. // Excluded check
  72560. if (light_2._excludedMeshesIds.length > 0) {
  72561. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  72562. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  72563. if (excludedMesh) {
  72564. light_2.excludedMeshes.push(excludedMesh);
  72565. }
  72566. }
  72567. light_2._excludedMeshesIds = [];
  72568. }
  72569. // Included check
  72570. if (light_2._includedOnlyMeshesIds.length > 0) {
  72571. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  72572. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  72573. if (includedOnlyMesh) {
  72574. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  72575. }
  72576. }
  72577. light_2._includedOnlyMeshesIds = [];
  72578. }
  72579. }
  72580. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  72581. // Actions (scene)
  72582. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  72583. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  72584. }
  72585. if (!addToScene) {
  72586. container.removeAllFromScene();
  72587. }
  72588. }
  72589. catch (err) {
  72590. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  72591. if (onError) {
  72592. onError(msg, err);
  72593. }
  72594. else {
  72595. BABYLON.Tools.Log(msg);
  72596. throw err;
  72597. }
  72598. }
  72599. finally {
  72600. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72601. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72602. }
  72603. }
  72604. return container;
  72605. };
  72606. BABYLON.SceneLoader.RegisterPlugin({
  72607. name: "babylon.js",
  72608. extensions: ".babylon",
  72609. canDirectLoad: function (data) {
  72610. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  72611. return true;
  72612. }
  72613. return false;
  72614. },
  72615. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  72616. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72617. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72618. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72619. // and avoid problems with multiple concurrent .babylon loads.
  72620. var log = "importMesh has failed JSON parse";
  72621. try {
  72622. var parsedData = JSON.parse(data);
  72623. log = "";
  72624. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72625. if (!meshesNames) {
  72626. meshesNames = null;
  72627. }
  72628. else if (!Array.isArray(meshesNames)) {
  72629. meshesNames = [meshesNames];
  72630. }
  72631. var hierarchyIds = new Array();
  72632. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72633. var loadedSkeletonsIds = [];
  72634. var loadedMaterialsIds = [];
  72635. var index;
  72636. var cache;
  72637. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72638. var parsedMesh = parsedData.meshes[index];
  72639. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  72640. if (meshesNames !== null) {
  72641. // Remove found mesh name from list.
  72642. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  72643. }
  72644. //Geometry?
  72645. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  72646. //does the file contain geometries?
  72647. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  72648. //find the correct geometry and add it to the scene
  72649. var found = false;
  72650. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  72651. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  72652. return;
  72653. }
  72654. else {
  72655. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  72656. if (parsedGeometryData.id === parsedMesh.geometryId) {
  72657. switch (geometryType) {
  72658. case "boxes":
  72659. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  72660. break;
  72661. case "spheres":
  72662. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  72663. break;
  72664. case "cylinders":
  72665. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  72666. break;
  72667. case "toruses":
  72668. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  72669. break;
  72670. case "grounds":
  72671. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  72672. break;
  72673. case "planes":
  72674. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  72675. break;
  72676. case "torusKnots":
  72677. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  72678. break;
  72679. case "vertexData":
  72680. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  72681. break;
  72682. }
  72683. found = true;
  72684. }
  72685. });
  72686. }
  72687. });
  72688. if (found === false) {
  72689. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  72690. }
  72691. }
  72692. }
  72693. // Material ?
  72694. if (parsedMesh.materialId) {
  72695. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  72696. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72697. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  72698. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  72699. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  72700. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  72701. var subMatId = parsedMultiMaterial.materials[matIndex];
  72702. loadedMaterialsIds.push(subMatId);
  72703. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  72704. if (mat) {
  72705. log += "\n\tMaterial " + mat.toString(fullDetails);
  72706. }
  72707. }
  72708. loadedMaterialsIds.push(parsedMultiMaterial.id);
  72709. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72710. if (mmat) {
  72711. materialFound = true;
  72712. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  72713. }
  72714. break;
  72715. }
  72716. }
  72717. }
  72718. if (materialFound === false) {
  72719. loadedMaterialsIds.push(parsedMesh.materialId);
  72720. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  72721. if (!mat) {
  72722. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  72723. }
  72724. else {
  72725. log += "\n\tMaterial " + mat.toString(fullDetails);
  72726. }
  72727. }
  72728. }
  72729. // Skeleton ?
  72730. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72731. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  72732. if (skeletonAlreadyLoaded === false) {
  72733. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  72734. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  72735. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  72736. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72737. skeletons.push(skeleton);
  72738. loadedSkeletonsIds.push(parsedSkeleton.id);
  72739. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  72740. }
  72741. }
  72742. }
  72743. }
  72744. // Morph targets ?
  72745. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72746. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72747. var managerData = _a[_i];
  72748. BABYLON.MorphTargetManager.Parse(managerData, scene);
  72749. }
  72750. }
  72751. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72752. meshes.push(mesh);
  72753. log += "\n\tMesh " + mesh.toString(fullDetails);
  72754. }
  72755. }
  72756. // Connecting parents
  72757. var currentMesh;
  72758. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72759. currentMesh = scene.meshes[index];
  72760. if (currentMesh._waitingParentId) {
  72761. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  72762. currentMesh._waitingParentId = null;
  72763. }
  72764. }
  72765. // freeze and compute world matrix application
  72766. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72767. currentMesh = scene.meshes[index];
  72768. if (currentMesh._waitingFreezeWorldMatrix) {
  72769. currentMesh.freezeWorldMatrix();
  72770. currentMesh._waitingFreezeWorldMatrix = null;
  72771. }
  72772. else {
  72773. currentMesh.computeWorldMatrix(true);
  72774. }
  72775. }
  72776. }
  72777. // Particles
  72778. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  72779. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  72780. if (parser) {
  72781. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  72782. var parsedParticleSystem = parsedData.particleSystems[index];
  72783. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  72784. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  72785. }
  72786. }
  72787. }
  72788. }
  72789. return true;
  72790. }
  72791. catch (err) {
  72792. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  72793. if (onError) {
  72794. onError(msg, err);
  72795. }
  72796. else {
  72797. BABYLON.Tools.Log(msg);
  72798. throw err;
  72799. }
  72800. }
  72801. finally {
  72802. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72803. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72804. }
  72805. }
  72806. return false;
  72807. },
  72808. load: function (scene, data, rootUrl, onError) {
  72809. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72810. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72811. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72812. // and avoid problems with multiple concurrent .babylon loads.
  72813. var log = "importScene has failed JSON parse";
  72814. try {
  72815. var parsedData = JSON.parse(data);
  72816. log = "";
  72817. // Scene
  72818. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  72819. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  72820. }
  72821. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  72822. scene.autoClear = parsedData.autoClear;
  72823. }
  72824. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  72825. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  72826. }
  72827. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  72828. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  72829. }
  72830. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  72831. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  72832. }
  72833. // Fog
  72834. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  72835. scene.fogMode = parsedData.fogMode;
  72836. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  72837. scene.fogStart = parsedData.fogStart;
  72838. scene.fogEnd = parsedData.fogEnd;
  72839. scene.fogDensity = parsedData.fogDensity;
  72840. log += "\tFog mode for scene: ";
  72841. switch (scene.fogMode) {
  72842. // getters not compiling, so using hardcoded
  72843. case 1:
  72844. log += "exp\n";
  72845. break;
  72846. case 2:
  72847. log += "exp2\n";
  72848. break;
  72849. case 3:
  72850. log += "linear\n";
  72851. break;
  72852. }
  72853. }
  72854. //Physics
  72855. if (parsedData.physicsEnabled) {
  72856. var physicsPlugin;
  72857. if (parsedData.physicsEngine === "cannon") {
  72858. physicsPlugin = new BABYLON.CannonJSPlugin();
  72859. }
  72860. else if (parsedData.physicsEngine === "oimo") {
  72861. physicsPlugin = new BABYLON.OimoJSPlugin();
  72862. }
  72863. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  72864. //else - default engine, which is currently oimo
  72865. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  72866. scene.enablePhysics(physicsGravity, physicsPlugin);
  72867. }
  72868. // Metadata
  72869. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  72870. scene.metadata = parsedData.metadata;
  72871. }
  72872. //collisions, if defined. otherwise, default is true
  72873. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  72874. scene.collisionsEnabled = parsedData.collisionsEnabled;
  72875. }
  72876. scene.workerCollisions = !!parsedData.workerCollisions;
  72877. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  72878. if (!container) {
  72879. return false;
  72880. }
  72881. if (parsedData.autoAnimate) {
  72882. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  72883. }
  72884. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  72885. scene.setActiveCameraByID(parsedData.activeCameraID);
  72886. }
  72887. // Environment texture
  72888. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  72889. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  72890. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  72891. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  72892. if (parsedData.environmentTextureRotationY) {
  72893. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  72894. }
  72895. scene.environmentTexture = hdrTexture;
  72896. }
  72897. else {
  72898. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  72899. if (parsedData.environmentTextureRotationY) {
  72900. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  72901. }
  72902. scene.environmentTexture = cubeTexture;
  72903. }
  72904. if (parsedData.createDefaultSkybox === true) {
  72905. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  72906. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  72907. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  72908. }
  72909. }
  72910. // Finish
  72911. return true;
  72912. }
  72913. catch (err) {
  72914. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  72915. if (onError) {
  72916. onError(msg, err);
  72917. }
  72918. else {
  72919. BABYLON.Tools.Log(msg);
  72920. throw err;
  72921. }
  72922. }
  72923. finally {
  72924. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72925. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72926. }
  72927. }
  72928. return false;
  72929. },
  72930. loadAssetContainer: function (scene, data, rootUrl, onError) {
  72931. var container = loadAssetContainer(scene, data, rootUrl, onError);
  72932. return container;
  72933. }
  72934. });
  72935. })(BABYLON || (BABYLON = {}));
  72936. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  72937. var BABYLON;
  72938. (function (BABYLON) {
  72939. var FilesInput = /** @class */ (function () {
  72940. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  72941. this.onProcessFileCallback = function () { return true; };
  72942. this._engine = engine;
  72943. this._currentScene = scene;
  72944. this._sceneLoadedCallback = sceneLoadedCallback;
  72945. this._progressCallback = progressCallback;
  72946. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  72947. this._textureLoadingCallback = textureLoadingCallback;
  72948. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  72949. this._onReloadCallback = onReloadCallback;
  72950. this._errorCallback = errorCallback;
  72951. }
  72952. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  72953. var _this = this;
  72954. if (elementToMonitor) {
  72955. this._elementToMonitor = elementToMonitor;
  72956. this._dragEnterHandler = function (e) { _this.drag(e); };
  72957. this._dragOverHandler = function (e) { _this.drag(e); };
  72958. this._dropHandler = function (e) { _this.drop(e); };
  72959. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  72960. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  72961. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  72962. }
  72963. };
  72964. FilesInput.prototype.dispose = function () {
  72965. if (!this._elementToMonitor) {
  72966. return;
  72967. }
  72968. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  72969. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  72970. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  72971. };
  72972. FilesInput.prototype.renderFunction = function () {
  72973. if (this._additionalRenderLoopLogicCallback) {
  72974. this._additionalRenderLoopLogicCallback();
  72975. }
  72976. if (this._currentScene) {
  72977. if (this._textureLoadingCallback) {
  72978. var remaining = this._currentScene.getWaitingItemsCount();
  72979. if (remaining > 0) {
  72980. this._textureLoadingCallback(remaining);
  72981. }
  72982. }
  72983. this._currentScene.render();
  72984. }
  72985. };
  72986. FilesInput.prototype.drag = function (e) {
  72987. e.stopPropagation();
  72988. e.preventDefault();
  72989. };
  72990. FilesInput.prototype.drop = function (eventDrop) {
  72991. eventDrop.stopPropagation();
  72992. eventDrop.preventDefault();
  72993. this.loadFiles(eventDrop);
  72994. };
  72995. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  72996. var _this = this;
  72997. var reader = folder.createReader();
  72998. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  72999. reader.readEntries(function (entries) {
  73000. remaining.count += entries.length;
  73001. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  73002. var entry = entries_1[_i];
  73003. if (entry.isFile) {
  73004. entry.file(function (file) {
  73005. file.correctName = relativePath + file.name;
  73006. files.push(file);
  73007. if (--remaining.count === 0) {
  73008. callback();
  73009. }
  73010. });
  73011. }
  73012. else if (entry.isDirectory) {
  73013. _this._traverseFolder(entry, files, remaining, callback);
  73014. }
  73015. }
  73016. if (--remaining.count) {
  73017. callback();
  73018. }
  73019. });
  73020. };
  73021. FilesInput.prototype._processFiles = function (files) {
  73022. for (var i = 0; i < files.length; i++) {
  73023. var name = files[i].correctName.toLowerCase();
  73024. var extension = name.split('.').pop();
  73025. if (!this.onProcessFileCallback(files[i], name, extension)) {
  73026. continue;
  73027. }
  73028. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  73029. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  73030. this._sceneFileToLoad = files[i];
  73031. }
  73032. FilesInput.FilesToLoad[name] = files[i];
  73033. }
  73034. };
  73035. FilesInput.prototype.loadFiles = function (event) {
  73036. var _this = this;
  73037. // Handling data transfer via drag'n'drop
  73038. if (event && event.dataTransfer && event.dataTransfer.files) {
  73039. this._filesToLoad = event.dataTransfer.files;
  73040. }
  73041. // Handling files from input files
  73042. if (event && event.target && event.target.files) {
  73043. this._filesToLoad = event.target.files;
  73044. }
  73045. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  73046. return;
  73047. }
  73048. if (this._startingProcessingFilesCallback) {
  73049. this._startingProcessingFilesCallback(this._filesToLoad);
  73050. }
  73051. if (this._filesToLoad && this._filesToLoad.length > 0) {
  73052. var files_1 = new Array();
  73053. var folders = [];
  73054. var items = event.dataTransfer ? event.dataTransfer.items : null;
  73055. for (var i = 0; i < this._filesToLoad.length; i++) {
  73056. var fileToLoad = this._filesToLoad[i];
  73057. var name_1 = fileToLoad.name.toLowerCase();
  73058. var entry = void 0;
  73059. fileToLoad.correctName = name_1;
  73060. if (items) {
  73061. var item = items[i];
  73062. if (item.getAsEntry) {
  73063. entry = item.getAsEntry();
  73064. }
  73065. else if (item.webkitGetAsEntry) {
  73066. entry = item.webkitGetAsEntry();
  73067. }
  73068. }
  73069. if (!entry) {
  73070. files_1.push(fileToLoad);
  73071. }
  73072. else {
  73073. if (entry.isDirectory) {
  73074. folders.push(entry);
  73075. }
  73076. else {
  73077. files_1.push(fileToLoad);
  73078. }
  73079. }
  73080. }
  73081. if (folders.length === 0) {
  73082. this._processFiles(files_1);
  73083. this._processReload();
  73084. }
  73085. else {
  73086. var remaining = { count: folders.length };
  73087. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  73088. var folder = folders_1[_i];
  73089. this._traverseFolder(folder, files_1, remaining, function () {
  73090. _this._processFiles(files_1);
  73091. if (remaining.count === 0) {
  73092. _this._processReload();
  73093. }
  73094. });
  73095. }
  73096. }
  73097. }
  73098. };
  73099. FilesInput.prototype._processReload = function () {
  73100. if (this._onReloadCallback) {
  73101. this._onReloadCallback(this._sceneFileToLoad);
  73102. }
  73103. else {
  73104. this.reload();
  73105. }
  73106. };
  73107. FilesInput.prototype.reload = function () {
  73108. var _this = this;
  73109. // If a scene file has been provided
  73110. if (this._sceneFileToLoad) {
  73111. if (this._currentScene) {
  73112. if (BABYLON.Tools.errorsCount > 0) {
  73113. BABYLON.Tools.ClearLogCache();
  73114. }
  73115. this._engine.stopRenderLoop();
  73116. }
  73117. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  73118. if (_this._progressCallback) {
  73119. _this._progressCallback(progress);
  73120. }
  73121. }).then(function (scene) {
  73122. if (_this._currentScene) {
  73123. _this._currentScene.dispose();
  73124. }
  73125. _this._currentScene = scene;
  73126. if (_this._sceneLoadedCallback) {
  73127. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  73128. }
  73129. // Wait for textures and shaders to be ready
  73130. _this._currentScene.executeWhenReady(function () {
  73131. _this._engine.runRenderLoop(function () {
  73132. _this.renderFunction();
  73133. });
  73134. });
  73135. }).catch(function (error) {
  73136. if (_this._errorCallback) {
  73137. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  73138. }
  73139. });
  73140. }
  73141. else {
  73142. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  73143. }
  73144. };
  73145. FilesInput.FilesToLoad = {};
  73146. return FilesInput;
  73147. }());
  73148. BABYLON.FilesInput = FilesInput;
  73149. })(BABYLON || (BABYLON = {}));
  73150. //# sourceMappingURL=babylon.filesInput.js.map
  73151. var BABYLON;
  73152. (function (BABYLON) {
  73153. var Tags = /** @class */ (function () {
  73154. function Tags() {
  73155. }
  73156. Tags.EnableFor = function (obj) {
  73157. obj._tags = obj._tags || {};
  73158. obj.hasTags = function () {
  73159. return Tags.HasTags(obj);
  73160. };
  73161. obj.addTags = function (tagsString) {
  73162. return Tags.AddTagsTo(obj, tagsString);
  73163. };
  73164. obj.removeTags = function (tagsString) {
  73165. return Tags.RemoveTagsFrom(obj, tagsString);
  73166. };
  73167. obj.matchesTagsQuery = function (tagsQuery) {
  73168. return Tags.MatchesQuery(obj, tagsQuery);
  73169. };
  73170. };
  73171. Tags.DisableFor = function (obj) {
  73172. delete obj._tags;
  73173. delete obj.hasTags;
  73174. delete obj.addTags;
  73175. delete obj.removeTags;
  73176. delete obj.matchesTagsQuery;
  73177. };
  73178. Tags.HasTags = function (obj) {
  73179. if (!obj._tags) {
  73180. return false;
  73181. }
  73182. return !BABYLON.Tools.IsEmpty(obj._tags);
  73183. };
  73184. Tags.GetTags = function (obj, asString) {
  73185. if (asString === void 0) { asString = true; }
  73186. if (!obj._tags) {
  73187. return null;
  73188. }
  73189. if (asString) {
  73190. var tagsArray = [];
  73191. for (var tag in obj._tags) {
  73192. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  73193. tagsArray.push(tag);
  73194. }
  73195. }
  73196. return tagsArray.join(" ");
  73197. }
  73198. else {
  73199. return obj._tags;
  73200. }
  73201. };
  73202. // the tags 'true' and 'false' are reserved and cannot be used as tags
  73203. // a tag cannot start with '||', '&&', and '!'
  73204. // it cannot contain whitespaces
  73205. Tags.AddTagsTo = function (obj, tagsString) {
  73206. if (!tagsString) {
  73207. return;
  73208. }
  73209. if (typeof tagsString !== "string") {
  73210. return;
  73211. }
  73212. var tags = tagsString.split(" ");
  73213. tags.forEach(function (tag, index, array) {
  73214. Tags._AddTagTo(obj, tag);
  73215. });
  73216. };
  73217. Tags._AddTagTo = function (obj, tag) {
  73218. tag = tag.trim();
  73219. if (tag === "" || tag === "true" || tag === "false") {
  73220. return;
  73221. }
  73222. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  73223. return;
  73224. }
  73225. Tags.EnableFor(obj);
  73226. obj._tags[tag] = true;
  73227. };
  73228. Tags.RemoveTagsFrom = function (obj, tagsString) {
  73229. if (!Tags.HasTags(obj)) {
  73230. return;
  73231. }
  73232. var tags = tagsString.split(" ");
  73233. for (var t in tags) {
  73234. Tags._RemoveTagFrom(obj, tags[t]);
  73235. }
  73236. };
  73237. Tags._RemoveTagFrom = function (obj, tag) {
  73238. delete obj._tags[tag];
  73239. };
  73240. Tags.MatchesQuery = function (obj, tagsQuery) {
  73241. if (tagsQuery === undefined) {
  73242. return true;
  73243. }
  73244. if (tagsQuery === "") {
  73245. return Tags.HasTags(obj);
  73246. }
  73247. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  73248. };
  73249. return Tags;
  73250. }());
  73251. BABYLON.Tags = Tags;
  73252. })(BABYLON || (BABYLON = {}));
  73253. //# sourceMappingURL=babylon.tags.js.map
  73254. var BABYLON;
  73255. (function (BABYLON) {
  73256. /**
  73257. * Class used to evalaute queries containing `and` and `or` operators
  73258. */
  73259. var AndOrNotEvaluator = /** @class */ (function () {
  73260. function AndOrNotEvaluator() {
  73261. }
  73262. /**
  73263. * Evaluate a query
  73264. * @param query defines the query to evaluate
  73265. * @param evaluateCallback defines the callback used to filter result
  73266. * @returns true if the query matches
  73267. */
  73268. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  73269. if (!query.match(/\([^\(\)]*\)/g)) {
  73270. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  73271. }
  73272. else {
  73273. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  73274. // remove parenthesis
  73275. r = r.slice(1, r.length - 1);
  73276. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  73277. });
  73278. }
  73279. if (query === "true") {
  73280. return true;
  73281. }
  73282. if (query === "false") {
  73283. return false;
  73284. }
  73285. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  73286. };
  73287. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  73288. evaluateCallback = evaluateCallback || (function (r) {
  73289. return r === "true" ? true : false;
  73290. });
  73291. var result;
  73292. var or = parenthesisContent.split("||");
  73293. for (var i in or) {
  73294. if (or.hasOwnProperty(i)) {
  73295. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  73296. var and = ori.split("&&");
  73297. if (and.length > 1) {
  73298. for (var j = 0; j < and.length; ++j) {
  73299. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  73300. if (andj !== "true" && andj !== "false") {
  73301. if (andj[0] === "!") {
  73302. result = !evaluateCallback(andj.substring(1));
  73303. }
  73304. else {
  73305. result = evaluateCallback(andj);
  73306. }
  73307. }
  73308. else {
  73309. result = andj === "true" ? true : false;
  73310. }
  73311. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  73312. ori = "false";
  73313. break;
  73314. }
  73315. }
  73316. }
  73317. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  73318. result = true;
  73319. break;
  73320. }
  73321. // result equals false (or undefined)
  73322. if (ori !== "true" && ori !== "false") {
  73323. if (ori[0] === "!") {
  73324. result = !evaluateCallback(ori.substring(1));
  73325. }
  73326. else {
  73327. result = evaluateCallback(ori);
  73328. }
  73329. }
  73330. else {
  73331. result = ori === "true" ? true : false;
  73332. }
  73333. }
  73334. }
  73335. // the whole parenthesis scope is replaced by 'true' or 'false'
  73336. return result ? "true" : "false";
  73337. };
  73338. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  73339. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  73340. // remove whitespaces
  73341. r = r.replace(/[\s]/g, function () { return ""; });
  73342. return r.length % 2 ? "!" : "";
  73343. });
  73344. booleanString = booleanString.trim();
  73345. if (booleanString === "!true") {
  73346. booleanString = "false";
  73347. }
  73348. else if (booleanString === "!false") {
  73349. booleanString = "true";
  73350. }
  73351. return booleanString;
  73352. };
  73353. return AndOrNotEvaluator;
  73354. }());
  73355. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  73356. })(BABYLON || (BABYLON = {}));
  73357. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  73358. var BABYLON;
  73359. (function (BABYLON) {
  73360. /**
  73361. * Class used to enable access to IndexedDB
  73362. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  73363. */
  73364. var Database = /** @class */ (function () {
  73365. /**
  73366. * Creates a new Database
  73367. * @param urlToScene defines the url to load the scene
  73368. * @param callbackManifestChecked defines the callback to use when manifest is checked
  73369. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  73370. */
  73371. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  73372. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  73373. var _this = this;
  73374. // Handling various flavors of prefixed version of IndexedDB
  73375. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  73376. this.callbackManifestChecked = callbackManifestChecked;
  73377. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  73378. this.db = null;
  73379. this._enableSceneOffline = false;
  73380. this._enableTexturesOffline = false;
  73381. this.manifestVersionFound = 0;
  73382. this.mustUpdateRessources = false;
  73383. this.hasReachedQuota = false;
  73384. if (!Database.IDBStorageEnabled) {
  73385. this.callbackManifestChecked(true);
  73386. }
  73387. else {
  73388. if (disableManifestCheck) {
  73389. this._enableSceneOffline = true;
  73390. this._enableTexturesOffline = true;
  73391. this.manifestVersionFound = 1;
  73392. BABYLON.Tools.SetImmediate(function () {
  73393. _this.callbackManifestChecked(true);
  73394. });
  73395. }
  73396. else {
  73397. this._checkManifestFile();
  73398. }
  73399. }
  73400. }
  73401. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  73402. /**
  73403. * Gets a boolean indicating if scene must be saved in the database
  73404. */
  73405. get: function () {
  73406. return this._enableSceneOffline;
  73407. },
  73408. enumerable: true,
  73409. configurable: true
  73410. });
  73411. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  73412. /**
  73413. * Gets a boolean indicating if textures must be saved in the database
  73414. */
  73415. get: function () {
  73416. return this._enableTexturesOffline;
  73417. },
  73418. enumerable: true,
  73419. configurable: true
  73420. });
  73421. Database.prototype._checkManifestFile = function () {
  73422. var _this = this;
  73423. var noManifestFile = function () {
  73424. _this._enableSceneOffline = false;
  73425. _this._enableTexturesOffline = false;
  73426. _this.callbackManifestChecked(false);
  73427. };
  73428. var timeStampUsed = false;
  73429. var manifestURL = this.currentSceneUrl + ".manifest";
  73430. var xhr = new XMLHttpRequest();
  73431. if (navigator.onLine) {
  73432. // Adding a timestamp to by-pass browsers' cache
  73433. timeStampUsed = true;
  73434. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  73435. }
  73436. xhr.open("GET", manifestURL, true);
  73437. xhr.addEventListener("load", function () {
  73438. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73439. try {
  73440. var manifestFile = JSON.parse(xhr.response);
  73441. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  73442. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  73443. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  73444. _this.manifestVersionFound = manifestFile.version;
  73445. }
  73446. if (_this.callbackManifestChecked) {
  73447. _this.callbackManifestChecked(true);
  73448. }
  73449. }
  73450. catch (ex) {
  73451. noManifestFile();
  73452. }
  73453. }
  73454. else {
  73455. noManifestFile();
  73456. }
  73457. }, false);
  73458. xhr.addEventListener("error", function (event) {
  73459. if (timeStampUsed) {
  73460. timeStampUsed = false;
  73461. // Let's retry without the timeStamp
  73462. // It could fail when coupled with HTML5 Offline API
  73463. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  73464. xhr.open("GET", retryManifestURL, true);
  73465. xhr.send();
  73466. }
  73467. else {
  73468. noManifestFile();
  73469. }
  73470. }, false);
  73471. try {
  73472. xhr.send();
  73473. }
  73474. catch (ex) {
  73475. BABYLON.Tools.Error("Error on XHR send request.");
  73476. this.callbackManifestChecked(false);
  73477. }
  73478. };
  73479. /**
  73480. * Open the database and make it available
  73481. * @param successCallback defines the callback to call on success
  73482. * @param errorCallback defines the callback to call on error
  73483. */
  73484. Database.prototype.openAsync = function (successCallback, errorCallback) {
  73485. var _this = this;
  73486. var handleError = function () {
  73487. _this.isSupported = false;
  73488. if (errorCallback)
  73489. errorCallback();
  73490. };
  73491. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  73492. // Your browser doesn't support IndexedDB
  73493. this.isSupported = false;
  73494. if (errorCallback)
  73495. errorCallback();
  73496. }
  73497. else {
  73498. // If the DB hasn't been opened or created yet
  73499. if (!this.db) {
  73500. this.hasReachedQuota = false;
  73501. this.isSupported = true;
  73502. var request = this.idbFactory.open("babylonjs", 1);
  73503. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  73504. request.onerror = function (event) {
  73505. handleError();
  73506. };
  73507. // executes when a version change transaction cannot complete due to other active transactions
  73508. request.onblocked = function (event) {
  73509. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  73510. handleError();
  73511. };
  73512. // DB has been opened successfully
  73513. request.onsuccess = function (event) {
  73514. _this.db = request.result;
  73515. successCallback();
  73516. };
  73517. // Initialization of the DB. Creating Scenes & Textures stores
  73518. request.onupgradeneeded = function (event) {
  73519. _this.db = (event.target).result;
  73520. if (_this.db) {
  73521. try {
  73522. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  73523. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  73524. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  73525. }
  73526. catch (ex) {
  73527. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  73528. handleError();
  73529. }
  73530. }
  73531. };
  73532. }
  73533. // DB has already been created and opened
  73534. else {
  73535. if (successCallback)
  73536. successCallback();
  73537. }
  73538. }
  73539. };
  73540. /**
  73541. * Loads an image from the database
  73542. * @param url defines the url to load from
  73543. * @param image defines the target DOM image
  73544. */
  73545. Database.prototype.loadImageFromDB = function (url, image) {
  73546. var _this = this;
  73547. var completeURL = Database._ReturnFullUrlLocation(url);
  73548. var saveAndLoadImage = function () {
  73549. if (!_this.hasReachedQuota && _this.db !== null) {
  73550. // the texture is not yet in the DB, let's try to save it
  73551. _this._saveImageIntoDBAsync(completeURL, image);
  73552. }
  73553. // If the texture is not in the DB and we've reached the DB quota limit
  73554. // let's load it directly from the web
  73555. else {
  73556. image.src = url;
  73557. }
  73558. };
  73559. if (!this.mustUpdateRessources) {
  73560. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  73561. }
  73562. // First time we're download the images or update requested in the manifest file by a version change
  73563. else {
  73564. saveAndLoadImage();
  73565. }
  73566. };
  73567. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  73568. if (this.isSupported && this.db !== null) {
  73569. var texture;
  73570. var transaction = this.db.transaction(["textures"]);
  73571. transaction.onabort = function (event) {
  73572. image.src = url;
  73573. };
  73574. transaction.oncomplete = function (event) {
  73575. var blobTextureURL;
  73576. if (texture) {
  73577. var URL = window.URL || window.webkitURL;
  73578. blobTextureURL = URL.createObjectURL(texture.data);
  73579. image.onerror = function () {
  73580. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  73581. image.src = url;
  73582. };
  73583. image.src = blobTextureURL;
  73584. }
  73585. else {
  73586. notInDBCallback();
  73587. }
  73588. };
  73589. var getRequest = transaction.objectStore("textures").get(url);
  73590. getRequest.onsuccess = function (event) {
  73591. texture = (event.target).result;
  73592. };
  73593. getRequest.onerror = function (event) {
  73594. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  73595. image.src = url;
  73596. };
  73597. }
  73598. else {
  73599. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73600. image.src = url;
  73601. }
  73602. };
  73603. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  73604. var _this = this;
  73605. if (this.isSupported) {
  73606. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  73607. var generateBlobUrl = function () {
  73608. var blobTextureURL;
  73609. if (blob) {
  73610. var URL = window.URL || window.webkitURL;
  73611. try {
  73612. blobTextureURL = URL.createObjectURL(blob);
  73613. }
  73614. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  73615. catch (ex) {
  73616. blobTextureURL = URL.createObjectURL(blob);
  73617. }
  73618. }
  73619. if (blobTextureURL) {
  73620. image.src = blobTextureURL;
  73621. }
  73622. };
  73623. if (Database.IsUASupportingBlobStorage) { // Create XHR
  73624. var xhr = new XMLHttpRequest(), blob;
  73625. xhr.open("GET", url, true);
  73626. xhr.responseType = "blob";
  73627. xhr.addEventListener("load", function () {
  73628. if (xhr.status === 200 && _this.db) {
  73629. // Blob as response (XHR2)
  73630. blob = xhr.response;
  73631. var transaction = _this.db.transaction(["textures"], "readwrite");
  73632. // the transaction could abort because of a QuotaExceededError error
  73633. transaction.onabort = function (event) {
  73634. try {
  73635. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73636. var srcElement = (event.srcElement || event.target);
  73637. var error = srcElement.error;
  73638. if (error && error.name === "QuotaExceededError") {
  73639. _this.hasReachedQuota = true;
  73640. }
  73641. }
  73642. catch (ex) { }
  73643. generateBlobUrl();
  73644. };
  73645. transaction.oncomplete = function (event) {
  73646. generateBlobUrl();
  73647. };
  73648. var newTexture = { textureUrl: url, data: blob };
  73649. try {
  73650. // Put the blob into the dabase
  73651. var addRequest = transaction.objectStore("textures").put(newTexture);
  73652. addRequest.onsuccess = function (event) {
  73653. };
  73654. addRequest.onerror = function (event) {
  73655. generateBlobUrl();
  73656. };
  73657. }
  73658. catch (ex) {
  73659. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  73660. if (ex.code === 25) {
  73661. Database.IsUASupportingBlobStorage = false;
  73662. }
  73663. image.src = url;
  73664. }
  73665. }
  73666. else {
  73667. image.src = url;
  73668. }
  73669. }, false);
  73670. xhr.addEventListener("error", function (event) {
  73671. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  73672. image.src = url;
  73673. }, false);
  73674. xhr.send();
  73675. }
  73676. else {
  73677. image.src = url;
  73678. }
  73679. }
  73680. else {
  73681. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73682. image.src = url;
  73683. }
  73684. };
  73685. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  73686. var _this = this;
  73687. var updateVersion = function () {
  73688. // the version is not yet in the DB or we need to update it
  73689. _this._saveVersionIntoDBAsync(url, versionLoaded);
  73690. };
  73691. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  73692. };
  73693. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  73694. var _this = this;
  73695. if (this.isSupported && this.db) {
  73696. var version;
  73697. try {
  73698. var transaction = this.db.transaction(["versions"]);
  73699. transaction.oncomplete = function (event) {
  73700. if (version) {
  73701. // If the version in the JSON file is different from the version in DB
  73702. if (_this.manifestVersionFound !== version.data) {
  73703. _this.mustUpdateRessources = true;
  73704. updateInDBCallback();
  73705. }
  73706. else {
  73707. callback(version.data);
  73708. }
  73709. }
  73710. // version was not found in DB
  73711. else {
  73712. _this.mustUpdateRessources = true;
  73713. updateInDBCallback();
  73714. }
  73715. };
  73716. transaction.onabort = function (event) {
  73717. callback(-1);
  73718. };
  73719. var getRequest = transaction.objectStore("versions").get(url);
  73720. getRequest.onsuccess = function (event) {
  73721. version = (event.target).result;
  73722. };
  73723. getRequest.onerror = function (event) {
  73724. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  73725. callback(-1);
  73726. };
  73727. }
  73728. catch (ex) {
  73729. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  73730. callback(-1);
  73731. }
  73732. }
  73733. else {
  73734. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73735. callback(-1);
  73736. }
  73737. };
  73738. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  73739. var _this = this;
  73740. if (this.isSupported && !this.hasReachedQuota && this.db) {
  73741. try {
  73742. // Open a transaction to the database
  73743. var transaction = this.db.transaction(["versions"], "readwrite");
  73744. // the transaction could abort because of a QuotaExceededError error
  73745. transaction.onabort = function (event) {
  73746. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73747. var error = event.srcElement['error'];
  73748. if (error && error.name === "QuotaExceededError") {
  73749. _this.hasReachedQuota = true;
  73750. }
  73751. }
  73752. catch (ex) { }
  73753. callback(-1);
  73754. };
  73755. transaction.oncomplete = function (event) {
  73756. callback(_this.manifestVersionFound);
  73757. };
  73758. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  73759. // Put the scene into the database
  73760. var addRequest = transaction.objectStore("versions").put(newVersion);
  73761. addRequest.onsuccess = function (event) {
  73762. };
  73763. addRequest.onerror = function (event) {
  73764. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  73765. };
  73766. }
  73767. catch (ex) {
  73768. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  73769. callback(-1);
  73770. }
  73771. }
  73772. else {
  73773. callback(-1);
  73774. }
  73775. };
  73776. /**
  73777. * Loads a file from database
  73778. * @param url defines the URL to load from
  73779. * @param sceneLoaded defines a callback to call on success
  73780. * @param progressCallBack defines a callback to call when progress changed
  73781. * @param errorCallback defines a callback to call on error
  73782. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  73783. */
  73784. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  73785. var _this = this;
  73786. var completeUrl = Database._ReturnFullUrlLocation(url);
  73787. var saveAndLoadFile = function () {
  73788. // the scene is not yet in the DB, let's try to save it
  73789. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73790. };
  73791. this._checkVersionFromDB(completeUrl, function (version) {
  73792. if (version !== -1) {
  73793. if (!_this.mustUpdateRessources) {
  73794. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  73795. }
  73796. else {
  73797. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73798. }
  73799. }
  73800. else {
  73801. if (errorCallback) {
  73802. errorCallback();
  73803. }
  73804. }
  73805. });
  73806. };
  73807. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  73808. if (this.isSupported && this.db) {
  73809. var targetStore;
  73810. if (url.indexOf(".babylon") !== -1) {
  73811. targetStore = "scenes";
  73812. }
  73813. else {
  73814. targetStore = "textures";
  73815. }
  73816. var file;
  73817. var transaction = this.db.transaction([targetStore]);
  73818. transaction.oncomplete = function (event) {
  73819. if (file) {
  73820. callback(file.data);
  73821. }
  73822. // file was not found in DB
  73823. else {
  73824. notInDBCallback();
  73825. }
  73826. };
  73827. transaction.onabort = function (event) {
  73828. notInDBCallback();
  73829. };
  73830. var getRequest = transaction.objectStore(targetStore).get(url);
  73831. getRequest.onsuccess = function (event) {
  73832. file = (event.target).result;
  73833. };
  73834. getRequest.onerror = function (event) {
  73835. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  73836. notInDBCallback();
  73837. };
  73838. }
  73839. else {
  73840. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73841. callback();
  73842. }
  73843. };
  73844. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  73845. var _this = this;
  73846. if (this.isSupported) {
  73847. var targetStore;
  73848. if (url.indexOf(".babylon") !== -1) {
  73849. targetStore = "scenes";
  73850. }
  73851. else {
  73852. targetStore = "textures";
  73853. }
  73854. // Create XHR
  73855. var xhr = new XMLHttpRequest();
  73856. var fileData;
  73857. xhr.open("GET", url + "?" + Date.now(), true);
  73858. if (useArrayBuffer) {
  73859. xhr.responseType = "arraybuffer";
  73860. }
  73861. if (progressCallback) {
  73862. xhr.onprogress = progressCallback;
  73863. }
  73864. xhr.addEventListener("load", function () {
  73865. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  73866. // Blob as response (XHR2)
  73867. //fileData = xhr.responseText;
  73868. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  73869. if (!_this.hasReachedQuota && _this.db) {
  73870. // Open a transaction to the database
  73871. var transaction = _this.db.transaction([targetStore], "readwrite");
  73872. // the transaction could abort because of a QuotaExceededError error
  73873. transaction.onabort = function (event) {
  73874. try {
  73875. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73876. var error = event.srcElement['error'];
  73877. if (error && error.name === "QuotaExceededError") {
  73878. _this.hasReachedQuota = true;
  73879. }
  73880. }
  73881. catch (ex) { }
  73882. callback(fileData);
  73883. };
  73884. transaction.oncomplete = function (event) {
  73885. callback(fileData);
  73886. };
  73887. var newFile;
  73888. if (targetStore === "scenes") {
  73889. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  73890. }
  73891. else {
  73892. newFile = { textureUrl: url, data: fileData };
  73893. }
  73894. try {
  73895. // Put the scene into the database
  73896. var addRequest = transaction.objectStore(targetStore).put(newFile);
  73897. addRequest.onsuccess = function (event) {
  73898. };
  73899. addRequest.onerror = function (event) {
  73900. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  73901. };
  73902. }
  73903. catch (ex) {
  73904. callback(fileData);
  73905. }
  73906. }
  73907. else {
  73908. callback(fileData);
  73909. }
  73910. }
  73911. else {
  73912. if (xhr.status >= 400 && errorCallback) {
  73913. errorCallback(xhr);
  73914. }
  73915. else {
  73916. callback();
  73917. }
  73918. }
  73919. }, false);
  73920. xhr.addEventListener("error", function (event) {
  73921. BABYLON.Tools.Error("error on XHR request.");
  73922. callback();
  73923. }, false);
  73924. xhr.send();
  73925. }
  73926. else {
  73927. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73928. callback();
  73929. }
  73930. };
  73931. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  73932. Database.IsUASupportingBlobStorage = true;
  73933. /** Gets a boolean indicating if Database storate is enabled */
  73934. Database.IDBStorageEnabled = true;
  73935. Database._ParseURL = function (url) {
  73936. var a = document.createElement('a');
  73937. a.href = url;
  73938. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  73939. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  73940. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  73941. return absLocation;
  73942. };
  73943. Database._ReturnFullUrlLocation = function (url) {
  73944. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  73945. return (Database._ParseURL(window.location.href) + url);
  73946. }
  73947. else {
  73948. return url;
  73949. }
  73950. };
  73951. return Database;
  73952. }());
  73953. BABYLON.Database = Database;
  73954. })(BABYLON || (BABYLON = {}));
  73955. //# sourceMappingURL=babylon.database.js.map
  73956. var BABYLON;
  73957. (function (BABYLON) {
  73958. var FresnelParameters = /** @class */ (function () {
  73959. function FresnelParameters() {
  73960. this._isEnabled = true;
  73961. this.leftColor = BABYLON.Color3.White();
  73962. this.rightColor = BABYLON.Color3.Black();
  73963. this.bias = 0;
  73964. this.power = 1;
  73965. }
  73966. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  73967. get: function () {
  73968. return this._isEnabled;
  73969. },
  73970. set: function (value) {
  73971. if (this._isEnabled === value) {
  73972. return;
  73973. }
  73974. this._isEnabled = value;
  73975. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  73976. },
  73977. enumerable: true,
  73978. configurable: true
  73979. });
  73980. FresnelParameters.prototype.clone = function () {
  73981. var newFresnelParameters = new FresnelParameters();
  73982. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  73983. return newFresnelParameters;
  73984. };
  73985. FresnelParameters.prototype.serialize = function () {
  73986. var serializationObject = {};
  73987. serializationObject.isEnabled = this.isEnabled;
  73988. serializationObject.leftColor = this.leftColor.asArray();
  73989. serializationObject.rightColor = this.rightColor.asArray();
  73990. serializationObject.bias = this.bias;
  73991. serializationObject.power = this.power;
  73992. return serializationObject;
  73993. };
  73994. FresnelParameters.Parse = function (parsedFresnelParameters) {
  73995. var fresnelParameters = new FresnelParameters();
  73996. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  73997. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  73998. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  73999. fresnelParameters.bias = parsedFresnelParameters.bias;
  74000. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  74001. return fresnelParameters;
  74002. };
  74003. return FresnelParameters;
  74004. }());
  74005. BABYLON.FresnelParameters = FresnelParameters;
  74006. })(BABYLON || (BABYLON = {}));
  74007. //# sourceMappingURL=babylon.fresnelParameters.js.map
  74008. var BABYLON;
  74009. (function (BABYLON) {
  74010. var MultiMaterial = /** @class */ (function (_super) {
  74011. __extends(MultiMaterial, _super);
  74012. function MultiMaterial(name, scene) {
  74013. var _this = _super.call(this, name, scene, true) || this;
  74014. scene.multiMaterials.push(_this);
  74015. _this.subMaterials = new Array();
  74016. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  74017. return _this;
  74018. }
  74019. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  74020. get: function () {
  74021. return this._subMaterials;
  74022. },
  74023. set: function (value) {
  74024. this._subMaterials = value;
  74025. this._hookArray(value);
  74026. },
  74027. enumerable: true,
  74028. configurable: true
  74029. });
  74030. MultiMaterial.prototype._hookArray = function (array) {
  74031. var _this = this;
  74032. var oldPush = array.push;
  74033. array.push = function () {
  74034. var items = [];
  74035. for (var _i = 0; _i < arguments.length; _i++) {
  74036. items[_i] = arguments[_i];
  74037. }
  74038. var result = oldPush.apply(array, items);
  74039. _this._markAllSubMeshesAsTexturesDirty();
  74040. return result;
  74041. };
  74042. var oldSplice = array.splice;
  74043. array.splice = function (index, deleteCount) {
  74044. var deleted = oldSplice.apply(array, [index, deleteCount]);
  74045. _this._markAllSubMeshesAsTexturesDirty();
  74046. return deleted;
  74047. };
  74048. };
  74049. // Properties
  74050. MultiMaterial.prototype.getSubMaterial = function (index) {
  74051. if (index < 0 || index >= this.subMaterials.length) {
  74052. return this.getScene().defaultMaterial;
  74053. }
  74054. return this.subMaterials[index];
  74055. };
  74056. MultiMaterial.prototype.getActiveTextures = function () {
  74057. var _a;
  74058. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  74059. if (subMaterial) {
  74060. return subMaterial.getActiveTextures();
  74061. }
  74062. else {
  74063. return [];
  74064. }
  74065. }));
  74066. };
  74067. // Methods
  74068. MultiMaterial.prototype.getClassName = function () {
  74069. return "MultiMaterial";
  74070. };
  74071. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74072. for (var index = 0; index < this.subMaterials.length; index++) {
  74073. var subMaterial = this.subMaterials[index];
  74074. if (subMaterial) {
  74075. if (subMaterial.storeEffectOnSubMeshes) {
  74076. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  74077. return false;
  74078. }
  74079. continue;
  74080. }
  74081. if (!subMaterial.isReady(mesh)) {
  74082. return false;
  74083. }
  74084. }
  74085. }
  74086. return true;
  74087. };
  74088. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  74089. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  74090. for (var index = 0; index < this.subMaterials.length; index++) {
  74091. var subMaterial = null;
  74092. var current = this.subMaterials[index];
  74093. if (cloneChildren && current) {
  74094. subMaterial = current.clone(name + "-" + current.name);
  74095. }
  74096. else {
  74097. subMaterial = this.subMaterials[index];
  74098. }
  74099. newMultiMaterial.subMaterials.push(subMaterial);
  74100. }
  74101. return newMultiMaterial;
  74102. };
  74103. MultiMaterial.prototype.serialize = function () {
  74104. var serializationObject = {};
  74105. serializationObject.name = this.name;
  74106. serializationObject.id = this.id;
  74107. if (BABYLON.Tags) {
  74108. serializationObject.tags = BABYLON.Tags.GetTags(this);
  74109. }
  74110. serializationObject.materials = [];
  74111. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  74112. var subMat = this.subMaterials[matIndex];
  74113. if (subMat) {
  74114. serializationObject.materials.push(subMat.id);
  74115. }
  74116. else {
  74117. serializationObject.materials.push(null);
  74118. }
  74119. }
  74120. return serializationObject;
  74121. };
  74122. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  74123. var scene = this.getScene();
  74124. if (!scene) {
  74125. return;
  74126. }
  74127. var index = scene.multiMaterials.indexOf(this);
  74128. if (index >= 0) {
  74129. scene.multiMaterials.splice(index, 1);
  74130. }
  74131. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  74132. };
  74133. return MultiMaterial;
  74134. }(BABYLON.Material));
  74135. BABYLON.MultiMaterial = MultiMaterial;
  74136. })(BABYLON || (BABYLON = {}));
  74137. //# sourceMappingURL=babylon.multiMaterial.js.map
  74138. var BABYLON;
  74139. (function (BABYLON) {
  74140. var FreeCameraTouchInput = /** @class */ (function () {
  74141. function FreeCameraTouchInput() {
  74142. this._offsetX = null;
  74143. this._offsetY = null;
  74144. this._pointerPressed = new Array();
  74145. this.touchAngularSensibility = 200000.0;
  74146. this.touchMoveSensibility = 250.0;
  74147. }
  74148. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  74149. var _this = this;
  74150. var previousPosition = null;
  74151. if (this._pointerInput === undefined) {
  74152. this._onLostFocus = function (evt) {
  74153. _this._offsetX = null;
  74154. _this._offsetY = null;
  74155. };
  74156. this._pointerInput = function (p, s) {
  74157. var evt = p.event;
  74158. if (evt.pointerType === "mouse") {
  74159. return;
  74160. }
  74161. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74162. if (!noPreventDefault) {
  74163. evt.preventDefault();
  74164. }
  74165. _this._pointerPressed.push(evt.pointerId);
  74166. if (_this._pointerPressed.length !== 1) {
  74167. return;
  74168. }
  74169. previousPosition = {
  74170. x: evt.clientX,
  74171. y: evt.clientY
  74172. };
  74173. }
  74174. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  74175. if (!noPreventDefault) {
  74176. evt.preventDefault();
  74177. }
  74178. var index = _this._pointerPressed.indexOf(evt.pointerId);
  74179. if (index === -1) {
  74180. return;
  74181. }
  74182. _this._pointerPressed.splice(index, 1);
  74183. if (index != 0) {
  74184. return;
  74185. }
  74186. previousPosition = null;
  74187. _this._offsetX = null;
  74188. _this._offsetY = null;
  74189. }
  74190. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  74191. if (!noPreventDefault) {
  74192. evt.preventDefault();
  74193. }
  74194. if (!previousPosition) {
  74195. return;
  74196. }
  74197. var index = _this._pointerPressed.indexOf(evt.pointerId);
  74198. if (index != 0) {
  74199. return;
  74200. }
  74201. _this._offsetX = evt.clientX - previousPosition.x;
  74202. _this._offsetY = -(evt.clientY - previousPosition.y);
  74203. }
  74204. };
  74205. }
  74206. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  74207. if (this._onLostFocus) {
  74208. element.addEventListener("blur", this._onLostFocus);
  74209. }
  74210. };
  74211. FreeCameraTouchInput.prototype.detachControl = function (element) {
  74212. if (this._pointerInput && element) {
  74213. if (this._observer) {
  74214. this.camera.getScene().onPointerObservable.remove(this._observer);
  74215. this._observer = null;
  74216. }
  74217. if (this._onLostFocus) {
  74218. element.removeEventListener("blur", this._onLostFocus);
  74219. this._onLostFocus = null;
  74220. }
  74221. this._pointerPressed = [];
  74222. this._offsetX = null;
  74223. this._offsetY = null;
  74224. }
  74225. };
  74226. FreeCameraTouchInput.prototype.checkInputs = function () {
  74227. if (this._offsetX && this._offsetY) {
  74228. var camera = this.camera;
  74229. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  74230. if (this._pointerPressed.length > 1) {
  74231. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  74232. }
  74233. else {
  74234. var speed = camera._computeLocalCameraSpeed();
  74235. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  74236. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  74237. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  74238. }
  74239. }
  74240. };
  74241. FreeCameraTouchInput.prototype.getClassName = function () {
  74242. return "FreeCameraTouchInput";
  74243. };
  74244. FreeCameraTouchInput.prototype.getSimpleName = function () {
  74245. return "touch";
  74246. };
  74247. __decorate([
  74248. BABYLON.serialize()
  74249. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  74250. __decorate([
  74251. BABYLON.serialize()
  74252. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  74253. return FreeCameraTouchInput;
  74254. }());
  74255. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  74256. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  74257. })(BABYLON || (BABYLON = {}));
  74258. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  74259. var BABYLON;
  74260. (function (BABYLON) {
  74261. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  74262. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  74263. });
  74264. // We're mainly based on the logic defined into the FreeCamera code
  74265. var TouchCamera = /** @class */ (function (_super) {
  74266. __extends(TouchCamera, _super);
  74267. //-- end properties for backward compatibility for inputs
  74268. function TouchCamera(name, position, scene) {
  74269. var _this = _super.call(this, name, position, scene) || this;
  74270. _this.inputs.addTouch();
  74271. _this._setupInputs();
  74272. return _this;
  74273. }
  74274. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  74275. //-- Begin properties for backward compatibility for inputs
  74276. get: function () {
  74277. var touch = this.inputs.attached["touch"];
  74278. if (touch)
  74279. return touch.touchAngularSensibility;
  74280. return 0;
  74281. },
  74282. set: function (value) {
  74283. var touch = this.inputs.attached["touch"];
  74284. if (touch)
  74285. touch.touchAngularSensibility = value;
  74286. },
  74287. enumerable: true,
  74288. configurable: true
  74289. });
  74290. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  74291. get: function () {
  74292. var touch = this.inputs.attached["touch"];
  74293. if (touch)
  74294. return touch.touchMoveSensibility;
  74295. return 0;
  74296. },
  74297. set: function (value) {
  74298. var touch = this.inputs.attached["touch"];
  74299. if (touch)
  74300. touch.touchMoveSensibility = value;
  74301. },
  74302. enumerable: true,
  74303. configurable: true
  74304. });
  74305. TouchCamera.prototype.getClassName = function () {
  74306. return "TouchCamera";
  74307. };
  74308. /** @hidden */
  74309. TouchCamera.prototype._setupInputs = function () {
  74310. var mouse = this.inputs.attached["mouse"];
  74311. if (mouse) {
  74312. mouse.touchEnabled = false;
  74313. }
  74314. };
  74315. return TouchCamera;
  74316. }(BABYLON.FreeCamera));
  74317. BABYLON.TouchCamera = TouchCamera;
  74318. })(BABYLON || (BABYLON = {}));
  74319. //# sourceMappingURL=babylon.touchCamera.js.map
  74320. var BABYLON;
  74321. (function (BABYLON) {
  74322. var ProceduralTexture = /** @class */ (function (_super) {
  74323. __extends(ProceduralTexture, _super);
  74324. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  74325. if (fallbackTexture === void 0) { fallbackTexture = null; }
  74326. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74327. if (isCube === void 0) { isCube = false; }
  74328. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  74329. _this.isCube = isCube;
  74330. _this.isEnabled = true;
  74331. _this._currentRefreshId = -1;
  74332. _this._refreshRate = 1;
  74333. /**
  74334. * Event raised when the texture is generated
  74335. */
  74336. _this.onGeneratedObservable = new BABYLON.Observable();
  74337. _this._vertexBuffers = {};
  74338. _this._uniforms = new Array();
  74339. _this._samplers = new Array();
  74340. /** @hidden */
  74341. _this._textures = {};
  74342. _this._floats = {};
  74343. _this._ints = {};
  74344. _this._floatsArrays = {};
  74345. _this._colors3 = {};
  74346. _this._colors4 = {};
  74347. _this._vectors2 = {};
  74348. _this._vectors3 = {};
  74349. _this._matrices = {};
  74350. _this._fallbackTextureUsed = false;
  74351. _this._cachedDefines = "";
  74352. _this._contentUpdateId = -1;
  74353. scene = _this.getScene();
  74354. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  74355. if (!component) {
  74356. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  74357. scene._addComponent(component);
  74358. }
  74359. scene.proceduralTextures.push(_this);
  74360. _this._engine = scene.getEngine();
  74361. _this.name = name;
  74362. _this.isRenderTarget = true;
  74363. _this._size = size;
  74364. _this._generateMipMaps = generateMipMaps;
  74365. _this.setFragment(fragment);
  74366. _this._fallbackTexture = fallbackTexture;
  74367. if (isCube) {
  74368. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  74369. _this.setFloat("face", 0);
  74370. }
  74371. else {
  74372. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  74373. }
  74374. // VBO
  74375. var vertices = [];
  74376. vertices.push(1, 1);
  74377. vertices.push(-1, 1);
  74378. vertices.push(-1, -1);
  74379. vertices.push(1, -1);
  74380. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74381. _this._createIndexBuffer();
  74382. return _this;
  74383. }
  74384. /**
  74385. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  74386. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  74387. */
  74388. ProceduralTexture.prototype.getContent = function () {
  74389. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  74390. return this._contentData;
  74391. }
  74392. this._contentData = this.readPixels(0, 0, this._contentData);
  74393. this._contentUpdateId = this._currentRefreshId;
  74394. return this._contentData;
  74395. };
  74396. ProceduralTexture.prototype._createIndexBuffer = function () {
  74397. var engine = this._engine;
  74398. // Indices
  74399. var indices = [];
  74400. indices.push(0);
  74401. indices.push(1);
  74402. indices.push(2);
  74403. indices.push(0);
  74404. indices.push(2);
  74405. indices.push(3);
  74406. this._indexBuffer = engine.createIndexBuffer(indices);
  74407. };
  74408. /** @hidden */
  74409. ProceduralTexture.prototype._rebuild = function () {
  74410. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74411. if (vb) {
  74412. vb._rebuild();
  74413. }
  74414. this._createIndexBuffer();
  74415. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74416. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74417. }
  74418. };
  74419. ProceduralTexture.prototype.reset = function () {
  74420. if (this._effect === undefined) {
  74421. return;
  74422. }
  74423. var engine = this._engine;
  74424. engine._releaseEffect(this._effect);
  74425. };
  74426. ProceduralTexture.prototype._getDefines = function () {
  74427. return "";
  74428. };
  74429. ProceduralTexture.prototype.isReady = function () {
  74430. var _this = this;
  74431. var engine = this._engine;
  74432. var shaders;
  74433. if (!this._fragment) {
  74434. return false;
  74435. }
  74436. if (this._fallbackTextureUsed) {
  74437. return true;
  74438. }
  74439. var defines = this._getDefines();
  74440. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  74441. return true;
  74442. }
  74443. if (this._fragment.fragmentElement !== undefined) {
  74444. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  74445. }
  74446. else {
  74447. shaders = { vertex: "procedural", fragment: this._fragment };
  74448. }
  74449. this._cachedDefines = defines;
  74450. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  74451. _this.releaseInternalTexture();
  74452. if (_this._fallbackTexture) {
  74453. _this._texture = _this._fallbackTexture._texture;
  74454. if (_this._texture) {
  74455. _this._texture.incrementReferences();
  74456. }
  74457. }
  74458. _this._fallbackTextureUsed = true;
  74459. });
  74460. return this._effect.isReady();
  74461. };
  74462. ProceduralTexture.prototype.resetRefreshCounter = function () {
  74463. this._currentRefreshId = -1;
  74464. };
  74465. ProceduralTexture.prototype.setFragment = function (fragment) {
  74466. this._fragment = fragment;
  74467. };
  74468. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  74469. get: function () {
  74470. return this._refreshRate;
  74471. },
  74472. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  74473. set: function (value) {
  74474. this._refreshRate = value;
  74475. this.resetRefreshCounter();
  74476. },
  74477. enumerable: true,
  74478. configurable: true
  74479. });
  74480. /** @hidden */
  74481. ProceduralTexture.prototype._shouldRender = function () {
  74482. if (!this.isEnabled || !this.isReady() || !this._texture) {
  74483. if (this._texture) {
  74484. this._texture.isReady = false;
  74485. }
  74486. return false;
  74487. }
  74488. if (this._fallbackTextureUsed) {
  74489. return false;
  74490. }
  74491. if (this._currentRefreshId === -1) { // At least render once
  74492. this._currentRefreshId = 1;
  74493. return true;
  74494. }
  74495. if (this.refreshRate === this._currentRefreshId) {
  74496. this._currentRefreshId = 1;
  74497. return true;
  74498. }
  74499. this._currentRefreshId++;
  74500. return false;
  74501. };
  74502. ProceduralTexture.prototype.getRenderSize = function () {
  74503. return this._size;
  74504. };
  74505. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  74506. if (this._fallbackTextureUsed) {
  74507. return;
  74508. }
  74509. this.releaseInternalTexture();
  74510. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  74511. // Update properties
  74512. this._size = size;
  74513. this._generateMipMaps = generateMipMaps;
  74514. };
  74515. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  74516. if (this._uniforms.indexOf(uniformName) === -1) {
  74517. this._uniforms.push(uniformName);
  74518. }
  74519. };
  74520. ProceduralTexture.prototype.setTexture = function (name, texture) {
  74521. if (this._samplers.indexOf(name) === -1) {
  74522. this._samplers.push(name);
  74523. }
  74524. this._textures[name] = texture;
  74525. return this;
  74526. };
  74527. ProceduralTexture.prototype.setFloat = function (name, value) {
  74528. this._checkUniform(name);
  74529. this._floats[name] = value;
  74530. return this;
  74531. };
  74532. /**
  74533. * Set the value of an uniform to an integer value
  74534. * @param name defines the name of the uniform
  74535. * @param value defines the value to set
  74536. * @returns the current procedural texture
  74537. */
  74538. ProceduralTexture.prototype.setInt = function (name, value) {
  74539. this._checkUniform(name);
  74540. this._ints[name] = value;
  74541. return this;
  74542. };
  74543. ProceduralTexture.prototype.setFloats = function (name, value) {
  74544. this._checkUniform(name);
  74545. this._floatsArrays[name] = value;
  74546. return this;
  74547. };
  74548. ProceduralTexture.prototype.setColor3 = function (name, value) {
  74549. this._checkUniform(name);
  74550. this._colors3[name] = value;
  74551. return this;
  74552. };
  74553. ProceduralTexture.prototype.setColor4 = function (name, value) {
  74554. this._checkUniform(name);
  74555. this._colors4[name] = value;
  74556. return this;
  74557. };
  74558. ProceduralTexture.prototype.setVector2 = function (name, value) {
  74559. this._checkUniform(name);
  74560. this._vectors2[name] = value;
  74561. return this;
  74562. };
  74563. ProceduralTexture.prototype.setVector3 = function (name, value) {
  74564. this._checkUniform(name);
  74565. this._vectors3[name] = value;
  74566. return this;
  74567. };
  74568. ProceduralTexture.prototype.setMatrix = function (name, value) {
  74569. this._checkUniform(name);
  74570. this._matrices[name] = value;
  74571. return this;
  74572. };
  74573. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74574. var scene = this.getScene();
  74575. if (!scene) {
  74576. return;
  74577. }
  74578. var engine = this._engine;
  74579. // Render
  74580. engine.enableEffect(this._effect);
  74581. engine.setState(false);
  74582. // Texture
  74583. for (var name in this._textures) {
  74584. this._effect.setTexture(name, this._textures[name]);
  74585. }
  74586. // Float
  74587. for (name in this._ints) {
  74588. this._effect.setInt(name, this._ints[name]);
  74589. }
  74590. // Float
  74591. for (name in this._floats) {
  74592. this._effect.setFloat(name, this._floats[name]);
  74593. }
  74594. // Floats
  74595. for (name in this._floatsArrays) {
  74596. this._effect.setArray(name, this._floatsArrays[name]);
  74597. }
  74598. // Color3
  74599. for (name in this._colors3) {
  74600. this._effect.setColor3(name, this._colors3[name]);
  74601. }
  74602. // Color4
  74603. for (name in this._colors4) {
  74604. var color = this._colors4[name];
  74605. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  74606. }
  74607. // Vector2
  74608. for (name in this._vectors2) {
  74609. this._effect.setVector2(name, this._vectors2[name]);
  74610. }
  74611. // Vector3
  74612. for (name in this._vectors3) {
  74613. this._effect.setVector3(name, this._vectors3[name]);
  74614. }
  74615. // Matrix
  74616. for (name in this._matrices) {
  74617. this._effect.setMatrix(name, this._matrices[name]);
  74618. }
  74619. if (!this._texture) {
  74620. return;
  74621. }
  74622. if (this.isCube) {
  74623. for (var face = 0; face < 6; face++) {
  74624. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  74625. // VBOs
  74626. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74627. this._effect.setFloat("face", face);
  74628. // Clear
  74629. engine.clear(scene.clearColor, true, true, true);
  74630. // Draw order
  74631. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74632. // Mipmaps
  74633. if (face === 5) {
  74634. engine.generateMipMapsForCubemap(this._texture);
  74635. }
  74636. }
  74637. }
  74638. else {
  74639. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  74640. // VBOs
  74641. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74642. // Clear
  74643. engine.clear(scene.clearColor, true, true, true);
  74644. // Draw order
  74645. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74646. }
  74647. // Unbind
  74648. engine.unBindFramebuffer(this._texture, this.isCube);
  74649. if (this.onGenerated) {
  74650. this.onGenerated();
  74651. }
  74652. this.onGeneratedObservable.notifyObservers(this);
  74653. };
  74654. ProceduralTexture.prototype.clone = function () {
  74655. var textureSize = this.getSize();
  74656. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  74657. // Base texture
  74658. newTexture.hasAlpha = this.hasAlpha;
  74659. newTexture.level = this.level;
  74660. // RenderTarget Texture
  74661. newTexture.coordinatesMode = this.coordinatesMode;
  74662. return newTexture;
  74663. };
  74664. ProceduralTexture.prototype.dispose = function () {
  74665. var scene = this.getScene();
  74666. if (!scene) {
  74667. return;
  74668. }
  74669. var index = scene.proceduralTextures.indexOf(this);
  74670. if (index >= 0) {
  74671. scene.proceduralTextures.splice(index, 1);
  74672. }
  74673. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74674. if (vertexBuffer) {
  74675. vertexBuffer.dispose();
  74676. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74677. }
  74678. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  74679. this._indexBuffer = null;
  74680. }
  74681. _super.prototype.dispose.call(this);
  74682. };
  74683. __decorate([
  74684. BABYLON.serialize()
  74685. ], ProceduralTexture.prototype, "_size", void 0);
  74686. __decorate([
  74687. BABYLON.serialize()
  74688. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  74689. __decorate([
  74690. BABYLON.serialize()
  74691. ], ProceduralTexture.prototype, "isEnabled", void 0);
  74692. __decorate([
  74693. BABYLON.serialize()
  74694. ], ProceduralTexture.prototype, "refreshRate", null);
  74695. return ProceduralTexture;
  74696. }(BABYLON.Texture));
  74697. BABYLON.ProceduralTexture = ProceduralTexture;
  74698. })(BABYLON || (BABYLON = {}));
  74699. //# sourceMappingURL=babylon.proceduralTexture.js.map
  74700. var BABYLON;
  74701. (function (BABYLON) {
  74702. /**
  74703. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  74704. * in a given scene.
  74705. */
  74706. var ProceduralTextureSceneComponent = /** @class */ (function () {
  74707. /**
  74708. * Creates a new instance of the component for the given scene
  74709. * @param scene Defines the scene to register the component in
  74710. */
  74711. function ProceduralTextureSceneComponent(scene) {
  74712. /**
  74713. * The component name helpfull to identify the component in the list of scene components.
  74714. */
  74715. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  74716. this.scene = scene;
  74717. this.scene.proceduralTextures = new Array();
  74718. scene.layers = new Array();
  74719. }
  74720. /**
  74721. * Registers the component in a given scene
  74722. */
  74723. ProceduralTextureSceneComponent.prototype.register = function () {
  74724. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  74725. };
  74726. /**
  74727. * Rebuilds the elements related to this component in case of
  74728. * context lost for instance.
  74729. */
  74730. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  74731. // Nothing to do here.
  74732. };
  74733. /**
  74734. * Disposes the component and the associated ressources.
  74735. */
  74736. ProceduralTextureSceneComponent.prototype.dispose = function () {
  74737. // Nothing to do here.
  74738. };
  74739. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  74740. if (this.scene.proceduralTexturesEnabled) {
  74741. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74742. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  74743. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  74744. if (proceduralTexture._shouldRender()) {
  74745. proceduralTexture.render();
  74746. }
  74747. }
  74748. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74749. }
  74750. };
  74751. return ProceduralTextureSceneComponent;
  74752. }());
  74753. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  74754. })(BABYLON || (BABYLON = {}));
  74755. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  74756. var BABYLON;
  74757. (function (BABYLON) {
  74758. var CustomProceduralTexture = /** @class */ (function (_super) {
  74759. __extends(CustomProceduralTexture, _super);
  74760. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  74761. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  74762. _this._animate = true;
  74763. _this._time = 0;
  74764. _this._texturePath = texturePath;
  74765. //Try to load json
  74766. _this.loadJson(texturePath);
  74767. _this.refreshRate = 1;
  74768. return _this;
  74769. }
  74770. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  74771. var _this = this;
  74772. var noConfigFile = function () {
  74773. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  74774. try {
  74775. _this.setFragment(_this._texturePath);
  74776. }
  74777. catch (ex) {
  74778. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  74779. }
  74780. };
  74781. var configFileUrl = jsonUrl + "/config.json";
  74782. var xhr = new XMLHttpRequest();
  74783. xhr.open("GET", configFileUrl, true);
  74784. xhr.addEventListener("load", function () {
  74785. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  74786. try {
  74787. _this._config = JSON.parse(xhr.response);
  74788. _this.updateShaderUniforms();
  74789. _this.updateTextures();
  74790. _this.setFragment(_this._texturePath + "/custom");
  74791. _this._animate = _this._config.animate;
  74792. _this.refreshRate = _this._config.refreshrate;
  74793. }
  74794. catch (ex) {
  74795. noConfigFile();
  74796. }
  74797. }
  74798. else {
  74799. noConfigFile();
  74800. }
  74801. }, false);
  74802. xhr.addEventListener("error", function () {
  74803. noConfigFile();
  74804. }, false);
  74805. try {
  74806. xhr.send();
  74807. }
  74808. catch (ex) {
  74809. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  74810. }
  74811. };
  74812. CustomProceduralTexture.prototype.isReady = function () {
  74813. if (!_super.prototype.isReady.call(this)) {
  74814. return false;
  74815. }
  74816. for (var name in this._textures) {
  74817. var texture = this._textures[name];
  74818. if (!texture.isReady()) {
  74819. return false;
  74820. }
  74821. }
  74822. return true;
  74823. };
  74824. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74825. var scene = this.getScene();
  74826. if (this._animate && scene) {
  74827. this._time += scene.getAnimationRatio() * 0.03;
  74828. this.updateShaderUniforms();
  74829. }
  74830. _super.prototype.render.call(this, useCameraPostProcess);
  74831. };
  74832. CustomProceduralTexture.prototype.updateTextures = function () {
  74833. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  74834. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  74835. }
  74836. };
  74837. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  74838. if (this._config) {
  74839. for (var j = 0; j < this._config.uniforms.length; j++) {
  74840. var uniform = this._config.uniforms[j];
  74841. switch (uniform.type) {
  74842. case "float":
  74843. this.setFloat(uniform.name, uniform.value);
  74844. break;
  74845. case "color3":
  74846. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  74847. break;
  74848. case "color4":
  74849. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  74850. break;
  74851. case "vector2":
  74852. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  74853. break;
  74854. case "vector3":
  74855. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  74856. break;
  74857. }
  74858. }
  74859. }
  74860. this.setFloat("time", this._time);
  74861. };
  74862. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  74863. get: function () {
  74864. return this._animate;
  74865. },
  74866. set: function (value) {
  74867. this._animate = value;
  74868. },
  74869. enumerable: true,
  74870. configurable: true
  74871. });
  74872. return CustomProceduralTexture;
  74873. }(BABYLON.ProceduralTexture));
  74874. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  74875. })(BABYLON || (BABYLON = {}));
  74876. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  74877. var BABYLON;
  74878. (function (BABYLON) {
  74879. var FreeCameraGamepadInput = /** @class */ (function () {
  74880. function FreeCameraGamepadInput() {
  74881. this.gamepadAngularSensibility = 200;
  74882. this.gamepadMoveSensibility = 40;
  74883. // private members
  74884. this._cameraTransform = BABYLON.Matrix.Identity();
  74885. this._deltaTransform = BABYLON.Vector3.Zero();
  74886. this._vector3 = BABYLON.Vector3.Zero();
  74887. this._vector2 = BABYLON.Vector2.Zero();
  74888. }
  74889. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74890. var _this = this;
  74891. var manager = this.camera.getScene().gamepadManager;
  74892. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74893. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74894. // prioritize XBOX gamepads.
  74895. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74896. _this.gamepad = gamepad;
  74897. }
  74898. }
  74899. });
  74900. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74901. if (_this.gamepad === gamepad) {
  74902. _this.gamepad = null;
  74903. }
  74904. });
  74905. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74906. };
  74907. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  74908. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74909. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74910. this.gamepad = null;
  74911. };
  74912. FreeCameraGamepadInput.prototype.checkInputs = function () {
  74913. if (this.gamepad && this.gamepad.leftStick) {
  74914. var camera = this.camera;
  74915. var LSValues = this.gamepad.leftStick;
  74916. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  74917. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74918. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  74919. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  74920. var RSValues = this.gamepad.rightStick;
  74921. if (RSValues) {
  74922. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  74923. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  74924. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  74925. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  74926. }
  74927. else {
  74928. RSValues = { x: 0, y: 0 };
  74929. }
  74930. if (!camera.rotationQuaternion) {
  74931. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  74932. }
  74933. else {
  74934. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  74935. }
  74936. var speed = camera._computeLocalCameraSpeed() * 50.0;
  74937. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  74938. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  74939. camera.cameraDirection.addInPlace(this._deltaTransform);
  74940. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  74941. camera.cameraRotation.addInPlace(this._vector2);
  74942. }
  74943. };
  74944. FreeCameraGamepadInput.prototype.getClassName = function () {
  74945. return "FreeCameraGamepadInput";
  74946. };
  74947. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  74948. return "gamepad";
  74949. };
  74950. __decorate([
  74951. BABYLON.serialize()
  74952. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  74953. __decorate([
  74954. BABYLON.serialize()
  74955. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74956. return FreeCameraGamepadInput;
  74957. }());
  74958. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  74959. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  74960. })(BABYLON || (BABYLON = {}));
  74961. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  74962. var BABYLON;
  74963. (function (BABYLON) {
  74964. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  74965. function ArcRotateCameraGamepadInput() {
  74966. this.gamepadRotationSensibility = 80;
  74967. this.gamepadMoveSensibility = 40;
  74968. }
  74969. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74970. var _this = this;
  74971. var manager = this.camera.getScene().gamepadManager;
  74972. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74973. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74974. // prioritize XBOX gamepads.
  74975. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74976. _this.gamepad = gamepad;
  74977. }
  74978. }
  74979. });
  74980. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74981. if (_this.gamepad === gamepad) {
  74982. _this.gamepad = null;
  74983. }
  74984. });
  74985. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74986. };
  74987. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  74988. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74989. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74990. this.gamepad = null;
  74991. };
  74992. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  74993. if (this.gamepad) {
  74994. var camera = this.camera;
  74995. var RSValues = this.gamepad.rightStick;
  74996. if (RSValues) {
  74997. if (RSValues.x != 0) {
  74998. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  74999. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  75000. camera.inertialAlphaOffset += normalizedRX;
  75001. }
  75002. }
  75003. if (RSValues.y != 0) {
  75004. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  75005. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  75006. camera.inertialBetaOffset += normalizedRY;
  75007. }
  75008. }
  75009. }
  75010. var LSValues = this.gamepad.leftStick;
  75011. if (LSValues && LSValues.y != 0) {
  75012. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  75013. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  75014. this.camera.inertialRadiusOffset -= normalizedLY;
  75015. }
  75016. }
  75017. }
  75018. };
  75019. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  75020. return "ArcRotateCameraGamepadInput";
  75021. };
  75022. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  75023. return "gamepad";
  75024. };
  75025. __decorate([
  75026. BABYLON.serialize()
  75027. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  75028. __decorate([
  75029. BABYLON.serialize()
  75030. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  75031. return ArcRotateCameraGamepadInput;
  75032. }());
  75033. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  75034. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  75035. })(BABYLON || (BABYLON = {}));
  75036. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  75037. var BABYLON;
  75038. (function (BABYLON) {
  75039. var GamepadManager = /** @class */ (function () {
  75040. function GamepadManager(_scene) {
  75041. var _this = this;
  75042. this._scene = _scene;
  75043. this._babylonGamepads = [];
  75044. this._oneGamepadConnected = false;
  75045. /** @hidden */
  75046. this._isMonitoring = false;
  75047. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  75048. if (!BABYLON.Tools.IsWindowObjectExist()) {
  75049. this._gamepadEventSupported = false;
  75050. }
  75051. else {
  75052. this._gamepadEventSupported = 'GamepadEvent' in window;
  75053. this._gamepadSupport = (navigator.getGamepads ||
  75054. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  75055. }
  75056. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  75057. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  75058. for (var i in _this._babylonGamepads) {
  75059. var gamepad = _this._babylonGamepads[i];
  75060. if (gamepad && gamepad._isConnected) {
  75061. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  75062. }
  75063. }
  75064. });
  75065. this._onGamepadConnectedEvent = function (evt) {
  75066. var gamepad = evt.gamepad;
  75067. if (gamepad.index in _this._babylonGamepads) {
  75068. if (_this._babylonGamepads[gamepad.index].isConnected) {
  75069. return;
  75070. }
  75071. }
  75072. var newGamepad;
  75073. if (_this._babylonGamepads[gamepad.index]) {
  75074. newGamepad = _this._babylonGamepads[gamepad.index];
  75075. newGamepad.browserGamepad = gamepad;
  75076. newGamepad._isConnected = true;
  75077. }
  75078. else {
  75079. newGamepad = _this._addNewGamepad(gamepad);
  75080. }
  75081. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  75082. _this._startMonitoringGamepads();
  75083. };
  75084. this._onGamepadDisconnectedEvent = function (evt) {
  75085. var gamepad = evt.gamepad;
  75086. // Remove the gamepad from the list of gamepads to monitor.
  75087. for (var i in _this._babylonGamepads) {
  75088. if (_this._babylonGamepads[i].index === gamepad.index) {
  75089. var disconnectedGamepad = _this._babylonGamepads[i];
  75090. disconnectedGamepad._isConnected = false;
  75091. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  75092. break;
  75093. }
  75094. }
  75095. };
  75096. if (this._gamepadSupport) {
  75097. //first add already-connected gamepads
  75098. this._updateGamepadObjects();
  75099. if (this._babylonGamepads.length) {
  75100. this._startMonitoringGamepads();
  75101. }
  75102. // Checking if the gamepad connected event is supported (like in Firefox)
  75103. if (this._gamepadEventSupported) {
  75104. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  75105. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  75106. }
  75107. else {
  75108. this._startMonitoringGamepads();
  75109. }
  75110. }
  75111. }
  75112. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  75113. get: function () {
  75114. return this._babylonGamepads;
  75115. },
  75116. enumerable: true,
  75117. configurable: true
  75118. });
  75119. GamepadManager.prototype.getGamepadByType = function (type) {
  75120. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  75121. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  75122. var gamepad = _a[_i];
  75123. if (gamepad && gamepad.type === type) {
  75124. return gamepad;
  75125. }
  75126. }
  75127. return null;
  75128. };
  75129. GamepadManager.prototype.dispose = function () {
  75130. if (this._gamepadEventSupported) {
  75131. if (this._onGamepadConnectedEvent) {
  75132. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  75133. }
  75134. if (this._onGamepadDisconnectedEvent) {
  75135. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  75136. }
  75137. this._onGamepadConnectedEvent = null;
  75138. this._onGamepadDisconnectedEvent = null;
  75139. }
  75140. this._babylonGamepads.forEach(function (gamepad) {
  75141. gamepad.dispose();
  75142. });
  75143. this.onGamepadConnectedObservable.clear();
  75144. this.onGamepadDisconnectedObservable.clear();
  75145. this._oneGamepadConnected = false;
  75146. this._stopMonitoringGamepads();
  75147. this._babylonGamepads = [];
  75148. };
  75149. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  75150. if (!this._oneGamepadConnected) {
  75151. this._oneGamepadConnected = true;
  75152. }
  75153. var newGamepad;
  75154. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  75155. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  75156. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  75157. }
  75158. // if pose is supported, use the (WebVR) pose enabled controller
  75159. else if (gamepad.pose) {
  75160. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  75161. }
  75162. else {
  75163. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  75164. }
  75165. this._babylonGamepads[newGamepad.index] = newGamepad;
  75166. return newGamepad;
  75167. };
  75168. GamepadManager.prototype._startMonitoringGamepads = function () {
  75169. if (!this._isMonitoring) {
  75170. this._isMonitoring = true;
  75171. //back-comp
  75172. if (!this._scene) {
  75173. this._checkGamepadsStatus();
  75174. }
  75175. }
  75176. };
  75177. GamepadManager.prototype._stopMonitoringGamepads = function () {
  75178. this._isMonitoring = false;
  75179. };
  75180. /** @hidden */
  75181. GamepadManager.prototype._checkGamepadsStatus = function () {
  75182. var _this = this;
  75183. // Hack to be compatible Chrome
  75184. this._updateGamepadObjects();
  75185. for (var i in this._babylonGamepads) {
  75186. var gamepad = this._babylonGamepads[i];
  75187. if (!gamepad || !gamepad.isConnected) {
  75188. continue;
  75189. }
  75190. gamepad.update();
  75191. }
  75192. if (this._isMonitoring && !this._scene) {
  75193. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  75194. }
  75195. };
  75196. // This function is called only on Chrome, which does not properly support
  75197. // connection/disconnection events and forces you to recopy again the gamepad object
  75198. GamepadManager.prototype._updateGamepadObjects = function () {
  75199. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  75200. for (var i = 0; i < gamepads.length; i++) {
  75201. var gamepad = gamepads[i];
  75202. if (gamepad) {
  75203. if (!this._babylonGamepads[gamepad.index]) {
  75204. var newGamepad = this._addNewGamepad(gamepad);
  75205. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  75206. }
  75207. else {
  75208. // Forced to copy again this object for Chrome for unknown reason
  75209. this._babylonGamepads[i].browserGamepad = gamepad;
  75210. if (!this._babylonGamepads[i].isConnected) {
  75211. this._babylonGamepads[i]._isConnected = true;
  75212. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  75213. }
  75214. }
  75215. }
  75216. }
  75217. };
  75218. return GamepadManager;
  75219. }());
  75220. BABYLON.GamepadManager = GamepadManager;
  75221. })(BABYLON || (BABYLON = {}));
  75222. //# sourceMappingURL=babylon.gamepadManager.js.map
  75223. var BABYLON;
  75224. (function (BABYLON) {
  75225. var StickValues = /** @class */ (function () {
  75226. function StickValues(x, y) {
  75227. this.x = x;
  75228. this.y = y;
  75229. }
  75230. return StickValues;
  75231. }());
  75232. BABYLON.StickValues = StickValues;
  75233. var Gamepad = /** @class */ (function () {
  75234. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  75235. if (leftStickX === void 0) { leftStickX = 0; }
  75236. if (leftStickY === void 0) { leftStickY = 1; }
  75237. if (rightStickX === void 0) { rightStickX = 2; }
  75238. if (rightStickY === void 0) { rightStickY = 3; }
  75239. this.id = id;
  75240. this.index = index;
  75241. this.browserGamepad = browserGamepad;
  75242. this._leftStick = { x: 0, y: 0 };
  75243. this._rightStick = { x: 0, y: 0 };
  75244. /** @hidden */
  75245. this._isConnected = true;
  75246. this._invertLeftStickY = false;
  75247. this.type = Gamepad.GAMEPAD;
  75248. this._leftStickAxisX = leftStickX;
  75249. this._leftStickAxisY = leftStickY;
  75250. this._rightStickAxisX = rightStickX;
  75251. this._rightStickAxisY = rightStickY;
  75252. if (this.browserGamepad.axes.length >= 2) {
  75253. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75254. }
  75255. if (this.browserGamepad.axes.length >= 4) {
  75256. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75257. }
  75258. }
  75259. Object.defineProperty(Gamepad.prototype, "isConnected", {
  75260. get: function () {
  75261. return this._isConnected;
  75262. },
  75263. enumerable: true,
  75264. configurable: true
  75265. });
  75266. Gamepad.prototype.onleftstickchanged = function (callback) {
  75267. this._onleftstickchanged = callback;
  75268. };
  75269. Gamepad.prototype.onrightstickchanged = function (callback) {
  75270. this._onrightstickchanged = callback;
  75271. };
  75272. Object.defineProperty(Gamepad.prototype, "leftStick", {
  75273. get: function () {
  75274. return this._leftStick;
  75275. },
  75276. set: function (newValues) {
  75277. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  75278. this._onleftstickchanged(newValues);
  75279. }
  75280. this._leftStick = newValues;
  75281. },
  75282. enumerable: true,
  75283. configurable: true
  75284. });
  75285. Object.defineProperty(Gamepad.prototype, "rightStick", {
  75286. get: function () {
  75287. return this._rightStick;
  75288. },
  75289. set: function (newValues) {
  75290. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  75291. this._onrightstickchanged(newValues);
  75292. }
  75293. this._rightStick = newValues;
  75294. },
  75295. enumerable: true,
  75296. configurable: true
  75297. });
  75298. Gamepad.prototype.update = function () {
  75299. if (this._leftStick) {
  75300. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75301. if (this._invertLeftStickY) {
  75302. this.leftStick.y *= -1;
  75303. }
  75304. }
  75305. if (this._rightStick) {
  75306. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75307. }
  75308. };
  75309. Gamepad.prototype.dispose = function () {
  75310. };
  75311. Gamepad.GAMEPAD = 0;
  75312. Gamepad.GENERIC = 1;
  75313. Gamepad.XBOX = 2;
  75314. Gamepad.POSE_ENABLED = 3;
  75315. return Gamepad;
  75316. }());
  75317. BABYLON.Gamepad = Gamepad;
  75318. var GenericPad = /** @class */ (function (_super) {
  75319. __extends(GenericPad, _super);
  75320. function GenericPad(id, index, browserGamepad) {
  75321. var _this = _super.call(this, id, index, browserGamepad) || this;
  75322. _this.onButtonDownObservable = new BABYLON.Observable();
  75323. _this.onButtonUpObservable = new BABYLON.Observable();
  75324. _this.type = Gamepad.GENERIC;
  75325. _this._buttons = new Array(browserGamepad.buttons.length);
  75326. return _this;
  75327. }
  75328. GenericPad.prototype.onbuttondown = function (callback) {
  75329. this._onbuttondown = callback;
  75330. };
  75331. GenericPad.prototype.onbuttonup = function (callback) {
  75332. this._onbuttonup = callback;
  75333. };
  75334. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  75335. if (newValue !== currentValue) {
  75336. if (newValue === 1) {
  75337. if (this._onbuttondown) {
  75338. this._onbuttondown(buttonIndex);
  75339. }
  75340. this.onButtonDownObservable.notifyObservers(buttonIndex);
  75341. }
  75342. if (newValue === 0) {
  75343. if (this._onbuttonup) {
  75344. this._onbuttonup(buttonIndex);
  75345. }
  75346. this.onButtonUpObservable.notifyObservers(buttonIndex);
  75347. }
  75348. }
  75349. return newValue;
  75350. };
  75351. GenericPad.prototype.update = function () {
  75352. _super.prototype.update.call(this);
  75353. for (var index = 0; index < this._buttons.length; index++) {
  75354. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  75355. }
  75356. };
  75357. GenericPad.prototype.dispose = function () {
  75358. _super.prototype.dispose.call(this);
  75359. this.onButtonDownObservable.clear();
  75360. this.onButtonUpObservable.clear();
  75361. };
  75362. return GenericPad;
  75363. }(Gamepad));
  75364. BABYLON.GenericPad = GenericPad;
  75365. })(BABYLON || (BABYLON = {}));
  75366. //# sourceMappingURL=babylon.gamepad.js.map
  75367. var BABYLON;
  75368. (function (BABYLON) {
  75369. /**
  75370. * Defines supported buttons for XBox360 compatible gamepads
  75371. */
  75372. var Xbox360Button;
  75373. (function (Xbox360Button) {
  75374. /** A */
  75375. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  75376. /** B */
  75377. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  75378. /** X */
  75379. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  75380. /** Y */
  75381. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  75382. /** Start */
  75383. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  75384. /** Back */
  75385. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  75386. /** Left button */
  75387. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  75388. /** Right button */
  75389. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  75390. /** Left stick */
  75391. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  75392. /** Right stick */
  75393. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  75394. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  75395. /** Defines values for XBox360 DPad */
  75396. var Xbox360Dpad;
  75397. (function (Xbox360Dpad) {
  75398. /** Up */
  75399. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  75400. /** Down */
  75401. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  75402. /** Left */
  75403. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  75404. /** Right */
  75405. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  75406. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  75407. /**
  75408. * Defines a XBox360 gamepad
  75409. */
  75410. var Xbox360Pad = /** @class */ (function (_super) {
  75411. __extends(Xbox360Pad, _super);
  75412. /**
  75413. * Creates a new XBox360 gamepad object
  75414. * @param id defines the id of this gamepad
  75415. * @param index defines its index
  75416. * @param gamepad defines the internal HTML gamepad object
  75417. * @param xboxOne defines if it is a XBox One gamepad
  75418. */
  75419. function Xbox360Pad(id, index, gamepad, xboxOne) {
  75420. if (xboxOne === void 0) { xboxOne = false; }
  75421. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  75422. _this._leftTrigger = 0;
  75423. _this._rightTrigger = 0;
  75424. /** Observable raised when a button is pressed */
  75425. _this.onButtonDownObservable = new BABYLON.Observable();
  75426. /** Observable raised when a button is released */
  75427. _this.onButtonUpObservable = new BABYLON.Observable();
  75428. /** Observable raised when a pad is pressed */
  75429. _this.onPadDownObservable = new BABYLON.Observable();
  75430. /** Observable raised when a pad is released */
  75431. _this.onPadUpObservable = new BABYLON.Observable();
  75432. _this._buttonA = 0;
  75433. _this._buttonB = 0;
  75434. _this._buttonX = 0;
  75435. _this._buttonY = 0;
  75436. _this._buttonBack = 0;
  75437. _this._buttonStart = 0;
  75438. _this._buttonLB = 0;
  75439. _this._buttonRB = 0;
  75440. _this._buttonLeftStick = 0;
  75441. _this._buttonRightStick = 0;
  75442. _this._dPadUp = 0;
  75443. _this._dPadDown = 0;
  75444. _this._dPadLeft = 0;
  75445. _this._dPadRight = 0;
  75446. _this._isXboxOnePad = false;
  75447. _this.type = BABYLON.Gamepad.XBOX;
  75448. _this._isXboxOnePad = xboxOne;
  75449. return _this;
  75450. }
  75451. /**
  75452. * Defines the callback to call when left trigger is pressed
  75453. * @param callback defines the callback to use
  75454. */
  75455. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  75456. this._onlefttriggerchanged = callback;
  75457. };
  75458. /**
  75459. * Defines the callback to call when right trigger is pressed
  75460. * @param callback defines the callback to use
  75461. */
  75462. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  75463. this._onrighttriggerchanged = callback;
  75464. };
  75465. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  75466. /**
  75467. * Gets or sets left trigger value
  75468. */
  75469. get: function () {
  75470. return this._leftTrigger;
  75471. },
  75472. set: function (newValue) {
  75473. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  75474. this._onlefttriggerchanged(newValue);
  75475. }
  75476. this._leftTrigger = newValue;
  75477. },
  75478. enumerable: true,
  75479. configurable: true
  75480. });
  75481. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  75482. /**
  75483. * Gets or sets right trigger value
  75484. */
  75485. get: function () {
  75486. return this._rightTrigger;
  75487. },
  75488. set: function (newValue) {
  75489. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  75490. this._onrighttriggerchanged(newValue);
  75491. }
  75492. this._rightTrigger = newValue;
  75493. },
  75494. enumerable: true,
  75495. configurable: true
  75496. });
  75497. /**
  75498. * Defines the callback to call when a button is pressed
  75499. * @param callback defines the callback to use
  75500. */
  75501. Xbox360Pad.prototype.onbuttondown = function (callback) {
  75502. this._onbuttondown = callback;
  75503. };
  75504. /**
  75505. * Defines the callback to call when a button is released
  75506. * @param callback defines the callback to use
  75507. */
  75508. Xbox360Pad.prototype.onbuttonup = function (callback) {
  75509. this._onbuttonup = callback;
  75510. };
  75511. /**
  75512. * Defines the callback to call when a pad is pressed
  75513. * @param callback defines the callback to use
  75514. */
  75515. Xbox360Pad.prototype.ondpaddown = function (callback) {
  75516. this._ondpaddown = callback;
  75517. };
  75518. /**
  75519. * Defines the callback to call when a pad is released
  75520. * @param callback defines the callback to use
  75521. */
  75522. Xbox360Pad.prototype.ondpadup = function (callback) {
  75523. this._ondpadup = callback;
  75524. };
  75525. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  75526. if (newValue !== currentValue) {
  75527. if (newValue === 1) {
  75528. if (this._onbuttondown) {
  75529. this._onbuttondown(buttonType);
  75530. }
  75531. this.onButtonDownObservable.notifyObservers(buttonType);
  75532. }
  75533. if (newValue === 0) {
  75534. if (this._onbuttonup) {
  75535. this._onbuttonup(buttonType);
  75536. }
  75537. this.onButtonUpObservable.notifyObservers(buttonType);
  75538. }
  75539. }
  75540. return newValue;
  75541. };
  75542. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  75543. if (newValue !== currentValue) {
  75544. if (newValue === 1) {
  75545. if (this._ondpaddown) {
  75546. this._ondpaddown(buttonType);
  75547. }
  75548. this.onPadDownObservable.notifyObservers(buttonType);
  75549. }
  75550. if (newValue === 0) {
  75551. if (this._ondpadup) {
  75552. this._ondpadup(buttonType);
  75553. }
  75554. this.onPadUpObservable.notifyObservers(buttonType);
  75555. }
  75556. }
  75557. return newValue;
  75558. };
  75559. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  75560. /** Gets or sets value of A button */
  75561. get: function () {
  75562. return this._buttonA;
  75563. },
  75564. set: function (value) {
  75565. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  75566. },
  75567. enumerable: true,
  75568. configurable: true
  75569. });
  75570. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  75571. /** Gets or sets value of B button */
  75572. get: function () {
  75573. return this._buttonB;
  75574. },
  75575. set: function (value) {
  75576. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  75577. },
  75578. enumerable: true,
  75579. configurable: true
  75580. });
  75581. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  75582. /** Gets or sets value of X button */
  75583. get: function () {
  75584. return this._buttonX;
  75585. },
  75586. set: function (value) {
  75587. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  75588. },
  75589. enumerable: true,
  75590. configurable: true
  75591. });
  75592. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  75593. /** Gets or sets value of Y button */
  75594. get: function () {
  75595. return this._buttonY;
  75596. },
  75597. set: function (value) {
  75598. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  75599. },
  75600. enumerable: true,
  75601. configurable: true
  75602. });
  75603. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  75604. /** Gets or sets value of Start button */
  75605. get: function () {
  75606. return this._buttonStart;
  75607. },
  75608. set: function (value) {
  75609. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  75610. },
  75611. enumerable: true,
  75612. configurable: true
  75613. });
  75614. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  75615. /** Gets or sets value of Back button */
  75616. get: function () {
  75617. return this._buttonBack;
  75618. },
  75619. set: function (value) {
  75620. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  75621. },
  75622. enumerable: true,
  75623. configurable: true
  75624. });
  75625. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  75626. /** Gets or sets value of Left button */
  75627. get: function () {
  75628. return this._buttonLB;
  75629. },
  75630. set: function (value) {
  75631. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  75632. },
  75633. enumerable: true,
  75634. configurable: true
  75635. });
  75636. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  75637. /** Gets or sets value of Right button */
  75638. get: function () {
  75639. return this._buttonRB;
  75640. },
  75641. set: function (value) {
  75642. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  75643. },
  75644. enumerable: true,
  75645. configurable: true
  75646. });
  75647. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  75648. /** Gets or sets value of left stick */
  75649. get: function () {
  75650. return this._buttonLeftStick;
  75651. },
  75652. set: function (value) {
  75653. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  75654. },
  75655. enumerable: true,
  75656. configurable: true
  75657. });
  75658. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  75659. /** Gets or sets value of right stick */
  75660. get: function () {
  75661. return this._buttonRightStick;
  75662. },
  75663. set: function (value) {
  75664. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  75665. },
  75666. enumerable: true,
  75667. configurable: true
  75668. });
  75669. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  75670. /** Gets or sets value of DPad up */
  75671. get: function () {
  75672. return this._dPadUp;
  75673. },
  75674. set: function (value) {
  75675. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  75676. },
  75677. enumerable: true,
  75678. configurable: true
  75679. });
  75680. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  75681. /** Gets or sets value of DPad down */
  75682. get: function () {
  75683. return this._dPadDown;
  75684. },
  75685. set: function (value) {
  75686. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  75687. },
  75688. enumerable: true,
  75689. configurable: true
  75690. });
  75691. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  75692. /** Gets or sets value of DPad left */
  75693. get: function () {
  75694. return this._dPadLeft;
  75695. },
  75696. set: function (value) {
  75697. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  75698. },
  75699. enumerable: true,
  75700. configurable: true
  75701. });
  75702. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  75703. /** Gets or sets value of DPad right */
  75704. get: function () {
  75705. return this._dPadRight;
  75706. },
  75707. set: function (value) {
  75708. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  75709. },
  75710. enumerable: true,
  75711. configurable: true
  75712. });
  75713. /**
  75714. * Force the gamepad to synchronize with device values
  75715. */
  75716. Xbox360Pad.prototype.update = function () {
  75717. _super.prototype.update.call(this);
  75718. if (this._isXboxOnePad) {
  75719. this.buttonA = this.browserGamepad.buttons[0].value;
  75720. this.buttonB = this.browserGamepad.buttons[1].value;
  75721. this.buttonX = this.browserGamepad.buttons[2].value;
  75722. this.buttonY = this.browserGamepad.buttons[3].value;
  75723. this.buttonLB = this.browserGamepad.buttons[4].value;
  75724. this.buttonRB = this.browserGamepad.buttons[5].value;
  75725. this.leftTrigger = this.browserGamepad.axes[2];
  75726. this.rightTrigger = this.browserGamepad.axes[5];
  75727. this.buttonBack = this.browserGamepad.buttons[9].value;
  75728. this.buttonStart = this.browserGamepad.buttons[8].value;
  75729. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  75730. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  75731. this.dPadUp = this.browserGamepad.buttons[11].value;
  75732. this.dPadDown = this.browserGamepad.buttons[12].value;
  75733. this.dPadLeft = this.browserGamepad.buttons[13].value;
  75734. this.dPadRight = this.browserGamepad.buttons[14].value;
  75735. }
  75736. else {
  75737. this.buttonA = this.browserGamepad.buttons[0].value;
  75738. this.buttonB = this.browserGamepad.buttons[1].value;
  75739. this.buttonX = this.browserGamepad.buttons[2].value;
  75740. this.buttonY = this.browserGamepad.buttons[3].value;
  75741. this.buttonLB = this.browserGamepad.buttons[4].value;
  75742. this.buttonRB = this.browserGamepad.buttons[5].value;
  75743. this.leftTrigger = this.browserGamepad.buttons[6].value;
  75744. this.rightTrigger = this.browserGamepad.buttons[7].value;
  75745. this.buttonBack = this.browserGamepad.buttons[8].value;
  75746. this.buttonStart = this.browserGamepad.buttons[9].value;
  75747. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  75748. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  75749. this.dPadUp = this.browserGamepad.buttons[12].value;
  75750. this.dPadDown = this.browserGamepad.buttons[13].value;
  75751. this.dPadLeft = this.browserGamepad.buttons[14].value;
  75752. this.dPadRight = this.browserGamepad.buttons[15].value;
  75753. }
  75754. };
  75755. Xbox360Pad.prototype.dispose = function () {
  75756. _super.prototype.dispose.call(this);
  75757. this.onButtonDownObservable.clear();
  75758. this.onButtonUpObservable.clear();
  75759. this.onPadDownObservable.clear();
  75760. this.onPadUpObservable.clear();
  75761. };
  75762. return Xbox360Pad;
  75763. }(BABYLON.Gamepad));
  75764. BABYLON.Xbox360Pad = Xbox360Pad;
  75765. })(BABYLON || (BABYLON = {}));
  75766. //# sourceMappingURL=babylon.xboxGamepad.js.map
  75767. var BABYLON;
  75768. (function (BABYLON) {
  75769. /**
  75770. * Defines the types of pose enabled controllers that are supported
  75771. */
  75772. var PoseEnabledControllerType;
  75773. (function (PoseEnabledControllerType) {
  75774. /**
  75775. * HTC Vive
  75776. */
  75777. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  75778. /**
  75779. * Oculus Rift
  75780. */
  75781. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  75782. /**
  75783. * Windows mixed reality
  75784. */
  75785. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  75786. /**
  75787. * Samsung gear VR
  75788. */
  75789. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  75790. /**
  75791. * Google Daydream
  75792. */
  75793. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  75794. /**
  75795. * Generic
  75796. */
  75797. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  75798. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  75799. /**
  75800. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75801. */
  75802. var PoseEnabledControllerHelper = /** @class */ (function () {
  75803. function PoseEnabledControllerHelper() {
  75804. }
  75805. /**
  75806. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75807. * @param vrGamepad the gamepad to initialized
  75808. * @returns a vr controller of the type the gamepad identified as
  75809. */
  75810. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  75811. // Oculus Touch
  75812. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  75813. return new BABYLON.OculusTouchController(vrGamepad);
  75814. }
  75815. // Windows Mixed Reality controllers
  75816. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  75817. return new BABYLON.WindowsMotionController(vrGamepad);
  75818. }
  75819. // HTC Vive
  75820. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  75821. return new BABYLON.ViveController(vrGamepad);
  75822. }
  75823. // Samsung/Oculus Gear VR or Oculus Go
  75824. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  75825. return new BABYLON.GearVRController(vrGamepad);
  75826. }
  75827. // Google Daydream
  75828. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  75829. return new BABYLON.DaydreamController(vrGamepad);
  75830. }
  75831. // Generic
  75832. else {
  75833. return new BABYLON.GenericController(vrGamepad);
  75834. }
  75835. };
  75836. return PoseEnabledControllerHelper;
  75837. }());
  75838. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  75839. /**
  75840. * Defines the PoseEnabledController object that contains state of a vr capable controller
  75841. */
  75842. var PoseEnabledController = /** @class */ (function (_super) {
  75843. __extends(PoseEnabledController, _super);
  75844. /**
  75845. * Creates a new PoseEnabledController from a gamepad
  75846. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  75847. */
  75848. function PoseEnabledController(browserGamepad) {
  75849. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  75850. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75851. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75852. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  75853. /**
  75854. * The device position in babylon space
  75855. */
  75856. _this.devicePosition = BABYLON.Vector3.Zero();
  75857. /**
  75858. * The device rotation in babylon space
  75859. */
  75860. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  75861. /**
  75862. * The scale factor of the device in babylon space
  75863. */
  75864. _this.deviceScaleFactor = 1;
  75865. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  75866. /**
  75867. * Internal, matrix used to convert room space to babylon space
  75868. * @hidden
  75869. */
  75870. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75871. /**
  75872. * Node to be used when casting a ray from the controller
  75873. * @hidden
  75874. */
  75875. _this._pointingPoseNode = null;
  75876. _this._workingMatrix = BABYLON.Matrix.Identity();
  75877. /**
  75878. * @hidden
  75879. */
  75880. _this._meshAttachedObservable = new BABYLON.Observable();
  75881. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  75882. _this.controllerType = PoseEnabledControllerType.GENERIC;
  75883. _this.position = BABYLON.Vector3.Zero();
  75884. _this.rotationQuaternion = new BABYLON.Quaternion();
  75885. _this._calculatedPosition = BABYLON.Vector3.Zero();
  75886. _this._calculatedRotation = new BABYLON.Quaternion();
  75887. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  75888. return _this;
  75889. }
  75890. /**
  75891. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  75892. */
  75893. PoseEnabledController.prototype.update = function () {
  75894. _super.prototype.update.call(this);
  75895. this._updatePoseAndMesh();
  75896. };
  75897. /**
  75898. * Updates only the pose device and mesh without doing any button event checking
  75899. */
  75900. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  75901. var pose = this.browserGamepad.pose;
  75902. this.updateFromDevice(pose);
  75903. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  75904. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  75905. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75906. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  75907. if (this._mesh) {
  75908. this._mesh.position.copyFrom(this.devicePosition);
  75909. if (this._mesh.rotationQuaternion) {
  75910. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  75911. }
  75912. }
  75913. };
  75914. /**
  75915. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75916. * @param poseData raw pose fromthe device
  75917. */
  75918. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  75919. if (poseData) {
  75920. this.rawPose = poseData;
  75921. if (poseData.position) {
  75922. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  75923. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  75924. this._deviceRoomPosition.z *= -1;
  75925. }
  75926. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  75927. this._calculatedPosition.addInPlace(this.position);
  75928. }
  75929. var pose = this.rawPose;
  75930. if (poseData.orientation && pose.orientation) {
  75931. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  75932. if (this._mesh) {
  75933. if (this._mesh.getScene().useRightHandedSystem) {
  75934. this._deviceRoomRotationQuaternion.z *= -1;
  75935. this._deviceRoomRotationQuaternion.w *= -1;
  75936. }
  75937. else {
  75938. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  75939. }
  75940. }
  75941. // if the camera is set, rotate to the camera's rotation
  75942. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  75943. }
  75944. }
  75945. };
  75946. /**
  75947. * Attaches a mesh to the controller
  75948. * @param mesh the mesh to be attached
  75949. */
  75950. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  75951. if (this._mesh) {
  75952. this._mesh.parent = null;
  75953. }
  75954. this._mesh = mesh;
  75955. if (this._poseControlledCamera) {
  75956. this._mesh.parent = this._poseControlledCamera;
  75957. }
  75958. if (!this._mesh.rotationQuaternion) {
  75959. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  75960. }
  75961. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  75962. this._updatePoseAndMesh();
  75963. if (this._pointingPoseNode) {
  75964. var parents = [];
  75965. var obj = this._pointingPoseNode;
  75966. while (obj.parent) {
  75967. parents.push(obj.parent);
  75968. obj = obj.parent;
  75969. }
  75970. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  75971. }
  75972. this._meshAttachedObservable.notifyObservers(mesh);
  75973. };
  75974. /**
  75975. * Attaches the controllers mesh to a camera
  75976. * @param camera the camera the mesh should be attached to
  75977. */
  75978. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  75979. this._poseControlledCamera = camera;
  75980. if (this._mesh) {
  75981. this._mesh.parent = this._poseControlledCamera;
  75982. }
  75983. };
  75984. /**
  75985. * Disposes of the controller
  75986. */
  75987. PoseEnabledController.prototype.dispose = function () {
  75988. if (this._mesh) {
  75989. this._mesh.dispose();
  75990. }
  75991. this._mesh = null;
  75992. _super.prototype.dispose.call(this);
  75993. };
  75994. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  75995. /**
  75996. * The mesh that is attached to the controller
  75997. */
  75998. get: function () {
  75999. return this._mesh;
  76000. },
  76001. enumerable: true,
  76002. configurable: true
  76003. });
  76004. /**
  76005. * Gets the ray of the controller in the direction the controller is pointing
  76006. * @param length the length the resulting ray should be
  76007. * @returns a ray in the direction the controller is pointing
  76008. */
  76009. PoseEnabledController.prototype.getForwardRay = function (length) {
  76010. if (length === void 0) { length = 100; }
  76011. if (!this.mesh) {
  76012. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  76013. }
  76014. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  76015. var origin = m.getTranslation();
  76016. var forward = new BABYLON.Vector3(0, 0, -1);
  76017. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76018. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76019. return new BABYLON.Ray(origin, direction, length);
  76020. };
  76021. /**
  76022. * Name of the child mesh that can be used to cast a ray from the controller
  76023. */
  76024. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  76025. return PoseEnabledController;
  76026. }(BABYLON.Gamepad));
  76027. BABYLON.PoseEnabledController = PoseEnabledController;
  76028. })(BABYLON || (BABYLON = {}));
  76029. //# sourceMappingURL=babylon.poseEnabledController.js.map
  76030. var BABYLON;
  76031. (function (BABYLON) {
  76032. /**
  76033. * Defines the WebVRController object that represents controllers tracked in 3D space
  76034. */
  76035. var WebVRController = /** @class */ (function (_super) {
  76036. __extends(WebVRController, _super);
  76037. /**
  76038. * Creates a new WebVRController from a gamepad
  76039. * @param vrGamepad the gamepad that the WebVRController should be created from
  76040. */
  76041. function WebVRController(vrGamepad) {
  76042. var _this = _super.call(this, vrGamepad) || this;
  76043. // Observables
  76044. /**
  76045. * Fired when the trigger state has changed
  76046. */
  76047. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  76048. /**
  76049. * Fired when the main button state has changed
  76050. */
  76051. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  76052. /**
  76053. * Fired when the secondary button state has changed
  76054. */
  76055. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  76056. /**
  76057. * Fired when the pad state has changed
  76058. */
  76059. _this.onPadStateChangedObservable = new BABYLON.Observable();
  76060. /**
  76061. * Fired when controllers stick values have changed
  76062. */
  76063. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  76064. /**
  76065. * X and Y axis corrisponding to the controllers joystick
  76066. */
  76067. _this.pad = { x: 0, y: 0 };
  76068. // avoid GC, store state in a tmp object
  76069. _this._changes = {
  76070. pressChanged: false,
  76071. touchChanged: false,
  76072. valueChanged: false,
  76073. changed: false
  76074. };
  76075. _this._buttons = new Array(vrGamepad.buttons.length);
  76076. _this.hand = vrGamepad.hand;
  76077. return _this;
  76078. }
  76079. /**
  76080. * Fired when a controller button's state has changed
  76081. * @param callback the callback containing the button that was modified
  76082. */
  76083. WebVRController.prototype.onButtonStateChange = function (callback) {
  76084. this._onButtonStateChange = callback;
  76085. };
  76086. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  76087. /**
  76088. * The default controller model for the controller
  76089. */
  76090. get: function () {
  76091. return this._defaultModel;
  76092. },
  76093. enumerable: true,
  76094. configurable: true
  76095. });
  76096. /**
  76097. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  76098. */
  76099. WebVRController.prototype.update = function () {
  76100. _super.prototype.update.call(this);
  76101. for (var index = 0; index < this._buttons.length; index++) {
  76102. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  76103. }
  76104. ;
  76105. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  76106. this.pad.x = this.leftStick.x;
  76107. this.pad.y = this.leftStick.y;
  76108. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  76109. }
  76110. };
  76111. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  76112. if (!newState) {
  76113. newState = {
  76114. pressed: false,
  76115. touched: false,
  76116. value: 0
  76117. };
  76118. }
  76119. if (!currentState) {
  76120. this._buttons[buttonIndex] = {
  76121. pressed: newState.pressed,
  76122. touched: newState.touched,
  76123. value: newState.value
  76124. };
  76125. return;
  76126. }
  76127. this._checkChanges(newState, currentState);
  76128. if (this._changes.changed) {
  76129. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  76130. this._handleButtonChange(buttonIndex, newState, this._changes);
  76131. }
  76132. this._buttons[buttonIndex].pressed = newState.pressed;
  76133. this._buttons[buttonIndex].touched = newState.touched;
  76134. // oculus triggers are never 0, thou not touched.
  76135. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  76136. };
  76137. WebVRController.prototype._checkChanges = function (newState, currentState) {
  76138. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  76139. this._changes.touchChanged = newState.touched !== currentState.touched;
  76140. this._changes.valueChanged = newState.value !== currentState.value;
  76141. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  76142. return this._changes;
  76143. };
  76144. /**
  76145. * Disposes of th webVRCOntroller
  76146. */
  76147. WebVRController.prototype.dispose = function () {
  76148. _super.prototype.dispose.call(this);
  76149. this.onTriggerStateChangedObservable.clear();
  76150. this.onMainButtonStateChangedObservable.clear();
  76151. this.onSecondaryButtonStateChangedObservable.clear();
  76152. this.onPadStateChangedObservable.clear();
  76153. this.onPadValuesChangedObservable.clear();
  76154. };
  76155. return WebVRController;
  76156. }(BABYLON.PoseEnabledController));
  76157. BABYLON.WebVRController = WebVRController;
  76158. })(BABYLON || (BABYLON = {}));
  76159. //# sourceMappingURL=babylon.webVRController.js.map
  76160. var BABYLON;
  76161. (function (BABYLON) {
  76162. /**
  76163. * Oculus Touch Controller
  76164. */
  76165. var OculusTouchController = /** @class */ (function (_super) {
  76166. __extends(OculusTouchController, _super);
  76167. /**
  76168. * Creates a new OculusTouchController from a gamepad
  76169. * @param vrGamepad the gamepad that the controller should be created from
  76170. */
  76171. function OculusTouchController(vrGamepad) {
  76172. var _this = _super.call(this, vrGamepad) || this;
  76173. /**
  76174. * Fired when the secondary trigger on this controller is modified
  76175. */
  76176. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  76177. /**
  76178. * Fired when the thumb rest on this controller is modified
  76179. */
  76180. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  76181. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  76182. return _this;
  76183. }
  76184. /**
  76185. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76186. * @param scene scene in which to add meshes
  76187. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76188. */
  76189. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76190. var _this = this;
  76191. var meshName;
  76192. // Hand
  76193. if (this.hand === 'left') {
  76194. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  76195. }
  76196. else { // Right is the default if no hand is specified
  76197. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  76198. }
  76199. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  76200. /*
  76201. Parent Mesh name: oculus_touch_left
  76202. - body
  76203. - trigger
  76204. - thumbstick
  76205. - grip
  76206. - button_y
  76207. - button_x
  76208. - button_enter
  76209. */
  76210. _this._defaultModel = newMeshes[1];
  76211. _this.attachToMesh(_this._defaultModel);
  76212. if (meshLoaded) {
  76213. meshLoaded(_this._defaultModel);
  76214. }
  76215. });
  76216. };
  76217. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  76218. /**
  76219. * Fired when the A button on this controller is modified
  76220. */
  76221. get: function () {
  76222. if (this.hand === 'right') {
  76223. return this.onMainButtonStateChangedObservable;
  76224. }
  76225. else {
  76226. throw new Error('No A button on left hand');
  76227. }
  76228. },
  76229. enumerable: true,
  76230. configurable: true
  76231. });
  76232. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  76233. /**
  76234. * Fired when the B button on this controller is modified
  76235. */
  76236. get: function () {
  76237. if (this.hand === 'right') {
  76238. return this.onSecondaryButtonStateChangedObservable;
  76239. }
  76240. else {
  76241. throw new Error('No B button on left hand');
  76242. }
  76243. },
  76244. enumerable: true,
  76245. configurable: true
  76246. });
  76247. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  76248. /**
  76249. * Fired when the X button on this controller is modified
  76250. */
  76251. get: function () {
  76252. if (this.hand === 'left') {
  76253. return this.onMainButtonStateChangedObservable;
  76254. }
  76255. else {
  76256. throw new Error('No X button on right hand');
  76257. }
  76258. },
  76259. enumerable: true,
  76260. configurable: true
  76261. });
  76262. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  76263. /**
  76264. * Fired when the Y button on this controller is modified
  76265. */
  76266. get: function () {
  76267. if (this.hand === 'left') {
  76268. return this.onSecondaryButtonStateChangedObservable;
  76269. }
  76270. else {
  76271. throw new Error('No Y button on right hand');
  76272. }
  76273. },
  76274. enumerable: true,
  76275. configurable: true
  76276. });
  76277. /**
  76278. * Called once for each button that changed state since the last frame
  76279. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  76280. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  76281. * 2) secondary trigger (same)
  76282. * 3) A (right) X (left), touch, pressed = value
  76283. * 4) B / Y
  76284. * 5) thumb rest
  76285. * @param buttonIdx Which button index changed
  76286. * @param state New state of the button
  76287. * @param changes Which properties on the state changed since last frame
  76288. */
  76289. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76290. var notifyObject = state; //{ state: state, changes: changes };
  76291. var triggerDirection = this.hand === 'right' ? -1 : 1;
  76292. switch (buttonIdx) {
  76293. case 0:
  76294. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76295. return;
  76296. case 1: // index trigger
  76297. if (this._defaultModel) {
  76298. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  76299. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  76300. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  76301. }
  76302. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76303. return;
  76304. case 2: // secondary trigger
  76305. if (this._defaultModel) {
  76306. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  76307. }
  76308. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  76309. return;
  76310. case 3:
  76311. if (this._defaultModel) {
  76312. if (notifyObject.pressed) {
  76313. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  76314. }
  76315. else {
  76316. (this._defaultModel.getChildren()[1]).position.y = 0;
  76317. }
  76318. }
  76319. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76320. return;
  76321. case 4:
  76322. if (this._defaultModel) {
  76323. if (notifyObject.pressed) {
  76324. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76325. }
  76326. else {
  76327. (this._defaultModel.getChildren()[2]).position.y = 0;
  76328. }
  76329. }
  76330. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76331. return;
  76332. case 5:
  76333. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  76334. return;
  76335. }
  76336. };
  76337. /**
  76338. * Base Url for the controller model.
  76339. */
  76340. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  76341. /**
  76342. * File name for the left controller model.
  76343. */
  76344. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  76345. /**
  76346. * File name for the right controller model.
  76347. */
  76348. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  76349. return OculusTouchController;
  76350. }(BABYLON.WebVRController));
  76351. BABYLON.OculusTouchController = OculusTouchController;
  76352. })(BABYLON || (BABYLON = {}));
  76353. //# sourceMappingURL=babylon.oculusTouchController.js.map
  76354. var BABYLON;
  76355. (function (BABYLON) {
  76356. /**
  76357. * Vive Controller
  76358. */
  76359. var ViveController = /** @class */ (function (_super) {
  76360. __extends(ViveController, _super);
  76361. /**
  76362. * Creates a new ViveController from a gamepad
  76363. * @param vrGamepad the gamepad that the controller should be created from
  76364. */
  76365. function ViveController(vrGamepad) {
  76366. var _this = _super.call(this, vrGamepad) || this;
  76367. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  76368. _this._invertLeftStickY = true;
  76369. return _this;
  76370. }
  76371. /**
  76372. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76373. * @param scene scene in which to add meshes
  76374. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76375. */
  76376. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76377. var _this = this;
  76378. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  76379. /*
  76380. Parent Mesh name: ViveWand
  76381. - body
  76382. - r_gripper
  76383. - l_gripper
  76384. - menu_button
  76385. - system_button
  76386. - trackpad
  76387. - trigger
  76388. - LED
  76389. */
  76390. _this._defaultModel = newMeshes[1];
  76391. _this.attachToMesh(_this._defaultModel);
  76392. if (meshLoaded) {
  76393. meshLoaded(_this._defaultModel);
  76394. }
  76395. });
  76396. };
  76397. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  76398. /**
  76399. * Fired when the left button on this controller is modified
  76400. */
  76401. get: function () {
  76402. return this.onMainButtonStateChangedObservable;
  76403. },
  76404. enumerable: true,
  76405. configurable: true
  76406. });
  76407. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  76408. /**
  76409. * Fired when the right button on this controller is modified
  76410. */
  76411. get: function () {
  76412. return this.onMainButtonStateChangedObservable;
  76413. },
  76414. enumerable: true,
  76415. configurable: true
  76416. });
  76417. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  76418. /**
  76419. * Fired when the menu button on this controller is modified
  76420. */
  76421. get: function () {
  76422. return this.onSecondaryButtonStateChangedObservable;
  76423. },
  76424. enumerable: true,
  76425. configurable: true
  76426. });
  76427. /**
  76428. * Called once for each button that changed state since the last frame
  76429. * Vive mapping:
  76430. * 0: touchpad
  76431. * 1: trigger
  76432. * 2: left AND right buttons
  76433. * 3: menu button
  76434. * @param buttonIdx Which button index changed
  76435. * @param state New state of the button
  76436. * @param changes Which properties on the state changed since last frame
  76437. */
  76438. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76439. var notifyObject = state; //{ state: state, changes: changes };
  76440. switch (buttonIdx) {
  76441. case 0:
  76442. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76443. return;
  76444. case 1: // index trigger
  76445. if (this._defaultModel) {
  76446. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  76447. }
  76448. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76449. return;
  76450. case 2: // left AND right button
  76451. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76452. return;
  76453. case 3:
  76454. if (this._defaultModel) {
  76455. if (notifyObject.pressed) {
  76456. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76457. }
  76458. else {
  76459. (this._defaultModel.getChildren()[2]).position.y = 0;
  76460. }
  76461. }
  76462. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76463. return;
  76464. }
  76465. };
  76466. /**
  76467. * Base Url for the controller model.
  76468. */
  76469. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  76470. /**
  76471. * File name for the controller model.
  76472. */
  76473. ViveController.MODEL_FILENAME = 'wand.babylon';
  76474. return ViveController;
  76475. }(BABYLON.WebVRController));
  76476. BABYLON.ViveController = ViveController;
  76477. })(BABYLON || (BABYLON = {}));
  76478. //# sourceMappingURL=babylon.viveController.js.map
  76479. var BABYLON;
  76480. (function (BABYLON) {
  76481. /**
  76482. * Generic Controller
  76483. */
  76484. var GenericController = /** @class */ (function (_super) {
  76485. __extends(GenericController, _super);
  76486. /**
  76487. * Creates a new GenericController from a gamepad
  76488. * @param vrGamepad the gamepad that the controller should be created from
  76489. */
  76490. function GenericController(vrGamepad) {
  76491. return _super.call(this, vrGamepad) || this;
  76492. }
  76493. /**
  76494. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76495. * @param scene scene in which to add meshes
  76496. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76497. */
  76498. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76499. var _this = this;
  76500. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  76501. _this._defaultModel = newMeshes[1];
  76502. _this.attachToMesh(_this._defaultModel);
  76503. if (meshLoaded) {
  76504. meshLoaded(_this._defaultModel);
  76505. }
  76506. });
  76507. };
  76508. /**
  76509. * Called once for each button that changed state since the last frame
  76510. * @param buttonIdx Which button index changed
  76511. * @param state New state of the button
  76512. * @param changes Which properties on the state changed since last frame
  76513. */
  76514. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76515. console.log("Button id: " + buttonIdx + "state: ");
  76516. console.dir(state);
  76517. };
  76518. /**
  76519. * Base Url for the controller model.
  76520. */
  76521. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76522. /**
  76523. * File name for the controller model.
  76524. */
  76525. GenericController.MODEL_FILENAME = 'generic.babylon';
  76526. return GenericController;
  76527. }(BABYLON.WebVRController));
  76528. BABYLON.GenericController = GenericController;
  76529. })(BABYLON || (BABYLON = {}));
  76530. //# sourceMappingURL=babylon.genericController.js.map
  76531. var BABYLON;
  76532. (function (BABYLON) {
  76533. /**
  76534. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  76535. */
  76536. var LoadedMeshInfo = /** @class */ (function () {
  76537. function LoadedMeshInfo() {
  76538. /**
  76539. * Map of the button meshes contained in the controller
  76540. */
  76541. this.buttonMeshes = {};
  76542. /**
  76543. * Map of the axis meshes contained in the controller
  76544. */
  76545. this.axisMeshes = {};
  76546. }
  76547. return LoadedMeshInfo;
  76548. }());
  76549. /**
  76550. * Defines the WindowsMotionController object that the state of the windows motion controller
  76551. */
  76552. var WindowsMotionController = /** @class */ (function (_super) {
  76553. __extends(WindowsMotionController, _super);
  76554. /**
  76555. * Creates a new WindowsMotionController from a gamepad
  76556. * @param vrGamepad the gamepad that the controller should be created from
  76557. */
  76558. function WindowsMotionController(vrGamepad) {
  76559. var _this = _super.call(this, vrGamepad) || this;
  76560. _this._mapping = {
  76561. // Semantic button names
  76562. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  76563. // A mapping of the button name to glTF model node name
  76564. // that should be transformed by button value.
  76565. buttonMeshNames: {
  76566. 'trigger': 'SELECT',
  76567. 'menu': 'MENU',
  76568. 'grip': 'GRASP',
  76569. 'thumbstick': 'THUMBSTICK_PRESS',
  76570. 'trackpad': 'TOUCHPAD_PRESS'
  76571. },
  76572. // This mapping is used to translate from the Motion Controller to Babylon semantics
  76573. buttonObservableNames: {
  76574. 'trigger': 'onTriggerStateChangedObservable',
  76575. 'menu': 'onSecondaryButtonStateChangedObservable',
  76576. 'grip': 'onMainButtonStateChangedObservable',
  76577. 'thumbstick': 'onPadStateChangedObservable',
  76578. 'trackpad': 'onTrackpadChangedObservable'
  76579. },
  76580. // A mapping of the axis name to glTF model node name
  76581. // that should be transformed by axis value.
  76582. // This array mirrors the browserGamepad.axes array, such that
  76583. // the mesh corresponding to axis 0 is in this array index 0.
  76584. axisMeshNames: [
  76585. 'THUMBSTICK_X',
  76586. 'THUMBSTICK_Y',
  76587. 'TOUCHPAD_TOUCH_X',
  76588. 'TOUCHPAD_TOUCH_Y'
  76589. ],
  76590. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  76591. };
  76592. /**
  76593. * Fired when the trackpad on this controller is clicked
  76594. */
  76595. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  76596. /**
  76597. * Fired when the trackpad on this controller is modified
  76598. */
  76599. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  76600. /**
  76601. * The current x and y values of this controller's trackpad
  76602. */
  76603. _this.trackpad = { x: 0, y: 0 };
  76604. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  76605. _this._loadedMeshInfo = null;
  76606. return _this;
  76607. }
  76608. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  76609. /**
  76610. * Fired when the trigger on this controller is modified
  76611. */
  76612. get: function () {
  76613. return this.onTriggerStateChangedObservable;
  76614. },
  76615. enumerable: true,
  76616. configurable: true
  76617. });
  76618. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  76619. /**
  76620. * Fired when the menu button on this controller is modified
  76621. */
  76622. get: function () {
  76623. return this.onSecondaryButtonStateChangedObservable;
  76624. },
  76625. enumerable: true,
  76626. configurable: true
  76627. });
  76628. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  76629. /**
  76630. * Fired when the grip button on this controller is modified
  76631. */
  76632. get: function () {
  76633. return this.onMainButtonStateChangedObservable;
  76634. },
  76635. enumerable: true,
  76636. configurable: true
  76637. });
  76638. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  76639. /**
  76640. * Fired when the thumbstick button on this controller is modified
  76641. */
  76642. get: function () {
  76643. return this.onPadStateChangedObservable;
  76644. },
  76645. enumerable: true,
  76646. configurable: true
  76647. });
  76648. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  76649. /**
  76650. * Fired when the touchpad button on this controller is modified
  76651. */
  76652. get: function () {
  76653. return this.onTrackpadChangedObservable;
  76654. },
  76655. enumerable: true,
  76656. configurable: true
  76657. });
  76658. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  76659. /**
  76660. * Fired when the touchpad values on this controller are modified
  76661. */
  76662. get: function () {
  76663. return this.onTrackpadValuesChangedObservable;
  76664. },
  76665. enumerable: true,
  76666. configurable: true
  76667. });
  76668. WindowsMotionController.prototype._updateTrackpad = function () {
  76669. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  76670. this.trackpad.x = this.browserGamepad["axes"][2];
  76671. this.trackpad.y = this.browserGamepad["axes"][3];
  76672. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  76673. }
  76674. };
  76675. /**
  76676. * Called once per frame by the engine.
  76677. */
  76678. WindowsMotionController.prototype.update = function () {
  76679. _super.prototype.update.call(this);
  76680. if (this.browserGamepad.axes) {
  76681. this._updateTrackpad();
  76682. // Only need to animate axes if there is a loaded mesh
  76683. if (this._loadedMeshInfo) {
  76684. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  76685. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  76686. }
  76687. }
  76688. }
  76689. };
  76690. /**
  76691. * Called once for each button that changed state since the last frame
  76692. * @param buttonIdx Which button index changed
  76693. * @param state New state of the button
  76694. * @param changes Which properties on the state changed since last frame
  76695. */
  76696. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76697. var buttonName = this._mapping.buttons[buttonIdx];
  76698. if (!buttonName) {
  76699. return;
  76700. }
  76701. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  76702. this._updateTrackpad();
  76703. // Only emit events for buttons that we know how to map from index to name
  76704. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  76705. if (observable) {
  76706. observable.notifyObservers(state);
  76707. }
  76708. this._lerpButtonTransform(buttonName, state.value);
  76709. };
  76710. /**
  76711. * Moves the buttons on the controller mesh based on their current state
  76712. * @param buttonName the name of the button to move
  76713. * @param buttonValue the value of the button which determines the buttons new position
  76714. */
  76715. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  76716. // If there is no loaded mesh, there is nothing to transform.
  76717. if (!this._loadedMeshInfo) {
  76718. return;
  76719. }
  76720. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  76721. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76722. return;
  76723. }
  76724. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  76725. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  76726. };
  76727. /**
  76728. * Moves the axis on the controller mesh based on its current state
  76729. * @param axis the index of the axis
  76730. * @param axisValue the value of the axis which determines the meshes new position
  76731. * @hidden
  76732. */
  76733. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  76734. if (!this._loadedMeshInfo) {
  76735. return;
  76736. }
  76737. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  76738. if (!meshInfo) {
  76739. return;
  76740. }
  76741. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76742. return;
  76743. }
  76744. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  76745. var lerpValue = axisValue * 0.5 + 0.5;
  76746. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  76747. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  76748. };
  76749. /**
  76750. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76751. * @param scene scene in which to add meshes
  76752. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76753. */
  76754. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  76755. var _this = this;
  76756. if (forceDefault === void 0) { forceDefault = false; }
  76757. var path;
  76758. var filename;
  76759. // Checking if GLB loader is present
  76760. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  76761. // Determine the device specific folder based on the ID suffix
  76762. var device = 'default';
  76763. if (this.id && !forceDefault) {
  76764. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  76765. device = ((match && match[0]) || device);
  76766. }
  76767. // Hand
  76768. if (this.hand === 'left') {
  76769. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  76770. }
  76771. else { // Right is the default if no hand is specified
  76772. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  76773. }
  76774. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  76775. }
  76776. else {
  76777. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  76778. path = BABYLON.GenericController.MODEL_BASE_URL;
  76779. filename = BABYLON.GenericController.MODEL_FILENAME;
  76780. }
  76781. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  76782. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  76783. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  76784. if (!_this._loadedMeshInfo) {
  76785. return;
  76786. }
  76787. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  76788. _this.attachToMesh(_this._defaultModel);
  76789. if (meshLoaded) {
  76790. meshLoaded(_this._defaultModel);
  76791. }
  76792. }, null, function (scene, message) {
  76793. BABYLON.Tools.Log(message);
  76794. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  76795. if (!forceDefault) {
  76796. _this.initControllerMesh(scene, meshLoaded, true);
  76797. }
  76798. });
  76799. };
  76800. /**
  76801. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  76802. * can be transformed by button presses and axes values, based on this._mapping.
  76803. *
  76804. * @param scene scene in which the meshes exist
  76805. * @param meshes list of meshes that make up the controller model to process
  76806. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  76807. */
  76808. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  76809. var loadedMeshInfo = null;
  76810. // Create a new mesh to contain the glTF hierarchy
  76811. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  76812. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  76813. var childMesh = null;
  76814. for (var i = 0; i < meshes.length; i++) {
  76815. var mesh = meshes[i];
  76816. if (!mesh.parent) {
  76817. // Exclude controller meshes from picking results
  76818. mesh.isPickable = false;
  76819. // Handle root node, attach to the new parentMesh
  76820. childMesh = mesh;
  76821. break;
  76822. }
  76823. }
  76824. if (childMesh) {
  76825. childMesh.setParent(parentMesh);
  76826. // Create our mesh info. Note that this method will always return non-null.
  76827. loadedMeshInfo = this.createMeshInfo(parentMesh);
  76828. }
  76829. else {
  76830. BABYLON.Tools.Warn('Could not find root node in model file.');
  76831. }
  76832. return loadedMeshInfo;
  76833. };
  76834. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  76835. var loadedMeshInfo = new LoadedMeshInfo();
  76836. var i;
  76837. loadedMeshInfo.rootNode = rootNode;
  76838. // Reset the caches
  76839. loadedMeshInfo.buttonMeshes = {};
  76840. loadedMeshInfo.axisMeshes = {};
  76841. // Button Meshes
  76842. for (i = 0; i < this._mapping.buttons.length; i++) {
  76843. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  76844. if (!buttonMeshName) {
  76845. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  76846. continue;
  76847. }
  76848. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  76849. if (!buttonMesh) {
  76850. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  76851. continue;
  76852. }
  76853. var buttonMeshInfo = {
  76854. index: i,
  76855. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  76856. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  76857. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  76858. };
  76859. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  76860. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  76861. }
  76862. else {
  76863. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  76864. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  76865. '(VALUE: ' + !!buttonMeshInfo.value +
  76866. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  76867. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  76868. ')');
  76869. }
  76870. }
  76871. // Axis Meshes
  76872. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  76873. var axisMeshName = this._mapping.axisMeshNames[i];
  76874. if (!axisMeshName) {
  76875. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  76876. continue;
  76877. }
  76878. var axisMesh = getChildByName(rootNode, axisMeshName);
  76879. if (!axisMesh) {
  76880. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  76881. continue;
  76882. }
  76883. var axisMeshInfo = {
  76884. index: i,
  76885. value: getImmediateChildByName(axisMesh, 'VALUE'),
  76886. min: getImmediateChildByName(axisMesh, 'MIN'),
  76887. max: getImmediateChildByName(axisMesh, 'MAX')
  76888. };
  76889. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  76890. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  76891. }
  76892. else {
  76893. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  76894. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  76895. '(VALUE: ' + !!axisMeshInfo.value +
  76896. ', MIN: ' + !!axisMeshInfo.min +
  76897. ', MAX:' + !!axisMeshInfo.max +
  76898. ')');
  76899. }
  76900. }
  76901. // Pointing Ray
  76902. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  76903. if (!loadedMeshInfo.pointingPoseNode) {
  76904. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  76905. }
  76906. else {
  76907. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  76908. }
  76909. return loadedMeshInfo;
  76910. // Look through all children recursively. This will return null if no mesh exists with the given name.
  76911. function getChildByName(node, name) {
  76912. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  76913. }
  76914. // Look through only immediate children. This will return null if no mesh exists with the given name.
  76915. function getImmediateChildByName(node, name) {
  76916. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  76917. }
  76918. };
  76919. /**
  76920. * Gets the ray of the controller in the direction the controller is pointing
  76921. * @param length the length the resulting ray should be
  76922. * @returns a ray in the direction the controller is pointing
  76923. */
  76924. WindowsMotionController.prototype.getForwardRay = function (length) {
  76925. if (length === void 0) { length = 100; }
  76926. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  76927. return _super.prototype.getForwardRay.call(this, length);
  76928. }
  76929. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  76930. var origin = m.getTranslation();
  76931. var forward = new BABYLON.Vector3(0, 0, -1);
  76932. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76933. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76934. return new BABYLON.Ray(origin, direction, length);
  76935. };
  76936. /**
  76937. * Disposes of the controller
  76938. */
  76939. WindowsMotionController.prototype.dispose = function () {
  76940. _super.prototype.dispose.call(this);
  76941. this.onTrackpadChangedObservable.clear();
  76942. };
  76943. /**
  76944. * The base url used to load the left and right controller models
  76945. */
  76946. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  76947. /**
  76948. * The name of the left controller model file
  76949. */
  76950. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  76951. /**
  76952. * The name of the right controller model file
  76953. */
  76954. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  76955. /**
  76956. * The controller name prefix for this controller type
  76957. */
  76958. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  76959. /**
  76960. * The controller id pattern for this controller type
  76961. */
  76962. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  76963. return WindowsMotionController;
  76964. }(BABYLON.WebVRController));
  76965. BABYLON.WindowsMotionController = WindowsMotionController;
  76966. })(BABYLON || (BABYLON = {}));
  76967. //# sourceMappingURL=babylon.windowsMotionController.js.map
  76968. var BABYLON;
  76969. (function (BABYLON) {
  76970. /**
  76971. * Gear VR Controller
  76972. */
  76973. var GearVRController = /** @class */ (function (_super) {
  76974. __extends(GearVRController, _super);
  76975. /**
  76976. * Creates a new GearVRController from a gamepad
  76977. * @param vrGamepad the gamepad that the controller should be created from
  76978. */
  76979. function GearVRController(vrGamepad) {
  76980. var _this = _super.call(this, vrGamepad) || this;
  76981. _this._maxRotationDistFromHeadset = Math.PI / 5;
  76982. _this._draggedRoomRotation = 0;
  76983. _this._tmpVector = new BABYLON.Vector3();
  76984. _this._buttonIndexToObservableNameMap = [
  76985. 'onTrackpadChangedObservable',
  76986. 'onTriggerStateChangedObservable' // Trigger
  76987. ];
  76988. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  76989. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  76990. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  76991. return _this;
  76992. }
  76993. /**
  76994. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76995. * @param poseData raw pose fromthe device
  76996. */
  76997. GearVRController.prototype.updateFromDevice = function (poseData) {
  76998. _super.prototype.updateFromDevice.call(this, poseData);
  76999. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  77000. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  77001. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  77002. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  77003. // Find the radian distance away that the headset is from the controllers rotation
  77004. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  77005. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  77006. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  77007. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  77008. this._draggedRoomRotation += rotationAmount;
  77009. // Rotate controller around headset
  77010. var sin = Math.sin(-rotationAmount);
  77011. var cos = Math.cos(-rotationAmount);
  77012. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  77013. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  77014. }
  77015. }
  77016. }
  77017. };
  77018. /**
  77019. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77020. * @param scene scene in which to add meshes
  77021. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77022. */
  77023. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77024. var _this = this;
  77025. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  77026. // Offset the controller so it will rotate around the users wrist
  77027. var mesh = new BABYLON.Mesh("", scene);
  77028. newMeshes[1].parent = mesh;
  77029. newMeshes[1].position.z = -0.15;
  77030. _this._defaultModel = mesh;
  77031. _this.attachToMesh(_this._defaultModel);
  77032. if (meshLoaded) {
  77033. meshLoaded(_this._defaultModel);
  77034. }
  77035. });
  77036. };
  77037. /**
  77038. * Called once for each button that changed state since the last frame
  77039. * @param buttonIdx Which button index changed
  77040. * @param state New state of the button
  77041. * @param changes Which properties on the state changed since last frame
  77042. */
  77043. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77044. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  77045. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  77046. // Only emit events for buttons that we know how to map from index to observable
  77047. var observable = this[observableName];
  77048. if (observable) {
  77049. observable.notifyObservers(state);
  77050. }
  77051. }
  77052. };
  77053. /**
  77054. * Base Url for the controller model.
  77055. */
  77056. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  77057. /**
  77058. * File name for the controller model.
  77059. */
  77060. GearVRController.MODEL_FILENAME = 'generic.babylon';
  77061. /**
  77062. * Gamepad Id prefix used to identify this controller.
  77063. */
  77064. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  77065. return GearVRController;
  77066. }(BABYLON.WebVRController));
  77067. BABYLON.GearVRController = GearVRController;
  77068. })(BABYLON || (BABYLON = {}));
  77069. //# sourceMappingURL=babylon.gearVRController.js.map
  77070. var BABYLON;
  77071. (function (BABYLON) {
  77072. /**
  77073. * Google Daydream controller
  77074. */
  77075. var DaydreamController = /** @class */ (function (_super) {
  77076. __extends(DaydreamController, _super);
  77077. /**
  77078. * Creates a new DaydreamController from a gamepad
  77079. * @param vrGamepad the gamepad that the controller should be created from
  77080. */
  77081. function DaydreamController(vrGamepad) {
  77082. var _this = _super.call(this, vrGamepad) || this;
  77083. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  77084. return _this;
  77085. }
  77086. /**
  77087. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77088. * @param scene scene in which to add meshes
  77089. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77090. */
  77091. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77092. var _this = this;
  77093. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  77094. _this._defaultModel = newMeshes[1];
  77095. _this.attachToMesh(_this._defaultModel);
  77096. if (meshLoaded) {
  77097. meshLoaded(_this._defaultModel);
  77098. }
  77099. });
  77100. };
  77101. /**
  77102. * Called once for each button that changed state since the last frame
  77103. * @param buttonIdx Which button index changed
  77104. * @param state New state of the button
  77105. * @param changes Which properties on the state changed since last frame
  77106. */
  77107. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77108. // Daydream controller only has 1 GamepadButton (on the trackpad).
  77109. if (buttonIdx === 0) {
  77110. var observable = this.onTriggerStateChangedObservable;
  77111. if (observable) {
  77112. observable.notifyObservers(state);
  77113. }
  77114. }
  77115. else {
  77116. // If the app or home buttons are ever made available
  77117. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  77118. }
  77119. };
  77120. /**
  77121. * Base Url for the controller model.
  77122. */
  77123. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  77124. /**
  77125. * File name for the controller model.
  77126. */
  77127. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  77128. /**
  77129. * Gamepad Id prefix used to identify Daydream Controller.
  77130. */
  77131. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  77132. return DaydreamController;
  77133. }(BABYLON.WebVRController));
  77134. BABYLON.DaydreamController = DaydreamController;
  77135. })(BABYLON || (BABYLON = {}));
  77136. //# sourceMappingURL=babylon.daydreamController.js.map
  77137. var BABYLON;
  77138. (function (BABYLON) {
  77139. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  77140. get: function () {
  77141. if (!this._gamepadManager) {
  77142. this._gamepadManager = new BABYLON.GamepadManager(this);
  77143. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  77144. if (!component) {
  77145. component = new GamepadSystemSceneComponent(this);
  77146. this._addComponent(component);
  77147. }
  77148. }
  77149. return this._gamepadManager;
  77150. },
  77151. enumerable: true,
  77152. configurable: true
  77153. });
  77154. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  77155. this.add(new BABYLON.FreeCameraGamepadInput());
  77156. return this;
  77157. };
  77158. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  77159. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  77160. return this;
  77161. };
  77162. /**
  77163. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  77164. */
  77165. var GamepadSystemSceneComponent = /** @class */ (function () {
  77166. /**
  77167. * Creates a new instance of the component for the given scene
  77168. * @param scene Defines the scene to register the component in
  77169. */
  77170. function GamepadSystemSceneComponent(scene) {
  77171. /**
  77172. * The component name helpfull to identify the component in the list of scene components.
  77173. */
  77174. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  77175. this.scene = scene;
  77176. }
  77177. /**
  77178. * Registers the component in a given scene
  77179. */
  77180. GamepadSystemSceneComponent.prototype.register = function () {
  77181. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  77182. };
  77183. /**
  77184. * Rebuilds the elements related to this component in case of
  77185. * context lost for instance.
  77186. */
  77187. GamepadSystemSceneComponent.prototype.rebuild = function () {
  77188. // Nothing to do for gamepads
  77189. };
  77190. /**
  77191. * Disposes the component and the associated ressources
  77192. */
  77193. GamepadSystemSceneComponent.prototype.dispose = function () {
  77194. var gamepadManager = this.scene._gamepadManager;
  77195. if (gamepadManager) {
  77196. gamepadManager.dispose();
  77197. this.scene._gamepadManager = null;
  77198. }
  77199. };
  77200. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  77201. var gamepadManager = this.scene._gamepadManager;
  77202. if (gamepadManager && gamepadManager._isMonitoring) {
  77203. gamepadManager._checkGamepadsStatus();
  77204. }
  77205. };
  77206. return GamepadSystemSceneComponent;
  77207. }());
  77208. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  77209. })(BABYLON || (BABYLON = {}));
  77210. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  77211. var BABYLON;
  77212. (function (BABYLON) {
  77213. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  77214. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  77215. });
  77216. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  77217. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  77218. });
  77219. var FollowCamera = /** @class */ (function (_super) {
  77220. __extends(FollowCamera, _super);
  77221. function FollowCamera(name, position, scene, lockedTarget) {
  77222. if (lockedTarget === void 0) { lockedTarget = null; }
  77223. var _this = _super.call(this, name, position, scene) || this;
  77224. _this.radius = 12;
  77225. _this.rotationOffset = 0;
  77226. _this.heightOffset = 4;
  77227. _this.cameraAcceleration = 0.05;
  77228. _this.maxCameraSpeed = 20;
  77229. _this.lockedTarget = lockedTarget;
  77230. return _this;
  77231. }
  77232. FollowCamera.prototype.getRadians = function (degrees) {
  77233. return degrees * Math.PI / 180;
  77234. };
  77235. FollowCamera.prototype.follow = function (cameraTarget) {
  77236. if (!cameraTarget)
  77237. return;
  77238. var yRotation;
  77239. if (cameraTarget.rotationQuaternion) {
  77240. var rotMatrix = new BABYLON.Matrix();
  77241. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  77242. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  77243. }
  77244. else {
  77245. yRotation = cameraTarget.rotation.y;
  77246. }
  77247. var radians = this.getRadians(this.rotationOffset) + yRotation;
  77248. var targetPosition = cameraTarget.getAbsolutePosition();
  77249. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  77250. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  77251. var dx = targetX - this.position.x;
  77252. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  77253. var dz = (targetZ) - this.position.z;
  77254. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  77255. var vy = dy * this.cameraAcceleration;
  77256. var vz = dz * this.cameraAcceleration * 2;
  77257. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  77258. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77259. }
  77260. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  77261. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77262. }
  77263. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  77264. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77265. }
  77266. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  77267. this.setTarget(targetPosition);
  77268. };
  77269. /** @hidden */
  77270. FollowCamera.prototype._checkInputs = function () {
  77271. _super.prototype._checkInputs.call(this);
  77272. if (this.lockedTarget) {
  77273. this.follow(this.lockedTarget);
  77274. }
  77275. };
  77276. FollowCamera.prototype.getClassName = function () {
  77277. return "FollowCamera";
  77278. };
  77279. __decorate([
  77280. BABYLON.serialize()
  77281. ], FollowCamera.prototype, "radius", void 0);
  77282. __decorate([
  77283. BABYLON.serialize()
  77284. ], FollowCamera.prototype, "rotationOffset", void 0);
  77285. __decorate([
  77286. BABYLON.serialize()
  77287. ], FollowCamera.prototype, "heightOffset", void 0);
  77288. __decorate([
  77289. BABYLON.serialize()
  77290. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  77291. __decorate([
  77292. BABYLON.serialize()
  77293. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  77294. __decorate([
  77295. BABYLON.serializeAsMeshReference("lockedTargetId")
  77296. ], FollowCamera.prototype, "lockedTarget", void 0);
  77297. return FollowCamera;
  77298. }(BABYLON.TargetCamera));
  77299. BABYLON.FollowCamera = FollowCamera;
  77300. var ArcFollowCamera = /** @class */ (function (_super) {
  77301. __extends(ArcFollowCamera, _super);
  77302. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  77303. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  77304. _this.alpha = alpha;
  77305. _this.beta = beta;
  77306. _this.radius = radius;
  77307. _this.target = target;
  77308. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  77309. _this.follow();
  77310. return _this;
  77311. }
  77312. ArcFollowCamera.prototype.follow = function () {
  77313. if (!this.target) {
  77314. return;
  77315. }
  77316. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  77317. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  77318. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  77319. var targetPosition = this.target.getAbsolutePosition();
  77320. this.position = targetPosition.add(this._cartesianCoordinates);
  77321. this.setTarget(targetPosition);
  77322. };
  77323. /** @hidden */
  77324. ArcFollowCamera.prototype._checkInputs = function () {
  77325. _super.prototype._checkInputs.call(this);
  77326. this.follow();
  77327. };
  77328. ArcFollowCamera.prototype.getClassName = function () {
  77329. return "ArcFollowCamera";
  77330. };
  77331. return ArcFollowCamera;
  77332. }(BABYLON.TargetCamera));
  77333. BABYLON.ArcFollowCamera = ArcFollowCamera;
  77334. })(BABYLON || (BABYLON = {}));
  77335. //# sourceMappingURL=babylon.followCamera.js.map
  77336. var BABYLON;
  77337. (function (BABYLON) {
  77338. // We're mainly based on the logic defined into the FreeCamera code
  77339. var UniversalCamera = /** @class */ (function (_super) {
  77340. __extends(UniversalCamera, _super);
  77341. //-- end properties for backward compatibility for inputs
  77342. function UniversalCamera(name, position, scene) {
  77343. var _this = _super.call(this, name, position, scene) || this;
  77344. _this.inputs.addGamepad();
  77345. return _this;
  77346. }
  77347. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  77348. //-- Begin properties for backward compatibility for inputs
  77349. get: function () {
  77350. var gamepad = this.inputs.attached["gamepad"];
  77351. if (gamepad)
  77352. return gamepad.gamepadAngularSensibility;
  77353. return 0;
  77354. },
  77355. set: function (value) {
  77356. var gamepad = this.inputs.attached["gamepad"];
  77357. if (gamepad)
  77358. gamepad.gamepadAngularSensibility = value;
  77359. },
  77360. enumerable: true,
  77361. configurable: true
  77362. });
  77363. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  77364. get: function () {
  77365. var gamepad = this.inputs.attached["gamepad"];
  77366. if (gamepad)
  77367. return gamepad.gamepadMoveSensibility;
  77368. return 0;
  77369. },
  77370. set: function (value) {
  77371. var gamepad = this.inputs.attached["gamepad"];
  77372. if (gamepad)
  77373. gamepad.gamepadMoveSensibility = value;
  77374. },
  77375. enumerable: true,
  77376. configurable: true
  77377. });
  77378. UniversalCamera.prototype.getClassName = function () {
  77379. return "UniversalCamera";
  77380. };
  77381. return UniversalCamera;
  77382. }(BABYLON.TouchCamera));
  77383. BABYLON.UniversalCamera = UniversalCamera;
  77384. })(BABYLON || (BABYLON = {}));
  77385. //# sourceMappingURL=babylon.universalCamera.js.map
  77386. var BABYLON;
  77387. (function (BABYLON) {
  77388. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  77389. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  77390. });
  77391. // We're mainly based on the logic defined into the FreeCamera code
  77392. var GamepadCamera = /** @class */ (function (_super) {
  77393. __extends(GamepadCamera, _super);
  77394. //-- end properties for backward compatibility for inputs
  77395. function GamepadCamera(name, position, scene) {
  77396. return _super.call(this, name, position, scene) || this;
  77397. }
  77398. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  77399. //-- Begin properties for backward compatibility for inputs
  77400. get: function () {
  77401. var gamepad = this.inputs.attached["gamepad"];
  77402. if (gamepad)
  77403. return gamepad.gamepadAngularSensibility;
  77404. return 0;
  77405. },
  77406. set: function (value) {
  77407. var gamepad = this.inputs.attached["gamepad"];
  77408. if (gamepad)
  77409. gamepad.gamepadAngularSensibility = value;
  77410. },
  77411. enumerable: true,
  77412. configurable: true
  77413. });
  77414. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  77415. get: function () {
  77416. var gamepad = this.inputs.attached["gamepad"];
  77417. if (gamepad)
  77418. return gamepad.gamepadMoveSensibility;
  77419. return 0;
  77420. },
  77421. set: function (value) {
  77422. var gamepad = this.inputs.attached["gamepad"];
  77423. if (gamepad)
  77424. gamepad.gamepadMoveSensibility = value;
  77425. },
  77426. enumerable: true,
  77427. configurable: true
  77428. });
  77429. GamepadCamera.prototype.getClassName = function () {
  77430. return "GamepadCamera";
  77431. };
  77432. return GamepadCamera;
  77433. }(BABYLON.UniversalCamera));
  77434. BABYLON.GamepadCamera = GamepadCamera;
  77435. })(BABYLON || (BABYLON = {}));
  77436. //# sourceMappingURL=babylon.gamepadCamera.js.map
  77437. var BABYLON;
  77438. (function (BABYLON) {
  77439. var PostProcessRenderPipelineManager = /** @class */ (function () {
  77440. function PostProcessRenderPipelineManager() {
  77441. this._renderPipelines = {};
  77442. }
  77443. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  77444. this._renderPipelines[renderPipeline._name] = renderPipeline;
  77445. };
  77446. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  77447. if (unique === void 0) { unique = false; }
  77448. var renderPipeline = this._renderPipelines[renderPipelineName];
  77449. if (!renderPipeline) {
  77450. return;
  77451. }
  77452. renderPipeline._attachCameras(cameras, unique);
  77453. };
  77454. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  77455. var renderPipeline = this._renderPipelines[renderPipelineName];
  77456. if (!renderPipeline) {
  77457. return;
  77458. }
  77459. renderPipeline._detachCameras(cameras);
  77460. };
  77461. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77462. var renderPipeline = this._renderPipelines[renderPipelineName];
  77463. if (!renderPipeline) {
  77464. return;
  77465. }
  77466. renderPipeline._enableEffect(renderEffectName, cameras);
  77467. };
  77468. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77469. var renderPipeline = this._renderPipelines[renderPipelineName];
  77470. if (!renderPipeline) {
  77471. return;
  77472. }
  77473. renderPipeline._disableEffect(renderEffectName, cameras);
  77474. };
  77475. PostProcessRenderPipelineManager.prototype.update = function () {
  77476. for (var renderPipelineName in this._renderPipelines) {
  77477. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77478. var pipeline = this._renderPipelines[renderPipelineName];
  77479. if (!pipeline.isSupported) {
  77480. pipeline.dispose();
  77481. delete this._renderPipelines[renderPipelineName];
  77482. }
  77483. else {
  77484. pipeline._update();
  77485. }
  77486. }
  77487. }
  77488. };
  77489. /** @hidden */
  77490. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  77491. for (var renderPipelineName in this._renderPipelines) {
  77492. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77493. var pipeline = this._renderPipelines[renderPipelineName];
  77494. pipeline._rebuild();
  77495. }
  77496. }
  77497. };
  77498. PostProcessRenderPipelineManager.prototype.dispose = function () {
  77499. for (var renderPipelineName in this._renderPipelines) {
  77500. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77501. var pipeline = this._renderPipelines[renderPipelineName];
  77502. pipeline.dispose();
  77503. }
  77504. }
  77505. };
  77506. return PostProcessRenderPipelineManager;
  77507. }());
  77508. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  77509. })(BABYLON || (BABYLON = {}));
  77510. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  77511. var BABYLON;
  77512. (function (BABYLON) {
  77513. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  77514. get: function () {
  77515. if (!this._postProcessRenderPipelineManager) {
  77516. // Register the G Buffer component to the scene.
  77517. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  77518. if (!component) {
  77519. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  77520. this._addComponent(component);
  77521. }
  77522. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  77523. }
  77524. return this._postProcessRenderPipelineManager;
  77525. },
  77526. enumerable: true,
  77527. configurable: true
  77528. });
  77529. /**
  77530. * Defines the Render Pipeline scene component responsible to rendering pipelines
  77531. */
  77532. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  77533. /**
  77534. * Creates a new instance of the component for the given scene
  77535. * @param scene Defines the scene to register the component in
  77536. */
  77537. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  77538. /**
  77539. * The component name helpfull to identify the component in the list of scene components.
  77540. */
  77541. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  77542. this.scene = scene;
  77543. }
  77544. /**
  77545. * Registers the component in a given scene
  77546. */
  77547. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  77548. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  77549. };
  77550. /**
  77551. * Rebuilds the elements related to this component in case of
  77552. * context lost for instance.
  77553. */
  77554. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  77555. if (this.scene._postProcessRenderPipelineManager) {
  77556. this.scene._postProcessRenderPipelineManager._rebuild();
  77557. }
  77558. };
  77559. /**
  77560. * Disposes the component and the associated ressources
  77561. */
  77562. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  77563. if (this.scene._postProcessRenderPipelineManager) {
  77564. this.scene._postProcessRenderPipelineManager.dispose();
  77565. }
  77566. };
  77567. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77568. if (this.scene._postProcessRenderPipelineManager) {
  77569. this.scene._postProcessRenderPipelineManager.update();
  77570. }
  77571. };
  77572. return PostProcessRenderPipelineManagerSceneComponent;
  77573. }());
  77574. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  77575. })(BABYLON || (BABYLON = {}));
  77576. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  77577. var BABYLON;
  77578. (function (BABYLON) {
  77579. /**
  77580. * This represents a set of one or more post processes in Babylon.
  77581. * A post process can be used to apply a shader to a texture after it is rendered.
  77582. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  77583. */
  77584. var PostProcessRenderEffect = /** @class */ (function () {
  77585. /**
  77586. * Instantiates a post process render effect.
  77587. * A post process can be used to apply a shader to a texture after it is rendered.
  77588. * @param engine The engine the effect is tied to
  77589. * @param name The name of the effect
  77590. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  77591. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  77592. */
  77593. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  77594. this._name = name;
  77595. this._singleInstance = singleInstance || true;
  77596. this._getPostProcesses = getPostProcesses;
  77597. this._cameras = {};
  77598. this._indicesForCamera = {};
  77599. this._postProcesses = {};
  77600. }
  77601. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  77602. /**
  77603. * Checks if all the post processes in the effect are supported.
  77604. */
  77605. get: function () {
  77606. for (var index in this._postProcesses) {
  77607. if (this._postProcesses.hasOwnProperty(index)) {
  77608. var pps = this._postProcesses[index];
  77609. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  77610. if (!pps[ppIndex].isSupported) {
  77611. return false;
  77612. }
  77613. }
  77614. }
  77615. }
  77616. return true;
  77617. },
  77618. enumerable: true,
  77619. configurable: true
  77620. });
  77621. /**
  77622. * Updates the current state of the effect
  77623. * @hidden
  77624. */
  77625. PostProcessRenderEffect.prototype._update = function () {
  77626. };
  77627. /**
  77628. * Attaches the effect on cameras
  77629. * @param cameras The camera to attach to.
  77630. * @hidden
  77631. */
  77632. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  77633. var _this = this;
  77634. var cameraKey;
  77635. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77636. if (!cams) {
  77637. return;
  77638. }
  77639. for (var i = 0; i < cams.length; i++) {
  77640. var camera = cams[i];
  77641. var cameraName = camera.name;
  77642. if (this._singleInstance) {
  77643. cameraKey = 0;
  77644. }
  77645. else {
  77646. cameraKey = cameraName;
  77647. }
  77648. if (!this._postProcesses[cameraKey]) {
  77649. var postProcess = this._getPostProcesses();
  77650. if (postProcess) {
  77651. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  77652. }
  77653. }
  77654. if (!this._indicesForCamera[cameraName]) {
  77655. this._indicesForCamera[cameraName] = [];
  77656. }
  77657. this._postProcesses[cameraKey].forEach(function (postProcess) {
  77658. var index = camera.attachPostProcess(postProcess);
  77659. _this._indicesForCamera[cameraName].push(index);
  77660. });
  77661. if (!this._cameras[cameraName]) {
  77662. this._cameras[cameraName] = camera;
  77663. }
  77664. }
  77665. };
  77666. /**
  77667. * Detatches the effect on cameras
  77668. * @param cameras The camera to detatch from.
  77669. * @hidden
  77670. */
  77671. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  77672. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77673. if (!cams) {
  77674. return;
  77675. }
  77676. for (var i = 0; i < cams.length; i++) {
  77677. var camera = cams[i];
  77678. var cameraName = camera.name;
  77679. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77680. camera.detachPostProcess(postProcess);
  77681. });
  77682. if (this._cameras[cameraName]) {
  77683. //this._indicesForCamera.splice(index, 1);
  77684. this._cameras[cameraName] = null;
  77685. }
  77686. }
  77687. };
  77688. /**
  77689. * Enables the effect on given cameras
  77690. * @param cameras The camera to enable.
  77691. * @hidden
  77692. */
  77693. PostProcessRenderEffect.prototype._enable = function (cameras) {
  77694. var _this = this;
  77695. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77696. if (!cams) {
  77697. return;
  77698. }
  77699. for (var i = 0; i < cams.length; i++) {
  77700. var camera = cams[i];
  77701. var cameraName = camera.name;
  77702. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  77703. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  77704. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77705. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  77706. });
  77707. }
  77708. }
  77709. }
  77710. };
  77711. /**
  77712. * Disables the effect on the given cameras
  77713. * @param cameras The camera to disable.
  77714. * @hidden
  77715. */
  77716. PostProcessRenderEffect.prototype._disable = function (cameras) {
  77717. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77718. if (!cams) {
  77719. return;
  77720. }
  77721. for (var i = 0; i < cams.length; i++) {
  77722. var camera = cams[i];
  77723. var cameraName = camera.name;
  77724. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77725. camera.detachPostProcess(postProcess);
  77726. });
  77727. }
  77728. };
  77729. /**
  77730. * Gets a list of the post processes contained in the effect.
  77731. * @param camera The camera to get the post processes on.
  77732. * @returns The list of the post processes in the effect.
  77733. */
  77734. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  77735. if (this._singleInstance) {
  77736. return this._postProcesses[0];
  77737. }
  77738. else {
  77739. if (!camera) {
  77740. return null;
  77741. }
  77742. return this._postProcesses[camera.name];
  77743. }
  77744. };
  77745. return PostProcessRenderEffect;
  77746. }());
  77747. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  77748. })(BABYLON || (BABYLON = {}));
  77749. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  77750. var BABYLON;
  77751. (function (BABYLON) {
  77752. var PostProcessRenderPipeline = /** @class */ (function () {
  77753. function PostProcessRenderPipeline(engine, name) {
  77754. this.engine = engine;
  77755. this._name = name;
  77756. this._renderEffects = {};
  77757. this._renderEffectsForIsolatedPass = new Array();
  77758. this._cameras = [];
  77759. }
  77760. PostProcessRenderPipeline.prototype.getClassName = function () {
  77761. return "PostProcessRenderPipeline";
  77762. };
  77763. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  77764. get: function () {
  77765. for (var renderEffectName in this._renderEffects) {
  77766. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77767. if (!this._renderEffects[renderEffectName].isSupported) {
  77768. return false;
  77769. }
  77770. }
  77771. }
  77772. return true;
  77773. },
  77774. enumerable: true,
  77775. configurable: true
  77776. });
  77777. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  77778. this._renderEffects[renderEffect._name] = renderEffect;
  77779. };
  77780. // private
  77781. /** @hidden */
  77782. PostProcessRenderPipeline.prototype._rebuild = function () {
  77783. };
  77784. /** @hidden */
  77785. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  77786. var renderEffects = this._renderEffects[renderEffectName];
  77787. if (!renderEffects) {
  77788. return;
  77789. }
  77790. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77791. };
  77792. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  77793. var renderEffects = this._renderEffects[renderEffectName];
  77794. if (!renderEffects) {
  77795. return;
  77796. }
  77797. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77798. };
  77799. /** @hidden */
  77800. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  77801. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77802. if (!cams) {
  77803. return;
  77804. }
  77805. var indicesToDelete = [];
  77806. var i;
  77807. for (i = 0; i < cams.length; i++) {
  77808. var camera = cams[i];
  77809. var cameraName = camera.name;
  77810. if (this._cameras.indexOf(camera) === -1) {
  77811. this._cameras[cameraName] = camera;
  77812. }
  77813. else if (unique) {
  77814. indicesToDelete.push(i);
  77815. }
  77816. }
  77817. for (i = 0; i < indicesToDelete.length; i++) {
  77818. cameras.splice(indicesToDelete[i], 1);
  77819. }
  77820. for (var renderEffectName in this._renderEffects) {
  77821. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77822. this._renderEffects[renderEffectName]._attachCameras(cams);
  77823. }
  77824. }
  77825. };
  77826. /** @hidden */
  77827. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  77828. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77829. if (!cams) {
  77830. return;
  77831. }
  77832. for (var renderEffectName in this._renderEffects) {
  77833. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77834. this._renderEffects[renderEffectName]._detachCameras(cams);
  77835. }
  77836. }
  77837. for (var i = 0; i < cams.length; i++) {
  77838. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  77839. }
  77840. };
  77841. /** @hidden */
  77842. PostProcessRenderPipeline.prototype._update = function () {
  77843. for (var renderEffectName in this._renderEffects) {
  77844. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77845. this._renderEffects[renderEffectName]._update();
  77846. }
  77847. }
  77848. for (var i = 0; i < this._cameras.length; i++) {
  77849. var cameraName = this._cameras[i].name;
  77850. if (this._renderEffectsForIsolatedPass[cameraName]) {
  77851. this._renderEffectsForIsolatedPass[cameraName]._update();
  77852. }
  77853. }
  77854. };
  77855. /** @hidden */
  77856. PostProcessRenderPipeline.prototype._reset = function () {
  77857. this._renderEffects = {};
  77858. this._renderEffectsForIsolatedPass = new Array();
  77859. };
  77860. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  77861. // 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)
  77862. var effectKeys = Object.keys(this._renderEffects);
  77863. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  77864. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  77865. if (postProcesses) {
  77866. postProcesses[0].samples = sampleCount;
  77867. return true;
  77868. }
  77869. }
  77870. return false;
  77871. };
  77872. PostProcessRenderPipeline.prototype.dispose = function () {
  77873. // Must be implemented by children
  77874. };
  77875. __decorate([
  77876. BABYLON.serialize()
  77877. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  77878. return PostProcessRenderPipeline;
  77879. }());
  77880. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  77881. })(BABYLON || (BABYLON = {}));
  77882. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  77883. var BABYLON;
  77884. (function (BABYLON) {
  77885. /**
  77886. * This represents a depth renderer in Babylon.
  77887. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  77888. */
  77889. var DepthRenderer = /** @class */ (function () {
  77890. /**
  77891. * Instantiates a depth renderer
  77892. * @param scene The scene the renderer belongs to
  77893. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  77894. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  77895. */
  77896. function DepthRenderer(scene, type, camera) {
  77897. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  77898. if (camera === void 0) { camera = null; }
  77899. var _this = this;
  77900. /**
  77901. * Specifiess that the depth renderer will only be used within
  77902. * the camera it is created for.
  77903. * This can help forcing its rendering during the camera processing.
  77904. */
  77905. this.useOnlyInActiveCamera = false;
  77906. this._scene = scene;
  77907. // Register the G Buffer component to the scene.
  77908. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  77909. if (!component) {
  77910. component = new BABYLON.DepthRendererSceneComponent(scene);
  77911. scene._addComponent(component);
  77912. }
  77913. this._camera = camera;
  77914. var engine = scene.getEngine();
  77915. // Render target
  77916. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  77917. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77918. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77919. this._depthMap.refreshRate = 1;
  77920. this._depthMap.renderParticles = false;
  77921. this._depthMap.renderList = null;
  77922. // Camera to get depth map from to support multiple concurrent cameras
  77923. this._depthMap.activeCamera = this._camera;
  77924. this._depthMap.ignoreCameraViewport = true;
  77925. this._depthMap.useCameraPostProcesses = false;
  77926. // set default depth value to 1.0 (far away)
  77927. this._depthMap.onClearObservable.add(function (engine) {
  77928. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  77929. });
  77930. // Custom render function
  77931. var renderSubMesh = function (subMesh) {
  77932. var mesh = subMesh.getRenderingMesh();
  77933. var scene = _this._scene;
  77934. var engine = scene.getEngine();
  77935. var material = subMesh.getMaterial();
  77936. if (!material) {
  77937. return;
  77938. }
  77939. // Culling and reverse (right handed system)
  77940. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77941. // Managing instances
  77942. var batch = mesh._getInstancesRenderList(subMesh._id);
  77943. if (batch.mustReturn) {
  77944. return;
  77945. }
  77946. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77947. var camera = _this._camera || scene.activeCamera;
  77948. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  77949. engine.enableEffect(_this._effect);
  77950. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77951. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77952. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  77953. // Alpha test
  77954. if (material && material.needAlphaTesting()) {
  77955. var alphaTexture = material.getAlphaTestTexture();
  77956. if (alphaTexture) {
  77957. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77958. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77959. }
  77960. }
  77961. // Bones
  77962. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77963. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77964. }
  77965. // Draw
  77966. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77967. }
  77968. };
  77969. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77970. var index;
  77971. if (depthOnlySubMeshes.length) {
  77972. engine.setColorWrite(false);
  77973. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77974. renderSubMesh(depthOnlySubMeshes.data[index]);
  77975. }
  77976. engine.setColorWrite(true);
  77977. }
  77978. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77979. renderSubMesh(opaqueSubMeshes.data[index]);
  77980. }
  77981. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77982. renderSubMesh(alphaTestSubMeshes.data[index]);
  77983. }
  77984. };
  77985. }
  77986. /**
  77987. * Creates the depth rendering effect and checks if the effect is ready.
  77988. * @param subMesh The submesh to be used to render the depth map of
  77989. * @param useInstances If multiple world instances should be used
  77990. * @returns if the depth renderer is ready to render the depth map
  77991. */
  77992. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  77993. var material = subMesh.getMaterial();
  77994. if (material.disableDepthWrite) {
  77995. return false;
  77996. }
  77997. var defines = [];
  77998. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77999. var mesh = subMesh.getMesh();
  78000. // Alpha test
  78001. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  78002. defines.push("#define ALPHATEST");
  78003. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78004. attribs.push(BABYLON.VertexBuffer.UVKind);
  78005. defines.push("#define UV1");
  78006. }
  78007. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78008. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78009. defines.push("#define UV2");
  78010. }
  78011. }
  78012. // Bones
  78013. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78014. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78015. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78016. if (mesh.numBoneInfluencers > 4) {
  78017. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78018. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78019. }
  78020. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78021. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78022. }
  78023. else {
  78024. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78025. }
  78026. // Instances
  78027. if (useInstances) {
  78028. defines.push("#define INSTANCES");
  78029. attribs.push("world0");
  78030. attribs.push("world1");
  78031. attribs.push("world2");
  78032. attribs.push("world3");
  78033. }
  78034. // Get correct effect
  78035. var join = defines.join("\n");
  78036. if (this._cachedDefines !== join) {
  78037. this._cachedDefines = join;
  78038. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  78039. }
  78040. return this._effect.isReady();
  78041. };
  78042. /**
  78043. * Gets the texture which the depth map will be written to.
  78044. * @returns The depth map texture
  78045. */
  78046. DepthRenderer.prototype.getDepthMap = function () {
  78047. return this._depthMap;
  78048. };
  78049. /**
  78050. * Disposes of the depth renderer.
  78051. */
  78052. DepthRenderer.prototype.dispose = function () {
  78053. this._depthMap.dispose();
  78054. };
  78055. return DepthRenderer;
  78056. }());
  78057. BABYLON.DepthRenderer = DepthRenderer;
  78058. })(BABYLON || (BABYLON = {}));
  78059. //# sourceMappingURL=babylon.depthRenderer.js.map
  78060. var BABYLON;
  78061. (function (BABYLON) {
  78062. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  78063. camera = camera || this.activeCamera;
  78064. if (!camera) {
  78065. throw "No camera available to enable depth renderer";
  78066. }
  78067. if (!this._depthRenderer) {
  78068. this._depthRenderer = {};
  78069. }
  78070. if (!this._depthRenderer[camera.id]) {
  78071. var textureType = 0;
  78072. if (this.getEngine().getCaps().textureHalfFloatRender) {
  78073. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78074. }
  78075. else if (this.getEngine().getCaps().textureFloatRender) {
  78076. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78077. }
  78078. else {
  78079. throw "Depth renderer does not support int texture type";
  78080. }
  78081. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  78082. }
  78083. return this._depthRenderer[camera.id];
  78084. };
  78085. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  78086. camera = camera || this.activeCamera;
  78087. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  78088. return;
  78089. }
  78090. this._depthRenderer[camera.id].dispose();
  78091. delete this._depthRenderer[camera.id];
  78092. };
  78093. /**
  78094. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  78095. * in several rendering techniques.
  78096. */
  78097. var DepthRendererSceneComponent = /** @class */ (function () {
  78098. /**
  78099. * Creates a new instance of the component for the given scene
  78100. * @param scene Defines the scene to register the component in
  78101. */
  78102. function DepthRendererSceneComponent(scene) {
  78103. /**
  78104. * The component name helpfull to identify the component in the list of scene components.
  78105. */
  78106. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  78107. this.scene = scene;
  78108. }
  78109. /**
  78110. * Registers the component in a given scene
  78111. */
  78112. DepthRendererSceneComponent.prototype.register = function () {
  78113. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  78114. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  78115. };
  78116. /**
  78117. * Rebuilds the elements related to this component in case of
  78118. * context lost for instance.
  78119. */
  78120. DepthRendererSceneComponent.prototype.rebuild = function () {
  78121. // Nothing to do for this component
  78122. };
  78123. /**
  78124. * Disposes the component and the associated ressources
  78125. */
  78126. DepthRendererSceneComponent.prototype.dispose = function () {
  78127. for (var key in this.scene._depthRenderer) {
  78128. this.scene._depthRenderer[key].dispose();
  78129. }
  78130. };
  78131. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78132. if (this.scene._depthRenderer) {
  78133. for (var key in this.scene._depthRenderer) {
  78134. var depthRenderer = this.scene._depthRenderer[key];
  78135. if (!depthRenderer.useOnlyInActiveCamera) {
  78136. renderTargets.push(depthRenderer.getDepthMap());
  78137. }
  78138. }
  78139. }
  78140. };
  78141. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  78142. if (this.scene._depthRenderer) {
  78143. for (var key in this.scene._depthRenderer) {
  78144. var depthRenderer = this.scene._depthRenderer[key];
  78145. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  78146. renderTargets.push(depthRenderer.getDepthMap());
  78147. }
  78148. }
  78149. }
  78150. };
  78151. return DepthRendererSceneComponent;
  78152. }());
  78153. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  78154. })(BABYLON || (BABYLON = {}));
  78155. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  78156. var BABYLON;
  78157. (function (BABYLON) {
  78158. /**
  78159. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78160. */
  78161. var GeometryBufferRenderer = /** @class */ (function () {
  78162. /**
  78163. * Creates a new G Buffer for the scene
  78164. * @param scene The scene the buffer belongs to
  78165. * @param ratio How big is the buffer related to the main canvas.
  78166. */
  78167. function GeometryBufferRenderer(scene, ratio) {
  78168. if (ratio === void 0) { ratio = 1; }
  78169. this._enablePosition = false;
  78170. this._scene = scene;
  78171. this._ratio = ratio;
  78172. // Register the G Buffer component to the scene.
  78173. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  78174. if (!component) {
  78175. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  78176. scene._addComponent(component);
  78177. }
  78178. // Render target
  78179. this._createRenderTargets();
  78180. }
  78181. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78182. /**
  78183. * Set the render list (meshes to be rendered) used in the G buffer.
  78184. */
  78185. set: function (meshes) {
  78186. this._multiRenderTarget.renderList = meshes;
  78187. },
  78188. enumerable: true,
  78189. configurable: true
  78190. });
  78191. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78192. /**
  78193. * Gets wether or not G buffer are supported by the running hardware.
  78194. * This requires draw buffer supports
  78195. */
  78196. get: function () {
  78197. return this._multiRenderTarget.isSupported;
  78198. },
  78199. enumerable: true,
  78200. configurable: true
  78201. });
  78202. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78203. /**
  78204. * Gets wether or not position are enabled for the G buffer.
  78205. */
  78206. get: function () {
  78207. return this._enablePosition;
  78208. },
  78209. /**
  78210. * Sets wether or not position are enabled for the G buffer.
  78211. */
  78212. set: function (enable) {
  78213. this._enablePosition = enable;
  78214. this.dispose();
  78215. this._createRenderTargets();
  78216. },
  78217. enumerable: true,
  78218. configurable: true
  78219. });
  78220. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78221. /**
  78222. * Gets the scene associated with the buffer.
  78223. */
  78224. get: function () {
  78225. return this._scene;
  78226. },
  78227. enumerable: true,
  78228. configurable: true
  78229. });
  78230. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78231. /**
  78232. * Gets the ratio used by the buffer during its creation.
  78233. * How big is the buffer related to the main canvas.
  78234. */
  78235. get: function () {
  78236. return this._ratio;
  78237. },
  78238. enumerable: true,
  78239. configurable: true
  78240. });
  78241. /**
  78242. * Checks wether everything is ready to render a submesh to the G buffer.
  78243. * @param subMesh the submesh to check readiness for
  78244. * @param useInstances is the mesh drawn using instance or not
  78245. * @returns true if ready otherwise false
  78246. */
  78247. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78248. var material = subMesh.getMaterial();
  78249. if (material && material.disableDepthWrite) {
  78250. return false;
  78251. }
  78252. var defines = [];
  78253. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78254. var mesh = subMesh.getMesh();
  78255. // Alpha test
  78256. if (material && material.needAlphaTesting()) {
  78257. defines.push("#define ALPHATEST");
  78258. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78259. attribs.push(BABYLON.VertexBuffer.UVKind);
  78260. defines.push("#define UV1");
  78261. }
  78262. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78263. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78264. defines.push("#define UV2");
  78265. }
  78266. }
  78267. // Buffers
  78268. if (this._enablePosition) {
  78269. defines.push("#define POSITION");
  78270. }
  78271. // Bones
  78272. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78273. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78274. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78275. if (mesh.numBoneInfluencers > 4) {
  78276. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78277. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78278. }
  78279. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78280. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78281. }
  78282. else {
  78283. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78284. }
  78285. // Instances
  78286. if (useInstances) {
  78287. defines.push("#define INSTANCES");
  78288. attribs.push("world0");
  78289. attribs.push("world1");
  78290. attribs.push("world2");
  78291. attribs.push("world3");
  78292. }
  78293. // Get correct effect
  78294. var join = defines.join("\n");
  78295. if (this._cachedDefines !== join) {
  78296. this._cachedDefines = join;
  78297. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78298. }
  78299. return this._effect.isReady();
  78300. };
  78301. /**
  78302. * Gets the current underlying G Buffer.
  78303. * @returns the buffer
  78304. */
  78305. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78306. return this._multiRenderTarget;
  78307. };
  78308. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78309. /**
  78310. * Gets the number of samples used to render the buffer (anti aliasing).
  78311. */
  78312. get: function () {
  78313. return this._multiRenderTarget.samples;
  78314. },
  78315. /**
  78316. * Sets the number of samples used to render the buffer (anti aliasing).
  78317. */
  78318. set: function (value) {
  78319. this._multiRenderTarget.samples = value;
  78320. },
  78321. enumerable: true,
  78322. configurable: true
  78323. });
  78324. /**
  78325. * Disposes the renderer and frees up associated resources.
  78326. */
  78327. GeometryBufferRenderer.prototype.dispose = function () {
  78328. this.getGBuffer().dispose();
  78329. };
  78330. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78331. var _this = this;
  78332. var engine = this._scene.getEngine();
  78333. var count = this._enablePosition ? 3 : 2;
  78334. 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 });
  78335. if (!this.isSupported) {
  78336. return;
  78337. }
  78338. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78339. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78340. this._multiRenderTarget.refreshRate = 1;
  78341. this._multiRenderTarget.renderParticles = false;
  78342. this._multiRenderTarget.renderList = null;
  78343. // set default depth value to 1.0 (far away)
  78344. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78345. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78346. });
  78347. // Custom render function
  78348. var renderSubMesh = function (subMesh) {
  78349. var mesh = subMesh.getRenderingMesh();
  78350. var scene = _this._scene;
  78351. var engine = scene.getEngine();
  78352. var material = subMesh.getMaterial();
  78353. if (!material) {
  78354. return;
  78355. }
  78356. // Culling
  78357. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78358. // Managing instances
  78359. var batch = mesh._getInstancesRenderList(subMesh._id);
  78360. if (batch.mustReturn) {
  78361. return;
  78362. }
  78363. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78364. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78365. engine.enableEffect(_this._effect);
  78366. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78367. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78368. _this._effect.setMatrix("view", scene.getViewMatrix());
  78369. // Alpha test
  78370. if (material && material.needAlphaTesting()) {
  78371. var alphaTexture = material.getAlphaTestTexture();
  78372. if (alphaTexture) {
  78373. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78374. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78375. }
  78376. }
  78377. // Bones
  78378. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78379. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78380. }
  78381. // Draw
  78382. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78383. }
  78384. };
  78385. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78386. var index;
  78387. if (depthOnlySubMeshes.length) {
  78388. engine.setColorWrite(false);
  78389. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78390. renderSubMesh(depthOnlySubMeshes.data[index]);
  78391. }
  78392. engine.setColorWrite(true);
  78393. }
  78394. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78395. renderSubMesh(opaqueSubMeshes.data[index]);
  78396. }
  78397. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78398. renderSubMesh(alphaTestSubMeshes.data[index]);
  78399. }
  78400. };
  78401. };
  78402. return GeometryBufferRenderer;
  78403. }());
  78404. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78405. })(BABYLON || (BABYLON = {}));
  78406. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78407. var BABYLON;
  78408. (function (BABYLON) {
  78409. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  78410. get: function () {
  78411. this._geometryBufferRenderer;
  78412. },
  78413. set: function (value) {
  78414. if (value && value.isSupported) {
  78415. this._geometryBufferRenderer = value;
  78416. }
  78417. ;
  78418. },
  78419. enumerable: true,
  78420. configurable: true
  78421. });
  78422. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  78423. if (ratio === void 0) { ratio = 1; }
  78424. if (this._geometryBufferRenderer) {
  78425. return this._geometryBufferRenderer;
  78426. }
  78427. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  78428. if (!this._geometryBufferRenderer.isSupported) {
  78429. this._geometryBufferRenderer = null;
  78430. }
  78431. return this._geometryBufferRenderer;
  78432. };
  78433. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  78434. if (!this._geometryBufferRenderer) {
  78435. return;
  78436. }
  78437. this._geometryBufferRenderer.dispose();
  78438. this._geometryBufferRenderer = null;
  78439. };
  78440. /**
  78441. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  78442. * in several rendering techniques.
  78443. */
  78444. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  78445. /**
  78446. * Creates a new instance of the component for the given scene
  78447. * @param scene Defines the scene to register the component in
  78448. */
  78449. function GeometryBufferRendererSceneComponent(scene) {
  78450. /**
  78451. * The component name helpful to identify the component in the list of scene components.
  78452. */
  78453. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  78454. this.scene = scene;
  78455. }
  78456. /**
  78457. * Registers the component in a given scene
  78458. */
  78459. GeometryBufferRendererSceneComponent.prototype.register = function () {
  78460. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  78461. };
  78462. /**
  78463. * Rebuilds the elements related to this component in case of
  78464. * context lost for instance.
  78465. */
  78466. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  78467. // Nothing to do for this component
  78468. };
  78469. /**
  78470. * Disposes the component and the associated ressources
  78471. */
  78472. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  78473. // Nothing to do for this component
  78474. };
  78475. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78476. if (this.scene._geometryBufferRenderer) {
  78477. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  78478. }
  78479. };
  78480. return GeometryBufferRendererSceneComponent;
  78481. }());
  78482. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  78483. })(BABYLON || (BABYLON = {}));
  78484. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  78485. var BABYLON;
  78486. (function (BABYLON) {
  78487. var SSAORenderingPipeline = /** @class */ (function (_super) {
  78488. __extends(SSAORenderingPipeline, _super);
  78489. /**
  78490. * @constructor
  78491. * @param {string} name - The rendering pipeline name
  78492. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78493. * @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 }
  78494. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78495. */
  78496. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  78497. var _this = _super.call(this, scene.getEngine(), name) || this;
  78498. // Members
  78499. /**
  78500. * The PassPostProcess id in the pipeline that contains the original scene color
  78501. */
  78502. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78503. /**
  78504. * The SSAO PostProcess id in the pipeline
  78505. */
  78506. _this.SSAORenderEffect = "SSAORenderEffect";
  78507. /**
  78508. * The horizontal blur PostProcess id in the pipeline
  78509. */
  78510. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78511. /**
  78512. * The vertical blur PostProcess id in the pipeline
  78513. */
  78514. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78515. /**
  78516. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78517. */
  78518. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78519. /**
  78520. * The output strength of the SSAO post-process. Default value is 1.0.
  78521. */
  78522. _this.totalStrength = 1.0;
  78523. /**
  78524. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  78525. */
  78526. _this.radius = 0.0001;
  78527. /**
  78528. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  78529. * Must not be equal to fallOff and superior to fallOff.
  78530. * Default value is 0.975
  78531. */
  78532. _this.area = 0.0075;
  78533. /**
  78534. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  78535. * Must not be equal to area and inferior to area.
  78536. * Default value is 0.0
  78537. */
  78538. _this.fallOff = 0.000001;
  78539. /**
  78540. * The base color of the SSAO post-process
  78541. * The final result is "base + ssao" between [0, 1]
  78542. */
  78543. _this.base = 0.5;
  78544. _this._firstUpdate = true;
  78545. _this._scene = scene;
  78546. // Set up assets
  78547. _this._createRandomTexture();
  78548. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78549. var ssaoRatio = ratio.ssaoRatio || ratio;
  78550. var combineRatio = ratio.combineRatio || ratio;
  78551. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78552. _this._createSSAOPostProcess(ssaoRatio);
  78553. _this._createBlurPostProcess(ssaoRatio);
  78554. _this._createSSAOCombinePostProcess(combineRatio);
  78555. // Set up pipeline
  78556. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78557. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78558. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78559. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78560. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78561. // Finish
  78562. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78563. if (cameras)
  78564. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78565. return _this;
  78566. }
  78567. // Public Methods
  78568. /**
  78569. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78570. */
  78571. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78572. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78573. for (var i = 0; i < this._scene.cameras.length; i++) {
  78574. var camera = this._scene.cameras[i];
  78575. this._originalColorPostProcess.dispose(camera);
  78576. this._ssaoPostProcess.dispose(camera);
  78577. this._blurHPostProcess.dispose(camera);
  78578. this._blurVPostProcess.dispose(camera);
  78579. this._ssaoCombinePostProcess.dispose(camera);
  78580. }
  78581. this._randomTexture.dispose();
  78582. if (disableDepthRender)
  78583. this._scene.disableDepthRenderer();
  78584. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78585. _super.prototype.dispose.call(this);
  78586. };
  78587. // Private Methods
  78588. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  78589. var _this = this;
  78590. var size = 16;
  78591. 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);
  78592. 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);
  78593. this._blurHPostProcess.onActivateObservable.add(function () {
  78594. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  78595. _this._blurHPostProcess.kernel = size * dw;
  78596. });
  78597. this._blurVPostProcess.onActivateObservable.add(function () {
  78598. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  78599. _this._blurVPostProcess.kernel = size * dw;
  78600. });
  78601. };
  78602. /** @hidden */
  78603. SSAORenderingPipeline.prototype._rebuild = function () {
  78604. this._firstUpdate = true;
  78605. _super.prototype._rebuild.call(this);
  78606. };
  78607. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78608. var _this = this;
  78609. var numSamples = 16;
  78610. var sampleSphere = [
  78611. 0.5381, 0.1856, -0.4319,
  78612. 0.1379, 0.2486, 0.4430,
  78613. 0.3371, 0.5679, -0.0057,
  78614. -0.6999, -0.0451, -0.0019,
  78615. 0.0689, -0.1598, -0.8547,
  78616. 0.0560, 0.0069, -0.1843,
  78617. -0.0146, 0.1402, 0.0762,
  78618. 0.0100, -0.1924, -0.0344,
  78619. -0.3577, -0.5301, -0.4358,
  78620. -0.3169, 0.1063, 0.0158,
  78621. 0.0103, -0.5869, 0.0046,
  78622. -0.0897, -0.4940, 0.3287,
  78623. 0.7119, -0.0154, -0.0918,
  78624. -0.0533, 0.0596, -0.5411,
  78625. 0.0352, -0.0631, 0.5460,
  78626. -0.4776, 0.2847, -0.0271
  78627. ];
  78628. var samplesFactor = 1.0 / numSamples;
  78629. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  78630. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78631. "area", "fallOff", "base", "range", "viewport"
  78632. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78633. this._ssaoPostProcess.onApply = function (effect) {
  78634. if (_this._firstUpdate) {
  78635. effect.setArray3("sampleSphere", sampleSphere);
  78636. effect.setFloat("samplesFactor", samplesFactor);
  78637. effect.setFloat("randTextureTiles", 4.0);
  78638. }
  78639. effect.setFloat("totalStrength", _this.totalStrength);
  78640. effect.setFloat("radius", _this.radius);
  78641. effect.setFloat("area", _this.area);
  78642. effect.setFloat("fallOff", _this.fallOff);
  78643. effect.setFloat("base", _this.base);
  78644. effect.setTexture("textureSampler", _this._depthTexture);
  78645. effect.setTexture("randomSampler", _this._randomTexture);
  78646. };
  78647. };
  78648. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78649. var _this = this;
  78650. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78651. this._ssaoCombinePostProcess.onApply = function (effect) {
  78652. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  78653. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78654. };
  78655. };
  78656. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  78657. var size = 512;
  78658. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78659. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78660. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78661. var context = this._randomTexture.getContext();
  78662. var rand = function (min, max) {
  78663. return Math.random() * (max - min) + min;
  78664. };
  78665. var randVector = BABYLON.Vector3.Zero();
  78666. for (var x = 0; x < size; x++) {
  78667. for (var y = 0; y < size; y++) {
  78668. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  78669. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  78670. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  78671. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78672. context.fillRect(x, y, 1, 1);
  78673. }
  78674. }
  78675. this._randomTexture.update(false);
  78676. };
  78677. __decorate([
  78678. BABYLON.serialize()
  78679. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  78680. __decorate([
  78681. BABYLON.serialize()
  78682. ], SSAORenderingPipeline.prototype, "radius", void 0);
  78683. __decorate([
  78684. BABYLON.serialize()
  78685. ], SSAORenderingPipeline.prototype, "area", void 0);
  78686. __decorate([
  78687. BABYLON.serialize()
  78688. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  78689. __decorate([
  78690. BABYLON.serialize()
  78691. ], SSAORenderingPipeline.prototype, "base", void 0);
  78692. return SSAORenderingPipeline;
  78693. }(BABYLON.PostProcessRenderPipeline));
  78694. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  78695. })(BABYLON || (BABYLON = {}));
  78696. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  78697. var BABYLON;
  78698. (function (BABYLON) {
  78699. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  78700. __extends(SSAO2RenderingPipeline, _super);
  78701. /**
  78702. * @constructor
  78703. * @param {string} name - The rendering pipeline name
  78704. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78705. * @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 }
  78706. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78707. */
  78708. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  78709. var _this = _super.call(this, scene.getEngine(), name) || this;
  78710. // Members
  78711. /**
  78712. * The PassPostProcess id in the pipeline that contains the original scene color
  78713. */
  78714. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78715. /**
  78716. * The SSAO PostProcess id in the pipeline
  78717. */
  78718. _this.SSAORenderEffect = "SSAORenderEffect";
  78719. /**
  78720. * The horizontal blur PostProcess id in the pipeline
  78721. */
  78722. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78723. /**
  78724. * The vertical blur PostProcess id in the pipeline
  78725. */
  78726. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78727. /**
  78728. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78729. */
  78730. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78731. /**
  78732. * The output strength of the SSAO post-process. Default value is 1.0.
  78733. */
  78734. _this.totalStrength = 1.0;
  78735. /**
  78736. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  78737. */
  78738. _this.maxZ = 100.0;
  78739. /**
  78740. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  78741. */
  78742. _this.minZAspect = 0.2;
  78743. _this._samples = 8;
  78744. _this._textureSamples = 1;
  78745. /**
  78746. * Are we using bilateral blur ?
  78747. */
  78748. _this._expensiveBlur = true;
  78749. /**
  78750. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  78751. */
  78752. _this.radius = 2.0;
  78753. /**
  78754. * The base color of the SSAO post-process
  78755. * The final result is "base + ssao" between [0, 1]
  78756. */
  78757. _this.base = 0;
  78758. _this._firstUpdate = true;
  78759. _this._bits = new Uint32Array(1);
  78760. _this._scene = scene;
  78761. _this._ratio = ratio;
  78762. if (!_this.isSupported) {
  78763. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  78764. return _this;
  78765. }
  78766. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  78767. var blurRatio = _this._ratio.blurRatio || ratio;
  78768. // Set up assets
  78769. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  78770. _this._createRandomTexture();
  78771. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  78772. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  78773. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78774. _this._originalColorPostProcess.samples = _this.textureSamples;
  78775. _this._createSSAOPostProcess(1.0);
  78776. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  78777. _this._createSSAOCombinePostProcess(blurRatio);
  78778. // Set up pipeline
  78779. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78780. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78781. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78782. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78783. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78784. // Finish
  78785. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78786. if (cameras)
  78787. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78788. return _this;
  78789. }
  78790. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  78791. get: function () {
  78792. return this._samples;
  78793. },
  78794. /**
  78795. * Number of samples used for the SSAO calculations. Default value is 8
  78796. */
  78797. set: function (n) {
  78798. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  78799. this._samples = n;
  78800. this._sampleSphere = this._generateHemisphere();
  78801. this._firstUpdate = true;
  78802. },
  78803. enumerable: true,
  78804. configurable: true
  78805. });
  78806. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  78807. get: function () {
  78808. return this._textureSamples;
  78809. },
  78810. /**
  78811. * Number of samples to use for antialiasing
  78812. */
  78813. set: function (n) {
  78814. this._textureSamples = n;
  78815. this._originalColorPostProcess.samples = n;
  78816. this._blurHPostProcess.samples = n;
  78817. this._blurVPostProcess.samples = n;
  78818. this._ssaoPostProcess.samples = n;
  78819. this._ssaoCombinePostProcess.samples = n;
  78820. },
  78821. enumerable: true,
  78822. configurable: true
  78823. });
  78824. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  78825. get: function () {
  78826. return this._expensiveBlur;
  78827. },
  78828. set: function (b) {
  78829. 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"]);
  78830. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  78831. this._expensiveBlur = b;
  78832. this._firstUpdate = true;
  78833. },
  78834. enumerable: true,
  78835. configurable: true
  78836. });
  78837. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  78838. /**
  78839. * Support test.
  78840. */
  78841. get: function () {
  78842. var engine = BABYLON.Engine.LastCreatedEngine;
  78843. if (!engine) {
  78844. return false;
  78845. }
  78846. return engine.getCaps().drawBuffersExtension;
  78847. },
  78848. enumerable: true,
  78849. configurable: true
  78850. });
  78851. // Public Methods
  78852. /**
  78853. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78854. */
  78855. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  78856. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  78857. for (var i = 0; i < this._scene.cameras.length; i++) {
  78858. var camera = this._scene.cameras[i];
  78859. this._originalColorPostProcess.dispose(camera);
  78860. this._ssaoPostProcess.dispose(camera);
  78861. this._blurHPostProcess.dispose(camera);
  78862. this._blurVPostProcess.dispose(camera);
  78863. this._ssaoCombinePostProcess.dispose(camera);
  78864. }
  78865. this._randomTexture.dispose();
  78866. if (disableGeometryBufferRenderer)
  78867. this._scene.disableGeometryBufferRenderer();
  78868. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78869. _super.prototype.dispose.call(this);
  78870. };
  78871. // Private Methods
  78872. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  78873. var _this = this;
  78874. this._samplerOffsets = [];
  78875. var expensive = this.expensiveBlur;
  78876. for (var i = -8; i < 8; i++) {
  78877. this._samplerOffsets.push(i * 2 + 0.5);
  78878. }
  78879. 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");
  78880. this._blurHPostProcess.onApply = function (effect) {
  78881. if (!_this._scene.activeCamera) {
  78882. return;
  78883. }
  78884. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  78885. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78886. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78887. effect.setFloat("radius", _this.radius);
  78888. effect.setTexture("depthSampler", _this._depthTexture);
  78889. if (_this._firstUpdate) {
  78890. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78891. }
  78892. };
  78893. 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");
  78894. this._blurVPostProcess.onApply = function (effect) {
  78895. if (!_this._scene.activeCamera) {
  78896. return;
  78897. }
  78898. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  78899. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78900. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78901. effect.setFloat("radius", _this.radius);
  78902. effect.setTexture("depthSampler", _this._depthTexture);
  78903. if (_this._firstUpdate) {
  78904. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78905. _this._firstUpdate = false;
  78906. }
  78907. };
  78908. this._blurHPostProcess.samples = this.textureSamples;
  78909. this._blurVPostProcess.samples = this.textureSamples;
  78910. };
  78911. /** @hidden */
  78912. SSAO2RenderingPipeline.prototype._rebuild = function () {
  78913. this._firstUpdate = true;
  78914. _super.prototype._rebuild.call(this);
  78915. };
  78916. //Van der Corput radical inverse
  78917. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  78918. this._bits[0] = i;
  78919. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  78920. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  78921. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  78922. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  78923. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  78924. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  78925. };
  78926. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  78927. return [i / n, this._radicalInverse_VdC(i)];
  78928. };
  78929. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  78930. var phi = v * 2.0 * Math.PI;
  78931. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  78932. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  78933. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  78934. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  78935. };
  78936. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  78937. var numSamples = this.samples;
  78938. var result = [];
  78939. var vector;
  78940. var i = 0;
  78941. while (i < numSamples) {
  78942. if (numSamples < 16) {
  78943. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  78944. }
  78945. else {
  78946. var rand = this._hammersley(i, numSamples);
  78947. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  78948. }
  78949. result.push(vector.x, vector.y, vector.z);
  78950. i++;
  78951. }
  78952. return result;
  78953. };
  78954. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78955. var _this = this;
  78956. var numSamples = this.samples;
  78957. this._sampleSphere = this._generateHemisphere();
  78958. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  78959. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78960. "base", "range", "projection", "near", "far", "texelSize",
  78961. "xViewport", "yViewport", "maxZ", "minZAspect"
  78962. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78963. this._ssaoPostProcess.onApply = function (effect) {
  78964. if (_this._firstUpdate) {
  78965. effect.setArray3("sampleSphere", _this._sampleSphere);
  78966. effect.setFloat("randTextureTiles", 32.0);
  78967. }
  78968. if (!_this._scene.activeCamera) {
  78969. return;
  78970. }
  78971. effect.setFloat("samplesFactor", 1 / _this.samples);
  78972. effect.setFloat("totalStrength", _this.totalStrength);
  78973. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  78974. effect.setFloat("radius", _this.radius);
  78975. effect.setFloat("maxZ", _this.maxZ);
  78976. effect.setFloat("minZAspect", _this.minZAspect);
  78977. effect.setFloat("base", _this.base);
  78978. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78979. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78980. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  78981. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  78982. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  78983. effect.setTexture("textureSampler", _this._depthTexture);
  78984. effect.setTexture("normalSampler", _this._normalTexture);
  78985. effect.setTexture("randomSampler", _this._randomTexture);
  78986. };
  78987. this._ssaoPostProcess.samples = this.textureSamples;
  78988. };
  78989. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78990. var _this = this;
  78991. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78992. this._ssaoCombinePostProcess.onApply = function (effect) {
  78993. var viewport = _this._scene.activeCamera.viewport;
  78994. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  78995. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78996. };
  78997. this._ssaoCombinePostProcess.samples = this.textureSamples;
  78998. };
  78999. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  79000. var size = 128;
  79001. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79002. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  79003. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  79004. var context = this._randomTexture.getContext();
  79005. var rand = function (min, max) {
  79006. return Math.random() * (max - min) + min;
  79007. };
  79008. var randVector = BABYLON.Vector3.Zero();
  79009. for (var x = 0; x < size; x++) {
  79010. for (var y = 0; y < size; y++) {
  79011. randVector.x = rand(0.0, 1.0);
  79012. randVector.y = rand(0.0, 1.0);
  79013. randVector.z = 0.0;
  79014. randVector.normalize();
  79015. randVector.scaleInPlace(255);
  79016. randVector.x = Math.floor(randVector.x);
  79017. randVector.y = Math.floor(randVector.y);
  79018. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  79019. context.fillRect(x, y, 1, 1);
  79020. }
  79021. }
  79022. this._randomTexture.update(false);
  79023. };
  79024. /**
  79025. * Serialize the rendering pipeline (Used when exporting)
  79026. * @returns the serialized object
  79027. */
  79028. SSAO2RenderingPipeline.prototype.serialize = function () {
  79029. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79030. serializationObject.customType = "SSAO2RenderingPipeline";
  79031. return serializationObject;
  79032. };
  79033. /**
  79034. * Parse the serialized pipeline
  79035. * @param source Source pipeline.
  79036. * @param scene The scene to load the pipeline to.
  79037. * @param rootUrl The URL of the serialized pipeline.
  79038. * @returns An instantiated pipeline from the serialized object.
  79039. */
  79040. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  79041. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79042. };
  79043. __decorate([
  79044. BABYLON.serialize()
  79045. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  79046. __decorate([
  79047. BABYLON.serialize()
  79048. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  79049. __decorate([
  79050. BABYLON.serialize()
  79051. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  79052. __decorate([
  79053. BABYLON.serialize("samples")
  79054. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  79055. __decorate([
  79056. BABYLON.serialize("textureSamples")
  79057. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  79058. __decorate([
  79059. BABYLON.serialize()
  79060. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  79061. __decorate([
  79062. BABYLON.serialize("expensiveBlur")
  79063. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  79064. __decorate([
  79065. BABYLON.serialize()
  79066. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  79067. __decorate([
  79068. BABYLON.serialize()
  79069. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  79070. return SSAO2RenderingPipeline;
  79071. }(BABYLON.PostProcessRenderPipeline));
  79072. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  79073. })(BABYLON || (BABYLON = {}));
  79074. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  79075. // BABYLON.JS Chromatic Aberration GLSL Shader
  79076. // Author: Olivier Guyot
  79077. // Separates very slightly R, G and B colors on the edges of the screen
  79078. // Inspired by Francois Tarlier & Martins Upitis
  79079. var BABYLON;
  79080. (function (BABYLON) {
  79081. var LensRenderingPipeline = /** @class */ (function (_super) {
  79082. __extends(LensRenderingPipeline, _super);
  79083. /**
  79084. * @constructor
  79085. *
  79086. * Effect parameters are as follow:
  79087. * {
  79088. * chromatic_aberration: number; // from 0 to x (1 for realism)
  79089. * edge_blur: number; // from 0 to x (1 for realism)
  79090. * distortion: number; // from 0 to x (1 for realism)
  79091. * grain_amount: number; // from 0 to 1
  79092. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  79093. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  79094. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  79095. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  79096. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  79097. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  79098. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  79099. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  79100. * }
  79101. * Note: if an effect parameter is unset, effect is disabled
  79102. *
  79103. * @param {string} name - The rendering pipeline name
  79104. * @param {object} parameters - An object containing all parameters (see above)
  79105. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79106. * @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)
  79107. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79108. */
  79109. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  79110. if (ratio === void 0) { ratio = 1.0; }
  79111. var _this = _super.call(this, scene.getEngine(), name) || this;
  79112. // Lens effects can be of the following:
  79113. // - chromatic aberration (slight shift of RGB colors)
  79114. // - blur on the edge of the lens
  79115. // - lens distortion
  79116. // - depth-of-field blur & highlights enhancing
  79117. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  79118. // - grain effect (noise or custom texture)
  79119. // Two additional texture samplers are needed:
  79120. // - depth map (for depth-of-field)
  79121. // - grain texture
  79122. /**
  79123. * The chromatic aberration PostProcess id in the pipeline
  79124. */
  79125. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  79126. /**
  79127. * The highlights enhancing PostProcess id in the pipeline
  79128. */
  79129. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  79130. /**
  79131. * The depth-of-field PostProcess id in the pipeline
  79132. */
  79133. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  79134. _this._scene = scene;
  79135. // Fetch texture samplers
  79136. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  79137. if (parameters.grain_texture) {
  79138. _this._grainTexture = parameters.grain_texture;
  79139. }
  79140. else {
  79141. _this._createGrainTexture();
  79142. }
  79143. // save parameters
  79144. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  79145. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  79146. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  79147. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  79148. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  79149. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  79150. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  79151. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  79152. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  79153. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  79154. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  79155. // Create effects
  79156. _this._createChromaticAberrationPostProcess(ratio);
  79157. _this._createHighlightsPostProcess(ratio);
  79158. _this._createDepthOfFieldPostProcess(ratio / 4);
  79159. // Set up pipeline
  79160. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  79161. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  79162. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  79163. if (_this._highlightsGain === -1) {
  79164. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  79165. }
  79166. // Finish
  79167. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79168. if (cameras) {
  79169. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  79170. }
  79171. return _this;
  79172. }
  79173. // public methods (self explanatory)
  79174. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  79175. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  79176. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  79177. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  79178. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  79179. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  79180. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  79181. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  79182. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  79183. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  79184. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  79185. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  79186. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  79187. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  79188. };
  79189. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  79190. this._highlightsPostProcess.updateEffect();
  79191. };
  79192. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  79193. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  79194. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  79195. this._highlightsGain = amount;
  79196. };
  79197. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  79198. if (this._highlightsGain === -1) {
  79199. this._highlightsGain = 1.0;
  79200. }
  79201. this._highlightsThreshold = amount;
  79202. };
  79203. LensRenderingPipeline.prototype.disableHighlights = function () {
  79204. this._highlightsGain = -1;
  79205. };
  79206. /**
  79207. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  79208. */
  79209. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  79210. if (disableDepthRender === void 0) { disableDepthRender = false; }
  79211. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  79212. this._chromaticAberrationPostProcess = null;
  79213. this._highlightsPostProcess = null;
  79214. this._depthOfFieldPostProcess = null;
  79215. this._grainTexture.dispose();
  79216. if (disableDepthRender)
  79217. this._scene.disableDepthRenderer();
  79218. };
  79219. // colors shifting and distortion
  79220. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  79221. var _this = this;
  79222. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  79223. [], // samplers
  79224. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79225. this._chromaticAberrationPostProcess.onApply = function (effect) {
  79226. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  79227. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79228. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79229. effect.setFloat('radialIntensity', 1);
  79230. effect.setFloat2('direction', 17, 17);
  79231. effect.setFloat2('centerPosition', 0.5, 0.5);
  79232. };
  79233. };
  79234. // highlights enhancing
  79235. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  79236. var _this = this;
  79237. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  79238. [], // samplers
  79239. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  79240. this._highlightsPostProcess.onApply = function (effect) {
  79241. effect.setFloat('gain', _this._highlightsGain);
  79242. effect.setFloat('threshold', _this._highlightsThreshold);
  79243. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  79244. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79245. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79246. };
  79247. };
  79248. // colors shifting and distortion
  79249. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  79250. var _this = this;
  79251. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  79252. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  79253. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  79254. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79255. this._depthOfFieldPostProcess.onApply = function (effect) {
  79256. effect.setTexture("depthSampler", _this._depthTexture);
  79257. effect.setTexture("grainSampler", _this._grainTexture);
  79258. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  79259. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  79260. effect.setFloat('grain_amount', _this._grainAmount);
  79261. effect.setBool('blur_noise', _this._blurNoise);
  79262. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79263. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79264. effect.setFloat('distortion', _this._distortion);
  79265. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  79266. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  79267. effect.setFloat('aperture', _this._dofAperture);
  79268. effect.setFloat('darken', _this._dofDarken);
  79269. effect.setFloat('edge_blur', _this._edgeBlur);
  79270. effect.setBool('highlights', (_this._highlightsGain !== -1));
  79271. if (_this._scene.activeCamera) {
  79272. effect.setFloat('near', _this._scene.activeCamera.minZ);
  79273. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  79274. }
  79275. };
  79276. };
  79277. // creates a black and white random noise texture, 512x512
  79278. LensRenderingPipeline.prototype._createGrainTexture = function () {
  79279. var size = 512;
  79280. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79281. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  79282. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  79283. var context = this._grainTexture.getContext();
  79284. var rand = function (min, max) {
  79285. return Math.random() * (max - min) + min;
  79286. };
  79287. var value;
  79288. for (var x = 0; x < size; x++) {
  79289. for (var y = 0; y < size; y++) {
  79290. value = Math.floor(rand(0.42, 0.58) * 255);
  79291. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  79292. context.fillRect(x, y, 1, 1);
  79293. }
  79294. }
  79295. this._grainTexture.update(false);
  79296. };
  79297. return LensRenderingPipeline;
  79298. }(BABYLON.PostProcessRenderPipeline));
  79299. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  79300. })(BABYLON || (BABYLON = {}));
  79301. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  79302. var BABYLON;
  79303. (function (BABYLON) {
  79304. var StandardRenderingPipeline = /** @class */ (function (_super) {
  79305. __extends(StandardRenderingPipeline, _super);
  79306. /**
  79307. * @constructor
  79308. * @param {string} name - The rendering pipeline name
  79309. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79310. * @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)
  79311. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  79312. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79313. */
  79314. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  79315. if (originalPostProcess === void 0) { originalPostProcess = null; }
  79316. var _this = _super.call(this, scene.getEngine(), name) || this;
  79317. /**
  79318. * Post-process used to down scale an image x4
  79319. */
  79320. _this.downSampleX4PostProcess = null;
  79321. /**
  79322. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  79323. */
  79324. _this.brightPassPostProcess = null;
  79325. /**
  79326. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  79327. */
  79328. _this.blurHPostProcesses = [];
  79329. /**
  79330. * Post-process array storing all the vertical blur post-processes used by the pipeline
  79331. */
  79332. _this.blurVPostProcesses = [];
  79333. /**
  79334. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  79335. */
  79336. _this.textureAdderPostProcess = null;
  79337. /**
  79338. * Post-process used to create volumetric lighting effect
  79339. */
  79340. _this.volumetricLightPostProcess = null;
  79341. /**
  79342. * Post-process used to smooth the previous volumetric light post-process on the X axis
  79343. */
  79344. _this.volumetricLightSmoothXPostProcess = null;
  79345. /**
  79346. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  79347. */
  79348. _this.volumetricLightSmoothYPostProcess = null;
  79349. /**
  79350. * Post-process used to merge the volumetric light effect and the real scene color
  79351. */
  79352. _this.volumetricLightMergePostProces = null;
  79353. /**
  79354. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  79355. */
  79356. _this.volumetricLightFinalPostProcess = null;
  79357. /**
  79358. * Base post-process used to calculate the average luminance of the final image for HDR
  79359. */
  79360. _this.luminancePostProcess = null;
  79361. /**
  79362. * Post-processes used to create down sample post-processes in order to get
  79363. * the average luminance of the final image for HDR
  79364. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  79365. */
  79366. _this.luminanceDownSamplePostProcesses = [];
  79367. /**
  79368. * Post-process used to create a HDR effect (light adaptation)
  79369. */
  79370. _this.hdrPostProcess = null;
  79371. /**
  79372. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  79373. */
  79374. _this.textureAdderFinalPostProcess = null;
  79375. /**
  79376. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  79377. */
  79378. _this.lensFlareFinalPostProcess = null;
  79379. /**
  79380. * Post-process used to merge the final HDR post-process and the real scene color
  79381. */
  79382. _this.hdrFinalPostProcess = null;
  79383. /**
  79384. * Post-process used to create a lens flare effect
  79385. */
  79386. _this.lensFlarePostProcess = null;
  79387. /**
  79388. * Post-process that merges the result of the lens flare post-process and the real scene color
  79389. */
  79390. _this.lensFlareComposePostProcess = null;
  79391. /**
  79392. * Post-process used to create a motion blur effect
  79393. */
  79394. _this.motionBlurPostProcess = null;
  79395. /**
  79396. * Post-process used to create a depth of field effect
  79397. */
  79398. _this.depthOfFieldPostProcess = null;
  79399. /**
  79400. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  79401. */
  79402. _this.fxaaPostProcess = null;
  79403. // Values
  79404. /**
  79405. * Represents the brightness threshold in order to configure the illuminated surfaces
  79406. */
  79407. _this.brightThreshold = 1.0;
  79408. /**
  79409. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  79410. */
  79411. _this.blurWidth = 512.0;
  79412. /**
  79413. * Sets if the blur for highlighted surfaces must be only horizontal
  79414. */
  79415. _this.horizontalBlur = false;
  79416. /**
  79417. * Sets the overall exposure used by the pipeline
  79418. */
  79419. _this.exposure = 1.0;
  79420. /**
  79421. * Texture used typically to simulate "dirty" on camera lens
  79422. */
  79423. _this.lensTexture = null;
  79424. /**
  79425. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  79426. */
  79427. _this.volumetricLightCoefficient = 0.2;
  79428. /**
  79429. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  79430. */
  79431. _this.volumetricLightPower = 4.0;
  79432. /**
  79433. * Used the set the blur intensity to smooth the volumetric lights
  79434. */
  79435. _this.volumetricLightBlurScale = 64.0;
  79436. /**
  79437. * Light (spot or directional) used to generate the volumetric lights rays
  79438. * The source light must have a shadow generate so the pipeline can get its
  79439. * depth map
  79440. */
  79441. _this.sourceLight = null;
  79442. /**
  79443. * For eye adaptation, represents the minimum luminance the eye can see
  79444. */
  79445. _this.hdrMinimumLuminance = 1.0;
  79446. /**
  79447. * For eye adaptation, represents the decrease luminance speed
  79448. */
  79449. _this.hdrDecreaseRate = 0.5;
  79450. /**
  79451. * For eye adaptation, represents the increase luminance speed
  79452. */
  79453. _this.hdrIncreaseRate = 0.5;
  79454. /**
  79455. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  79456. */
  79457. _this.lensColorTexture = null;
  79458. /**
  79459. * The overall strengh for the lens flare effect
  79460. */
  79461. _this.lensFlareStrength = 20.0;
  79462. /**
  79463. * Dispersion coefficient for lens flare ghosts
  79464. */
  79465. _this.lensFlareGhostDispersal = 1.4;
  79466. /**
  79467. * Main lens flare halo width
  79468. */
  79469. _this.lensFlareHaloWidth = 0.7;
  79470. /**
  79471. * Based on the lens distortion effect, defines how much the lens flare result
  79472. * is distorted
  79473. */
  79474. _this.lensFlareDistortionStrength = 16.0;
  79475. /**
  79476. * Lens star texture must be used to simulate rays on the flares and is available
  79477. * in the documentation
  79478. */
  79479. _this.lensStarTexture = null;
  79480. /**
  79481. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  79482. * flare effect by taking account of the dirt texture
  79483. */
  79484. _this.lensFlareDirtTexture = null;
  79485. /**
  79486. * Represents the focal length for the depth of field effect
  79487. */
  79488. _this.depthOfFieldDistance = 10.0;
  79489. /**
  79490. * Represents the blur intensity for the blurred part of the depth of field effect
  79491. */
  79492. _this.depthOfFieldBlurWidth = 64.0;
  79493. /**
  79494. * For motion blur, defines how much the image is blurred by the movement
  79495. */
  79496. _this.motionStrength = 1.0;
  79497. /**
  79498. * List of animations for the pipeline (IAnimatable implementation)
  79499. */
  79500. _this.animations = [];
  79501. _this._currentDepthOfFieldSource = null;
  79502. _this._hdrCurrentLuminance = 1.0;
  79503. // Getters and setters
  79504. _this._bloomEnabled = false;
  79505. _this._depthOfFieldEnabled = false;
  79506. _this._vlsEnabled = false;
  79507. _this._lensFlareEnabled = false;
  79508. _this._hdrEnabled = false;
  79509. _this._motionBlurEnabled = false;
  79510. _this._fxaaEnabled = false;
  79511. _this._motionBlurSamples = 64.0;
  79512. _this._volumetricLightStepsCount = 50.0;
  79513. _this._samples = 1;
  79514. _this._cameras = cameras || [];
  79515. // Initialize
  79516. _this._scene = scene;
  79517. _this._basePostProcess = originalPostProcess;
  79518. _this._ratio = ratio;
  79519. // Misc
  79520. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79521. // Finish
  79522. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79523. _this._buildPipeline();
  79524. return _this;
  79525. }
  79526. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  79527. /**
  79528. * Specifies if the bloom pipeline is enabled
  79529. */
  79530. get: function () {
  79531. return this._bloomEnabled;
  79532. },
  79533. set: function (enabled) {
  79534. if (this._bloomEnabled === enabled) {
  79535. return;
  79536. }
  79537. this._bloomEnabled = enabled;
  79538. this._buildPipeline();
  79539. },
  79540. enumerable: true,
  79541. configurable: true
  79542. });
  79543. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  79544. /**
  79545. * Specifies if the depth of field pipeline is enabed
  79546. */
  79547. get: function () {
  79548. return this._depthOfFieldEnabled;
  79549. },
  79550. set: function (enabled) {
  79551. if (this._depthOfFieldEnabled === enabled) {
  79552. return;
  79553. }
  79554. this._depthOfFieldEnabled = enabled;
  79555. this._buildPipeline();
  79556. },
  79557. enumerable: true,
  79558. configurable: true
  79559. });
  79560. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  79561. /**
  79562. * Specifies if the lens flare pipeline is enabed
  79563. */
  79564. get: function () {
  79565. return this._lensFlareEnabled;
  79566. },
  79567. set: function (enabled) {
  79568. if (this._lensFlareEnabled === enabled) {
  79569. return;
  79570. }
  79571. this._lensFlareEnabled = enabled;
  79572. this._buildPipeline();
  79573. },
  79574. enumerable: true,
  79575. configurable: true
  79576. });
  79577. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  79578. /**
  79579. * Specifies if the HDR pipeline is enabled
  79580. */
  79581. get: function () {
  79582. return this._hdrEnabled;
  79583. },
  79584. set: function (enabled) {
  79585. if (this._hdrEnabled === enabled) {
  79586. return;
  79587. }
  79588. this._hdrEnabled = enabled;
  79589. this._buildPipeline();
  79590. },
  79591. enumerable: true,
  79592. configurable: true
  79593. });
  79594. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  79595. /**
  79596. * Specifies if the volumetric lights scattering effect is enabled
  79597. */
  79598. get: function () {
  79599. return this._vlsEnabled;
  79600. },
  79601. set: function (enabled) {
  79602. if (this._vlsEnabled === enabled) {
  79603. return;
  79604. }
  79605. if (enabled) {
  79606. var geometry = this._scene.enableGeometryBufferRenderer();
  79607. if (!geometry) {
  79608. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  79609. return;
  79610. }
  79611. }
  79612. this._vlsEnabled = enabled;
  79613. this._buildPipeline();
  79614. },
  79615. enumerable: true,
  79616. configurable: true
  79617. });
  79618. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  79619. /**
  79620. * Specifies if the motion blur effect is enabled
  79621. */
  79622. get: function () {
  79623. return this._motionBlurEnabled;
  79624. },
  79625. set: function (enabled) {
  79626. if (this._motionBlurEnabled === enabled) {
  79627. return;
  79628. }
  79629. this._motionBlurEnabled = enabled;
  79630. this._buildPipeline();
  79631. },
  79632. enumerable: true,
  79633. configurable: true
  79634. });
  79635. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  79636. /**
  79637. * Specifies if anti-aliasing is enabled
  79638. */
  79639. get: function () {
  79640. return this._fxaaEnabled;
  79641. },
  79642. set: function (enabled) {
  79643. if (this._fxaaEnabled === enabled) {
  79644. return;
  79645. }
  79646. this._fxaaEnabled = enabled;
  79647. this._buildPipeline();
  79648. },
  79649. enumerable: true,
  79650. configurable: true
  79651. });
  79652. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  79653. /**
  79654. * Specifies the number of steps used to calculate the volumetric lights
  79655. * Typically in interval [50, 200]
  79656. */
  79657. get: function () {
  79658. return this._volumetricLightStepsCount;
  79659. },
  79660. set: function (count) {
  79661. if (this.volumetricLightPostProcess) {
  79662. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  79663. }
  79664. this._volumetricLightStepsCount = count;
  79665. },
  79666. enumerable: true,
  79667. configurable: true
  79668. });
  79669. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  79670. /**
  79671. * Specifies the number of samples used for the motion blur effect
  79672. * Typically in interval [16, 64]
  79673. */
  79674. get: function () {
  79675. return this._motionBlurSamples;
  79676. },
  79677. set: function (samples) {
  79678. if (this.motionBlurPostProcess) {
  79679. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  79680. }
  79681. this._motionBlurSamples = samples;
  79682. },
  79683. enumerable: true,
  79684. configurable: true
  79685. });
  79686. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  79687. /**
  79688. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79689. */
  79690. get: function () {
  79691. return this._samples;
  79692. },
  79693. set: function (sampleCount) {
  79694. if (this._samples === sampleCount) {
  79695. return;
  79696. }
  79697. this._samples = sampleCount;
  79698. this._buildPipeline();
  79699. },
  79700. enumerable: true,
  79701. configurable: true
  79702. });
  79703. StandardRenderingPipeline.prototype._buildPipeline = function () {
  79704. var _this = this;
  79705. var ratio = this._ratio;
  79706. var scene = this._scene;
  79707. this._disposePostProcesses();
  79708. this._reset();
  79709. // Create pass post-process
  79710. if (!this._basePostProcess) {
  79711. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  79712. this.originalPostProcess.onApply = function (effect) {
  79713. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  79714. };
  79715. }
  79716. else {
  79717. this.originalPostProcess = this._basePostProcess;
  79718. }
  79719. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  79720. this._currentDepthOfFieldSource = this.originalPostProcess;
  79721. if (this._bloomEnabled) {
  79722. // Create down sample X4 post-process
  79723. this._createDownSampleX4PostProcess(scene, ratio / 2);
  79724. // Create bright pass post-process
  79725. this._createBrightPassPostProcess(scene, ratio / 2);
  79726. // Create gaussian blur post-processes (down sampling blurs)
  79727. this._createBlurPostProcesses(scene, ratio / 4, 1);
  79728. // Create texture adder post-process
  79729. this._createTextureAdderPostProcess(scene, ratio);
  79730. // Create depth-of-field source post-process
  79731. 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);
  79732. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  79733. }
  79734. if (this._vlsEnabled) {
  79735. // Create volumetric light
  79736. this._createVolumetricLightPostProcess(scene, ratio);
  79737. // Create volumetric light final post-process
  79738. 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);
  79739. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  79740. }
  79741. if (this._lensFlareEnabled) {
  79742. // Create lens flare post-process
  79743. this._createLensFlarePostProcess(scene, ratio);
  79744. // Create depth-of-field source post-process post lens-flare and disable it now
  79745. 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);
  79746. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  79747. }
  79748. if (this._hdrEnabled) {
  79749. // Create luminance
  79750. this._createLuminancePostProcesses(scene, this._floatTextureType);
  79751. // Create HDR
  79752. this._createHdrPostProcess(scene, ratio);
  79753. // Create depth-of-field source post-process post hdr and disable it now
  79754. 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);
  79755. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  79756. }
  79757. if (this._depthOfFieldEnabled) {
  79758. // Create gaussian blur used by depth-of-field
  79759. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  79760. // Create depth-of-field post-process
  79761. this._createDepthOfFieldPostProcess(scene, ratio);
  79762. }
  79763. if (this._motionBlurEnabled) {
  79764. // Create motion blur post-process
  79765. this._createMotionBlurPostProcess(scene, ratio);
  79766. }
  79767. if (this._fxaaEnabled) {
  79768. // Create fxaa post-process
  79769. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79770. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  79771. }
  79772. if (this._cameras !== null) {
  79773. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  79774. }
  79775. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  79776. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  79777. }
  79778. };
  79779. // Down Sample X4 Post-Processs
  79780. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  79781. var _this = this;
  79782. var downSampleX4Offsets = new Array(32);
  79783. 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);
  79784. this.downSampleX4PostProcess.onApply = function (effect) {
  79785. var id = 0;
  79786. var width = _this.downSampleX4PostProcess.width;
  79787. var height = _this.downSampleX4PostProcess.height;
  79788. for (var i = -2; i < 2; i++) {
  79789. for (var j = -2; j < 2; j++) {
  79790. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  79791. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  79792. id += 2;
  79793. }
  79794. }
  79795. effect.setArray2("dsOffsets", downSampleX4Offsets);
  79796. };
  79797. // Add to pipeline
  79798. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  79799. };
  79800. // Brightpass Post-Process
  79801. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  79802. var _this = this;
  79803. var brightOffsets = new Array(8);
  79804. 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);
  79805. this.brightPassPostProcess.onApply = function (effect) {
  79806. var sU = (1.0 / _this.brightPassPostProcess.width);
  79807. var sV = (1.0 / _this.brightPassPostProcess.height);
  79808. brightOffsets[0] = -0.5 * sU;
  79809. brightOffsets[1] = 0.5 * sV;
  79810. brightOffsets[2] = 0.5 * sU;
  79811. brightOffsets[3] = 0.5 * sV;
  79812. brightOffsets[4] = -0.5 * sU;
  79813. brightOffsets[5] = -0.5 * sV;
  79814. brightOffsets[6] = 0.5 * sU;
  79815. brightOffsets[7] = -0.5 * sV;
  79816. effect.setArray2("dsOffsets", brightOffsets);
  79817. effect.setFloat("brightThreshold", _this.brightThreshold);
  79818. };
  79819. // Add to pipeline
  79820. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  79821. };
  79822. // Create blur H&V post-processes
  79823. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  79824. var _this = this;
  79825. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  79826. var engine = scene.getEngine();
  79827. 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);
  79828. 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);
  79829. blurX.onActivateObservable.add(function () {
  79830. var dw = blurX.width / engine.getRenderWidth();
  79831. blurX.kernel = _this[blurWidthKey] * dw;
  79832. });
  79833. blurY.onActivateObservable.add(function () {
  79834. var dw = blurY.height / engine.getRenderHeight();
  79835. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  79836. });
  79837. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  79838. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  79839. this.blurHPostProcesses.push(blurX);
  79840. this.blurVPostProcesses.push(blurY);
  79841. };
  79842. // Create texture adder post-process
  79843. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  79844. var _this = this;
  79845. 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);
  79846. this.textureAdderPostProcess.onApply = function (effect) {
  79847. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  79848. effect.setTexture("lensSampler", _this.lensTexture);
  79849. effect.setFloat("exposure", _this.exposure);
  79850. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  79851. };
  79852. // Add to pipeline
  79853. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  79854. };
  79855. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  79856. var _this = this;
  79857. var geometryRenderer = scene.enableGeometryBufferRenderer();
  79858. geometryRenderer.enablePosition = true;
  79859. var geometry = geometryRenderer.getGBuffer();
  79860. // Base post-process
  79861. 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));
  79862. var depthValues = BABYLON.Vector2.Zero();
  79863. this.volumetricLightPostProcess.onApply = function (effect) {
  79864. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  79865. var generator = _this.sourceLight.getShadowGenerator();
  79866. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  79867. effect.setTexture("positionSampler", geometry.textures[2]);
  79868. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  79869. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  79870. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  79871. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  79872. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  79873. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  79874. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  79875. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  79876. effect.setVector2("depthValues", depthValues);
  79877. }
  79878. };
  79879. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  79880. // Smooth
  79881. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  79882. // Merge
  79883. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  79884. this.volumetricLightMergePostProces.onApply = function (effect) {
  79885. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  79886. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  79887. };
  79888. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  79889. };
  79890. // Create luminance
  79891. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  79892. var _this = this;
  79893. // Create luminance
  79894. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  79895. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  79896. var offsets = [];
  79897. this.luminancePostProcess.onApply = function (effect) {
  79898. var sU = (1.0 / _this.luminancePostProcess.width);
  79899. var sV = (1.0 / _this.luminancePostProcess.height);
  79900. offsets[0] = -0.5 * sU;
  79901. offsets[1] = 0.5 * sV;
  79902. offsets[2] = 0.5 * sU;
  79903. offsets[3] = 0.5 * sV;
  79904. offsets[4] = -0.5 * sU;
  79905. offsets[5] = -0.5 * sV;
  79906. offsets[6] = 0.5 * sU;
  79907. offsets[7] = -0.5 * sV;
  79908. effect.setArray2("lumOffsets", offsets);
  79909. };
  79910. // Add to pipeline
  79911. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  79912. // Create down sample luminance
  79913. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  79914. var size = Math.pow(3, i);
  79915. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  79916. if (i === 0) {
  79917. defines += "#define FINAL_DOWN_SAMPLER";
  79918. }
  79919. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  79920. this.luminanceDownSamplePostProcesses.push(postProcess);
  79921. }
  79922. // Create callbacks and add effects
  79923. var lastLuminance = this.luminancePostProcess;
  79924. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  79925. var downSampleOffsets = new Array(18);
  79926. pp.onApply = function (effect) {
  79927. if (!lastLuminance) {
  79928. return;
  79929. }
  79930. var id = 0;
  79931. for (var x = -1; x < 2; x++) {
  79932. for (var y = -1; y < 2; y++) {
  79933. downSampleOffsets[id] = x / lastLuminance.width;
  79934. downSampleOffsets[id + 1] = y / lastLuminance.height;
  79935. id += 2;
  79936. }
  79937. }
  79938. effect.setArray2("dsOffsets", downSampleOffsets);
  79939. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  79940. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79941. lastLuminance = _this.luminancePostProcess;
  79942. }
  79943. else {
  79944. lastLuminance = pp;
  79945. }
  79946. };
  79947. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79948. pp.onAfterRender = function (effect) {
  79949. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  79950. 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);
  79951. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  79952. };
  79953. }
  79954. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  79955. });
  79956. };
  79957. // Create HDR post-process
  79958. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  79959. var _this = this;
  79960. 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);
  79961. var outputLiminance = 1;
  79962. var time = 0;
  79963. var lastTime = 0;
  79964. this.hdrPostProcess.onApply = function (effect) {
  79965. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  79966. time += scene.getEngine().getDeltaTime();
  79967. if (outputLiminance < 0) {
  79968. outputLiminance = _this._hdrCurrentLuminance;
  79969. }
  79970. else {
  79971. var dt = (lastTime - time) / 1000.0;
  79972. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  79973. outputLiminance += _this.hdrDecreaseRate * dt;
  79974. }
  79975. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  79976. outputLiminance -= _this.hdrIncreaseRate * dt;
  79977. }
  79978. else {
  79979. outputLiminance = _this._hdrCurrentLuminance;
  79980. }
  79981. }
  79982. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  79983. effect.setFloat("averageLuminance", outputLiminance);
  79984. lastTime = time;
  79985. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  79986. };
  79987. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  79988. };
  79989. // Create lens flare post-process
  79990. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  79991. var _this = this;
  79992. 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);
  79993. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  79994. this._createBlurPostProcesses(scene, ratio / 4, 2);
  79995. 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);
  79996. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  79997. var resolution = new BABYLON.Vector2(0, 0);
  79998. // Lens flare
  79999. this.lensFlarePostProcess.onApply = function (effect) {
  80000. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  80001. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  80002. effect.setFloat("strength", _this.lensFlareStrength);
  80003. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  80004. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  80005. // Shift
  80006. resolution.x = _this.lensFlarePostProcess.width;
  80007. resolution.y = _this.lensFlarePostProcess.height;
  80008. effect.setVector2("resolution", resolution);
  80009. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  80010. };
  80011. // Compose
  80012. 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);
  80013. 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);
  80014. this.lensFlareComposePostProcess.onApply = function (effect) {
  80015. if (!_this._scene.activeCamera) {
  80016. return;
  80017. }
  80018. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  80019. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  80020. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  80021. // Lens start rotation matrix
  80022. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  80023. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  80024. 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));
  80025. camRot *= 4.0;
  80026. 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);
  80027. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  80028. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  80029. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  80030. };
  80031. };
  80032. // Create depth-of-field post-process
  80033. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  80034. var _this = this;
  80035. 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);
  80036. this.depthOfFieldPostProcess.onApply = function (effect) {
  80037. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  80038. effect.setTexture("depthSampler", _this._getDepthTexture());
  80039. effect.setFloat("distance", _this.depthOfFieldDistance);
  80040. };
  80041. // Add to pipeline
  80042. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  80043. };
  80044. // Create motion blur post-process
  80045. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  80046. var _this = this;
  80047. 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);
  80048. var motionScale = 0;
  80049. var prevViewProjection = BABYLON.Matrix.Identity();
  80050. var invViewProjection = BABYLON.Matrix.Identity();
  80051. var viewProjection = BABYLON.Matrix.Identity();
  80052. var screenSize = BABYLON.Vector2.Zero();
  80053. this.motionBlurPostProcess.onApply = function (effect) {
  80054. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  80055. viewProjection.invertToRef(invViewProjection);
  80056. effect.setMatrix("inverseViewProjection", invViewProjection);
  80057. effect.setMatrix("prevViewProjection", prevViewProjection);
  80058. prevViewProjection = viewProjection;
  80059. screenSize.x = _this.motionBlurPostProcess.width;
  80060. screenSize.y = _this.motionBlurPostProcess.height;
  80061. effect.setVector2("screenSize", screenSize);
  80062. motionScale = scene.getEngine().getFps() / 60.0;
  80063. effect.setFloat("motionScale", motionScale);
  80064. effect.setFloat("motionStrength", _this.motionStrength);
  80065. effect.setTexture("depthSampler", _this._getDepthTexture());
  80066. };
  80067. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  80068. };
  80069. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  80070. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  80071. var renderer = this._scene.enableGeometryBufferRenderer();
  80072. return renderer.getGBuffer().textures[0];
  80073. }
  80074. return this._scene.enableDepthRenderer().getDepthMap();
  80075. };
  80076. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  80077. for (var i = 0; i < this._cameras.length; i++) {
  80078. var camera = this._cameras[i];
  80079. if (this.originalPostProcess) {
  80080. this.originalPostProcess.dispose(camera);
  80081. }
  80082. if (this.downSampleX4PostProcess) {
  80083. this.downSampleX4PostProcess.dispose(camera);
  80084. }
  80085. if (this.brightPassPostProcess) {
  80086. this.brightPassPostProcess.dispose(camera);
  80087. }
  80088. if (this.textureAdderPostProcess) {
  80089. this.textureAdderPostProcess.dispose(camera);
  80090. }
  80091. if (this.textureAdderFinalPostProcess) {
  80092. this.textureAdderFinalPostProcess.dispose(camera);
  80093. }
  80094. if (this.volumetricLightPostProcess) {
  80095. this.volumetricLightPostProcess.dispose(camera);
  80096. }
  80097. if (this.volumetricLightSmoothXPostProcess) {
  80098. this.volumetricLightSmoothXPostProcess.dispose(camera);
  80099. }
  80100. if (this.volumetricLightSmoothYPostProcess) {
  80101. this.volumetricLightSmoothYPostProcess.dispose(camera);
  80102. }
  80103. if (this.volumetricLightMergePostProces) {
  80104. this.volumetricLightMergePostProces.dispose(camera);
  80105. }
  80106. if (this.volumetricLightFinalPostProcess) {
  80107. this.volumetricLightFinalPostProcess.dispose(camera);
  80108. }
  80109. if (this.lensFlarePostProcess) {
  80110. this.lensFlarePostProcess.dispose(camera);
  80111. }
  80112. if (this.lensFlareComposePostProcess) {
  80113. this.lensFlareComposePostProcess.dispose(camera);
  80114. }
  80115. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  80116. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  80117. }
  80118. if (this.luminancePostProcess) {
  80119. this.luminancePostProcess.dispose(camera);
  80120. }
  80121. if (this.hdrPostProcess) {
  80122. this.hdrPostProcess.dispose(camera);
  80123. }
  80124. if (this.hdrFinalPostProcess) {
  80125. this.hdrFinalPostProcess.dispose(camera);
  80126. }
  80127. if (this.depthOfFieldPostProcess) {
  80128. this.depthOfFieldPostProcess.dispose(camera);
  80129. }
  80130. if (this.motionBlurPostProcess) {
  80131. this.motionBlurPostProcess.dispose(camera);
  80132. }
  80133. if (this.fxaaPostProcess) {
  80134. this.fxaaPostProcess.dispose(camera);
  80135. }
  80136. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  80137. this.blurHPostProcesses[j].dispose(camera);
  80138. }
  80139. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  80140. this.blurVPostProcesses[j].dispose(camera);
  80141. }
  80142. }
  80143. this.originalPostProcess = null;
  80144. this.downSampleX4PostProcess = null;
  80145. this.brightPassPostProcess = null;
  80146. this.textureAdderPostProcess = null;
  80147. this.textureAdderFinalPostProcess = null;
  80148. this.volumetricLightPostProcess = null;
  80149. this.volumetricLightSmoothXPostProcess = null;
  80150. this.volumetricLightSmoothYPostProcess = null;
  80151. this.volumetricLightMergePostProces = null;
  80152. this.volumetricLightFinalPostProcess = null;
  80153. this.lensFlarePostProcess = null;
  80154. this.lensFlareComposePostProcess = null;
  80155. this.luminancePostProcess = null;
  80156. this.hdrPostProcess = null;
  80157. this.hdrFinalPostProcess = null;
  80158. this.depthOfFieldPostProcess = null;
  80159. this.motionBlurPostProcess = null;
  80160. this.fxaaPostProcess = null;
  80161. this.luminanceDownSamplePostProcesses = [];
  80162. this.blurHPostProcesses = [];
  80163. this.blurVPostProcesses = [];
  80164. };
  80165. /**
  80166. * Dispose of the pipeline and stop all post processes
  80167. */
  80168. StandardRenderingPipeline.prototype.dispose = function () {
  80169. this._disposePostProcesses();
  80170. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80171. _super.prototype.dispose.call(this);
  80172. };
  80173. /**
  80174. * Serialize the rendering pipeline (Used when exporting)
  80175. * @returns the serialized object
  80176. */
  80177. StandardRenderingPipeline.prototype.serialize = function () {
  80178. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80179. if (this.sourceLight) {
  80180. serializationObject.sourceLightId = this.sourceLight.id;
  80181. }
  80182. serializationObject.customType = "StandardRenderingPipeline";
  80183. return serializationObject;
  80184. };
  80185. /**
  80186. * Parse the serialized pipeline
  80187. * @param source Source pipeline.
  80188. * @param scene The scene to load the pipeline to.
  80189. * @param rootUrl The URL of the serialized pipeline.
  80190. * @returns An instantiated pipeline from the serialized object.
  80191. */
  80192. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80193. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  80194. if (source.sourceLightId) {
  80195. p.sourceLight = scene.getLightByID(source.sourceLightId);
  80196. }
  80197. return p;
  80198. };
  80199. // Luminance steps
  80200. StandardRenderingPipeline.LuminanceSteps = 6;
  80201. __decorate([
  80202. BABYLON.serialize()
  80203. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  80204. __decorate([
  80205. BABYLON.serialize()
  80206. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  80207. __decorate([
  80208. BABYLON.serialize()
  80209. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  80210. __decorate([
  80211. BABYLON.serialize()
  80212. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  80213. __decorate([
  80214. BABYLON.serializeAsTexture("lensTexture")
  80215. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  80216. __decorate([
  80217. BABYLON.serialize()
  80218. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  80219. __decorate([
  80220. BABYLON.serialize()
  80221. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  80222. __decorate([
  80223. BABYLON.serialize()
  80224. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  80225. __decorate([
  80226. BABYLON.serialize()
  80227. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  80228. __decorate([
  80229. BABYLON.serialize()
  80230. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  80231. __decorate([
  80232. BABYLON.serialize()
  80233. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  80234. __decorate([
  80235. BABYLON.serializeAsTexture("lensColorTexture")
  80236. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  80237. __decorate([
  80238. BABYLON.serialize()
  80239. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  80240. __decorate([
  80241. BABYLON.serialize()
  80242. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  80243. __decorate([
  80244. BABYLON.serialize()
  80245. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  80246. __decorate([
  80247. BABYLON.serialize()
  80248. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  80249. __decorate([
  80250. BABYLON.serializeAsTexture("lensStarTexture")
  80251. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  80252. __decorate([
  80253. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  80254. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  80255. __decorate([
  80256. BABYLON.serialize()
  80257. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  80258. __decorate([
  80259. BABYLON.serialize()
  80260. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  80261. __decorate([
  80262. BABYLON.serialize()
  80263. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  80264. __decorate([
  80265. BABYLON.serialize()
  80266. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  80267. __decorate([
  80268. BABYLON.serialize()
  80269. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  80270. __decorate([
  80271. BABYLON.serialize()
  80272. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  80273. __decorate([
  80274. BABYLON.serialize()
  80275. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  80276. __decorate([
  80277. BABYLON.serialize()
  80278. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  80279. __decorate([
  80280. BABYLON.serialize()
  80281. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  80282. __decorate([
  80283. BABYLON.serialize()
  80284. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  80285. __decorate([
  80286. BABYLON.serialize()
  80287. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  80288. __decorate([
  80289. BABYLON.serialize()
  80290. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  80291. __decorate([
  80292. BABYLON.serialize()
  80293. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  80294. __decorate([
  80295. BABYLON.serialize()
  80296. ], StandardRenderingPipeline.prototype, "samples", null);
  80297. return StandardRenderingPipeline;
  80298. }(BABYLON.PostProcessRenderPipeline));
  80299. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  80300. })(BABYLON || (BABYLON = {}));
  80301. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  80302. var BABYLON;
  80303. (function (BABYLON) {
  80304. var FxaaPostProcess = /** @class */ (function (_super) {
  80305. __extends(FxaaPostProcess, _super);
  80306. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80307. if (camera === void 0) { camera = null; }
  80308. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80309. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  80310. var defines = _this._getDefines();
  80311. _this.updateEffect(defines);
  80312. _this.onApplyObservable.add(function (effect) {
  80313. var texelSize = _this.texelSize;
  80314. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  80315. });
  80316. return _this;
  80317. }
  80318. FxaaPostProcess.prototype._getDefines = function () {
  80319. var engine = this.getEngine();
  80320. if (!engine) {
  80321. return null;
  80322. }
  80323. var glInfo = engine.getGlInfo();
  80324. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  80325. return "#define MALI 1\n";
  80326. }
  80327. return null;
  80328. };
  80329. return FxaaPostProcess;
  80330. }(BABYLON.PostProcess));
  80331. BABYLON.FxaaPostProcess = FxaaPostProcess;
  80332. })(BABYLON || (BABYLON = {}));
  80333. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  80334. var BABYLON;
  80335. (function (BABYLON) {
  80336. /**
  80337. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  80338. */
  80339. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  80340. __extends(ChromaticAberrationPostProcess, _super);
  80341. /**
  80342. * Creates a new instance ChromaticAberrationPostProcess
  80343. * @param name The name of the effect.
  80344. * @param screenWidth The width of the screen to apply the effect on.
  80345. * @param screenHeight The height of the screen to apply the effect on.
  80346. * @param options The required width/height ratio to downsize to before computing the render pass.
  80347. * @param camera The camera to apply the render pass to.
  80348. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80349. * @param engine The engine which the post process will be applied. (default: current engine)
  80350. * @param reusable If the post process can be reused on the same frame. (default: false)
  80351. * @param textureType Type of textures used when performing the post process. (default: 0)
  80352. * @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)
  80353. */
  80354. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80355. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80356. if (blockCompilation === void 0) { blockCompilation = false; }
  80357. 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;
  80358. /**
  80359. * The amount of seperation of rgb channels (default: 30)
  80360. */
  80361. _this.aberrationAmount = 30;
  80362. /**
  80363. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  80364. */
  80365. _this.radialIntensity = 0;
  80366. /**
  80367. * 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))
  80368. */
  80369. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  80370. /**
  80371. * 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))
  80372. */
  80373. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  80374. _this.onApplyObservable.add(function (effect) {
  80375. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  80376. effect.setFloat('screen_width', screenWidth);
  80377. effect.setFloat('screen_height', screenHeight);
  80378. effect.setFloat('radialIntensity', _this.radialIntensity);
  80379. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  80380. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  80381. });
  80382. return _this;
  80383. }
  80384. return ChromaticAberrationPostProcess;
  80385. }(BABYLON.PostProcess));
  80386. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  80387. })(BABYLON || (BABYLON = {}));
  80388. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  80389. var BABYLON;
  80390. (function (BABYLON) {
  80391. /**
  80392. * The GrainPostProcess adds noise to the image at mid luminance levels
  80393. */
  80394. var GrainPostProcess = /** @class */ (function (_super) {
  80395. __extends(GrainPostProcess, _super);
  80396. /**
  80397. * Creates a new instance of @see GrainPostProcess
  80398. * @param name The name of the effect.
  80399. * @param options The required width/height ratio to downsize to before computing the render pass.
  80400. * @param camera The camera to apply the render pass to.
  80401. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80402. * @param engine The engine which the post process will be applied. (default: current engine)
  80403. * @param reusable If the post process can be reused on the same frame. (default: false)
  80404. * @param textureType Type of textures used when performing the post process. (default: 0)
  80405. * @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)
  80406. */
  80407. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80408. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80409. if (blockCompilation === void 0) { blockCompilation = false; }
  80410. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80411. /**
  80412. * The intensity of the grain added (default: 30)
  80413. */
  80414. _this.intensity = 30;
  80415. /**
  80416. * If the grain should be randomized on every frame
  80417. */
  80418. _this.animated = false;
  80419. _this.onApplyObservable.add(function (effect) {
  80420. effect.setFloat('intensity', _this.intensity);
  80421. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  80422. });
  80423. return _this;
  80424. }
  80425. return GrainPostProcess;
  80426. }(BABYLON.PostProcess));
  80427. BABYLON.GrainPostProcess = GrainPostProcess;
  80428. })(BABYLON || (BABYLON = {}));
  80429. //# sourceMappingURL=babylon.grainPostProcess.js.map
  80430. var BABYLON;
  80431. (function (BABYLON) {
  80432. /**
  80433. * The SharpenPostProcess applies a sharpen kernel to every pixel
  80434. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80435. */
  80436. var SharpenPostProcess = /** @class */ (function (_super) {
  80437. __extends(SharpenPostProcess, _super);
  80438. /**
  80439. * Creates a new instance ConvolutionPostProcess
  80440. * @param name The name of the effect.
  80441. * @param options The required width/height ratio to downsize to before computing the render pass.
  80442. * @param camera The camera to apply the render pass to.
  80443. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80444. * @param engine The engine which the post process will be applied. (default: current engine)
  80445. * @param reusable If the post process can be reused on the same frame. (default: false)
  80446. * @param textureType Type of textures used when performing the post process. (default: 0)
  80447. * @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)
  80448. */
  80449. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80450. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80451. if (blockCompilation === void 0) { blockCompilation = false; }
  80452. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80453. /**
  80454. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  80455. */
  80456. _this.colorAmount = 1.0;
  80457. /**
  80458. * How much sharpness should be applied (default: 0.3)
  80459. */
  80460. _this.edgeAmount = 0.3;
  80461. _this.onApply = function (effect) {
  80462. effect.setFloat2("screenSize", _this.width, _this.height);
  80463. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  80464. };
  80465. return _this;
  80466. }
  80467. return SharpenPostProcess;
  80468. }(BABYLON.PostProcess));
  80469. BABYLON.SharpenPostProcess = SharpenPostProcess;
  80470. })(BABYLON || (BABYLON = {}));
  80471. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  80472. var BABYLON;
  80473. (function (BABYLON) {
  80474. /**
  80475. * The Blur Post Process which blurs an image based on a kernel and direction.
  80476. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  80477. */
  80478. var BlurPostProcess = /** @class */ (function (_super) {
  80479. __extends(BlurPostProcess, _super);
  80480. /**
  80481. * Creates a new instance BlurPostProcess
  80482. * @param name The name of the effect.
  80483. * @param direction The direction in which to blur the image.
  80484. * @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.
  80485. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  80486. * @param camera The camera to apply the render pass to.
  80487. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80488. * @param engine The engine which the post process will be applied. (default: current engine)
  80489. * @param reusable If the post process can be reused on the same frame. (default: false)
  80490. * @param textureType Type of textures used when performing the post process. (default: 0)
  80491. * @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)
  80492. */
  80493. function BlurPostProcess(name,
  80494. /** The direction in which to blur the image. */
  80495. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  80496. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80497. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80498. if (defines === void 0) { defines = ""; }
  80499. if (blockCompilation === void 0) { blockCompilation = false; }
  80500. 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;
  80501. _this.direction = direction;
  80502. _this.blockCompilation = blockCompilation;
  80503. _this._packedFloat = false;
  80504. _this._staticDefines = "";
  80505. _this._staticDefines = defines;
  80506. _this.onApplyObservable.add(function (effect) {
  80507. if (_this._outputTexture) {
  80508. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  80509. }
  80510. else {
  80511. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  80512. }
  80513. });
  80514. _this.kernel = kernel;
  80515. return _this;
  80516. }
  80517. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  80518. /**
  80519. * Gets the length in pixels of the blur sample region
  80520. */
  80521. get: function () {
  80522. return this._idealKernel;
  80523. },
  80524. /**
  80525. * Sets the length in pixels of the blur sample region
  80526. */
  80527. set: function (v) {
  80528. if (this._idealKernel === v) {
  80529. return;
  80530. }
  80531. v = Math.max(v, 1);
  80532. this._idealKernel = v;
  80533. this._kernel = this._nearestBestKernel(v);
  80534. if (!this.blockCompilation) {
  80535. this._updateParameters();
  80536. }
  80537. },
  80538. enumerable: true,
  80539. configurable: true
  80540. });
  80541. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  80542. /**
  80543. * Gets wether or not the blur is unpacking/repacking floats
  80544. */
  80545. get: function () {
  80546. return this._packedFloat;
  80547. },
  80548. /**
  80549. * Sets wether or not the blur needs to unpack/repack floats
  80550. */
  80551. set: function (v) {
  80552. if (this._packedFloat === v) {
  80553. return;
  80554. }
  80555. this._packedFloat = v;
  80556. if (!this.blockCompilation) {
  80557. this._updateParameters();
  80558. }
  80559. },
  80560. enumerable: true,
  80561. configurable: true
  80562. });
  80563. /**
  80564. * Updates the effect with the current post process compile time values and recompiles the shader.
  80565. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80566. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80567. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80568. * @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
  80569. * @param onCompiled Called when the shader has been compiled.
  80570. * @param onError Called if there is an error when compiling a shader.
  80571. */
  80572. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80573. if (defines === void 0) { defines = null; }
  80574. if (uniforms === void 0) { uniforms = null; }
  80575. if (samplers === void 0) { samplers = null; }
  80576. this._updateParameters(onCompiled, onError);
  80577. };
  80578. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  80579. // Generate sampling offsets and weights
  80580. var N = this._kernel;
  80581. var centerIndex = (N - 1) / 2;
  80582. // Generate Gaussian sampling weights over kernel
  80583. var offsets = [];
  80584. var weights = [];
  80585. var totalWeight = 0;
  80586. for (var i = 0; i < N; i++) {
  80587. var u = i / (N - 1);
  80588. var w = this._gaussianWeight(u * 2.0 - 1);
  80589. offsets[i] = (i - centerIndex);
  80590. weights[i] = w;
  80591. totalWeight += w;
  80592. }
  80593. // Normalize weights
  80594. for (var i = 0; i < weights.length; i++) {
  80595. weights[i] /= totalWeight;
  80596. }
  80597. // Optimize: combine samples to take advantage of hardware linear sampling
  80598. // Walk from left to center, combining pairs (symmetrically)
  80599. var linearSamplingWeights = [];
  80600. var linearSamplingOffsets = [];
  80601. var linearSamplingMap = [];
  80602. for (var i = 0; i <= centerIndex; i += 2) {
  80603. var j = Math.min(i + 1, Math.floor(centerIndex));
  80604. var singleCenterSample = i === j;
  80605. if (singleCenterSample) {
  80606. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80607. }
  80608. else {
  80609. var sharedCell = j === centerIndex;
  80610. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  80611. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  80612. if (offsetLinear === 0) {
  80613. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80614. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  80615. }
  80616. else {
  80617. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  80618. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  80619. }
  80620. }
  80621. }
  80622. for (var i = 0; i < linearSamplingMap.length; i++) {
  80623. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  80624. linearSamplingWeights[i] = linearSamplingMap[i].w;
  80625. }
  80626. // Replace with optimized
  80627. offsets = linearSamplingOffsets;
  80628. weights = linearSamplingWeights;
  80629. // Generate shaders
  80630. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  80631. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  80632. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  80633. var defines = "";
  80634. defines += this._staticDefines;
  80635. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  80636. if (this._staticDefines.indexOf("DOF") != -1) {
  80637. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  80638. varyingCount--;
  80639. }
  80640. for (var i = 0; i < varyingCount; i++) {
  80641. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  80642. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  80643. }
  80644. var depCount = 0;
  80645. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  80646. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  80647. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  80648. depCount++;
  80649. }
  80650. if (this.packedFloat) {
  80651. defines += "#define PACKEDFLOAT 1";
  80652. }
  80653. this.blockCompilation = false;
  80654. _super.prototype.updateEffect.call(this, defines, null, null, {
  80655. varyingCount: varyingCount,
  80656. depCount: depCount
  80657. }, onCompiled, onError);
  80658. };
  80659. /**
  80660. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  80661. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  80662. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  80663. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  80664. * The gaps between physical kernels are compensated for in the weighting of the samples
  80665. * @param idealKernel Ideal blur kernel.
  80666. * @return Nearest best kernel.
  80667. */
  80668. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  80669. var v = Math.round(idealKernel);
  80670. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  80671. var k = _a[_i];
  80672. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  80673. return Math.max(k, 3);
  80674. }
  80675. }
  80676. return Math.max(v, 3);
  80677. };
  80678. /**
  80679. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  80680. * @param x The point on the Gaussian distribution to sample.
  80681. * @return the value of the Gaussian function at x.
  80682. */
  80683. BlurPostProcess.prototype._gaussianWeight = function (x) {
  80684. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  80685. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  80686. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  80687. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  80688. // truncated at around 1.3% of peak strength.
  80689. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  80690. var sigma = (1 / 3);
  80691. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  80692. var exponent = -((x * x) / (2.0 * sigma * sigma));
  80693. var weight = (1.0 / denominator) * Math.exp(exponent);
  80694. return weight;
  80695. };
  80696. /**
  80697. * Generates a string that can be used as a floating point number in GLSL.
  80698. * @param x Value to print.
  80699. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  80700. * @return GLSL float string.
  80701. */
  80702. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  80703. if (decimalFigures === void 0) { decimalFigures = 8; }
  80704. return x.toFixed(decimalFigures).replace(/0+$/, '');
  80705. };
  80706. return BlurPostProcess;
  80707. }(BABYLON.PostProcess));
  80708. BABYLON.BlurPostProcess = BlurPostProcess;
  80709. })(BABYLON || (BABYLON = {}));
  80710. //# sourceMappingURL=babylon.blurPostProcess.js.map
  80711. var BABYLON;
  80712. (function (BABYLON) {
  80713. /**
  80714. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  80715. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  80716. * based on samples that have a large difference in distance than the center pixel.
  80717. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80718. */
  80719. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  80720. __extends(DepthOfFieldBlurPostProcess, _super);
  80721. /**
  80722. * Creates a new instance CircleOfConfusionPostProcess
  80723. * @param name The name of the effect.
  80724. * @param scene The scene the effect belongs to.
  80725. * @param direction The direction the blur should be applied.
  80726. * @param kernel The size of the kernel used to blur.
  80727. * @param options The required width/height ratio to downsize to before computing the render pass.
  80728. * @param camera The camera to apply the render pass to.
  80729. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  80730. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  80731. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80732. * @param engine The engine which the post process will be applied. (default: current engine)
  80733. * @param reusable If the post process can be reused on the same frame. (default: false)
  80734. * @param textureType Type of textures used when performing the post process. (default: 0)
  80735. * @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)
  80736. */
  80737. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  80738. if (imageToBlur === void 0) { imageToBlur = null; }
  80739. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80740. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80741. if (blockCompilation === void 0) { blockCompilation = false; }
  80742. 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;
  80743. _this.direction = direction;
  80744. _this.onApplyObservable.add(function (effect) {
  80745. if (imageToBlur != null) {
  80746. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  80747. }
  80748. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80749. if (scene.activeCamera) {
  80750. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80751. }
  80752. });
  80753. return _this;
  80754. }
  80755. return DepthOfFieldBlurPostProcess;
  80756. }(BABYLON.BlurPostProcess));
  80757. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  80758. })(BABYLON || (BABYLON = {}));
  80759. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  80760. var BABYLON;
  80761. (function (BABYLON) {
  80762. /**
  80763. * Options to be set when merging outputs from the default pipeline.
  80764. */
  80765. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  80766. function DepthOfFieldMergePostProcessOptions() {
  80767. }
  80768. return DepthOfFieldMergePostProcessOptions;
  80769. }());
  80770. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  80771. /**
  80772. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80773. */
  80774. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  80775. __extends(DepthOfFieldMergePostProcess, _super);
  80776. /**
  80777. * Creates a new instance of DepthOfFieldMergePostProcess
  80778. * @param name The name of the effect.
  80779. * @param originalFromInput Post process which's input will be used for the merge.
  80780. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  80781. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  80782. * @param options The required width/height ratio to downsize to before computing the render pass.
  80783. * @param camera The camera to apply the render pass to.
  80784. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80785. * @param engine The engine which the post process will be applied. (default: current engine)
  80786. * @param reusable If the post process can be reused on the same frame. (default: false)
  80787. * @param textureType Type of textures used when performing the post process. (default: 0)
  80788. * @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)
  80789. */
  80790. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80791. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80792. if (blockCompilation === void 0) { blockCompilation = false; }
  80793. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80794. _this.blurSteps = blurSteps;
  80795. _this.onApplyObservable.add(function (effect) {
  80796. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80797. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80798. blurSteps.forEach(function (step, index) {
  80799. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  80800. });
  80801. });
  80802. if (!blockCompilation) {
  80803. _this.updateEffect();
  80804. }
  80805. return _this;
  80806. }
  80807. /**
  80808. * Updates the effect with the current post process compile time values and recompiles the shader.
  80809. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80810. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80811. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80812. * @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
  80813. * @param onCompiled Called when the shader has been compiled.
  80814. * @param onError Called if there is an error when compiling a shader.
  80815. */
  80816. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80817. if (defines === void 0) { defines = null; }
  80818. if (uniforms === void 0) { uniforms = null; }
  80819. if (samplers === void 0) { samplers = null; }
  80820. if (!defines) {
  80821. defines = "";
  80822. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  80823. }
  80824. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  80825. };
  80826. return DepthOfFieldMergePostProcess;
  80827. }(BABYLON.PostProcess));
  80828. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  80829. })(BABYLON || (BABYLON = {}));
  80830. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  80831. var BABYLON;
  80832. (function (BABYLON) {
  80833. /**
  80834. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  80835. */
  80836. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  80837. __extends(CircleOfConfusionPostProcess, _super);
  80838. /**
  80839. * Creates a new instance CircleOfConfusionPostProcess
  80840. * @param name The name of the effect.
  80841. * @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.
  80842. * @param options The required width/height ratio to downsize to before computing the render pass.
  80843. * @param camera The camera to apply the render pass to.
  80844. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80845. * @param engine The engine which the post process will be applied. (default: current engine)
  80846. * @param reusable If the post process can be reused on the same frame. (default: false)
  80847. * @param textureType Type of textures used when performing the post process. (default: 0)
  80848. * @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)
  80849. */
  80850. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80851. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80852. if (blockCompilation === void 0) { blockCompilation = false; }
  80853. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80854. /**
  80855. * 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.
  80856. */
  80857. _this.lensSize = 50;
  80858. /**
  80859. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80860. */
  80861. _this.fStop = 1.4;
  80862. /**
  80863. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80864. */
  80865. _this.focusDistance = 2000;
  80866. /**
  80867. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  80868. */
  80869. _this.focalLength = 50;
  80870. _this._depthTexture = null;
  80871. _this._depthTexture = depthTexture;
  80872. _this.onApplyObservable.add(function (effect) {
  80873. if (!_this._depthTexture) {
  80874. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  80875. return;
  80876. }
  80877. effect.setTexture("depthSampler", _this._depthTexture);
  80878. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  80879. var aperture = _this.lensSize / _this.fStop;
  80880. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  80881. effect.setFloat('focusDistance', _this.focusDistance);
  80882. effect.setFloat('cocPrecalculation', cocPrecalculation);
  80883. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  80884. });
  80885. return _this;
  80886. }
  80887. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  80888. /**
  80889. * 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.
  80890. */
  80891. set: function (value) {
  80892. this._depthTexture = value;
  80893. },
  80894. enumerable: true,
  80895. configurable: true
  80896. });
  80897. return CircleOfConfusionPostProcess;
  80898. }(BABYLON.PostProcess));
  80899. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  80900. })(BABYLON || (BABYLON = {}));
  80901. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  80902. var BABYLON;
  80903. (function (BABYLON) {
  80904. /**
  80905. * Specifies the level of max blur that should be applied when using the depth of field effect
  80906. */
  80907. var DepthOfFieldEffectBlurLevel;
  80908. (function (DepthOfFieldEffectBlurLevel) {
  80909. /**
  80910. * Subtle blur
  80911. */
  80912. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  80913. /**
  80914. * Medium blur
  80915. */
  80916. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  80917. /**
  80918. * Large blur
  80919. */
  80920. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  80921. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  80922. ;
  80923. /**
  80924. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  80925. */
  80926. var DepthOfFieldEffect = /** @class */ (function (_super) {
  80927. __extends(DepthOfFieldEffect, _super);
  80928. /**
  80929. * Creates a new instance DepthOfFieldEffect
  80930. * @param scene The scene the effect belongs to.
  80931. * @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.
  80932. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80933. * @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)
  80934. */
  80935. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  80936. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  80937. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80938. if (blockCompilation === void 0) { blockCompilation = false; }
  80939. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  80940. return _this._effects;
  80941. }, true) || this;
  80942. /**
  80943. * @hidden Internal post processes in depth of field effect
  80944. */
  80945. _this._effects = [];
  80946. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  80947. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80948. // 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)
  80949. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  80950. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80951. _this._depthOfFieldBlurY = [];
  80952. _this._depthOfFieldBlurX = [];
  80953. var blurCount = 1;
  80954. var kernelSize = 15;
  80955. switch (blurLevel) {
  80956. case DepthOfFieldEffectBlurLevel.High: {
  80957. blurCount = 3;
  80958. kernelSize = 51;
  80959. break;
  80960. }
  80961. case DepthOfFieldEffectBlurLevel.Medium: {
  80962. blurCount = 2;
  80963. kernelSize = 31;
  80964. break;
  80965. }
  80966. default: {
  80967. kernelSize = 15;
  80968. blurCount = 1;
  80969. break;
  80970. }
  80971. }
  80972. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  80973. var ratio = 1.0;
  80974. for (var i = 0; i < blurCount; i++) {
  80975. 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);
  80976. blurY.autoClear = false;
  80977. ratio = 0.75 / Math.pow(2, i);
  80978. 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);
  80979. blurX.autoClear = false;
  80980. _this._depthOfFieldBlurY.push(blurY);
  80981. _this._depthOfFieldBlurX.push(blurX);
  80982. }
  80983. // Set all post processes on the effect.
  80984. _this._effects = [_this._circleOfConfusion];
  80985. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  80986. _this._effects.push(_this._depthOfFieldBlurY[i]);
  80987. _this._effects.push(_this._depthOfFieldBlurX[i]);
  80988. }
  80989. // Merge blurred images with original image based on circleOfConfusion
  80990. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80991. _this._dofMerge.autoClear = false;
  80992. _this._effects.push(_this._dofMerge);
  80993. return _this;
  80994. }
  80995. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  80996. get: function () {
  80997. return this._circleOfConfusion.focalLength;
  80998. },
  80999. /**
  81000. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  81001. */
  81002. set: function (value) {
  81003. this._circleOfConfusion.focalLength = value;
  81004. },
  81005. enumerable: true,
  81006. configurable: true
  81007. });
  81008. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  81009. get: function () {
  81010. return this._circleOfConfusion.fStop;
  81011. },
  81012. /**
  81013. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  81014. */
  81015. set: function (value) {
  81016. this._circleOfConfusion.fStop = value;
  81017. },
  81018. enumerable: true,
  81019. configurable: true
  81020. });
  81021. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  81022. get: function () {
  81023. return this._circleOfConfusion.focusDistance;
  81024. },
  81025. /**
  81026. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  81027. */
  81028. set: function (value) {
  81029. this._circleOfConfusion.focusDistance = value;
  81030. },
  81031. enumerable: true,
  81032. configurable: true
  81033. });
  81034. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  81035. get: function () {
  81036. return this._circleOfConfusion.lensSize;
  81037. },
  81038. /**
  81039. * 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.
  81040. */
  81041. set: function (value) {
  81042. this._circleOfConfusion.lensSize = value;
  81043. },
  81044. enumerable: true,
  81045. configurable: true
  81046. });
  81047. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  81048. /**
  81049. * 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.
  81050. */
  81051. set: function (value) {
  81052. this._circleOfConfusion.depthTexture = value;
  81053. },
  81054. enumerable: true,
  81055. configurable: true
  81056. });
  81057. /**
  81058. * Disposes each of the internal effects for a given camera.
  81059. * @param camera The camera to dispose the effect on.
  81060. */
  81061. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  81062. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81063. this._effects[effectIndex].dispose(camera);
  81064. }
  81065. };
  81066. /**
  81067. * @hidden Internal
  81068. */
  81069. DepthOfFieldEffect.prototype._updateEffects = function () {
  81070. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81071. this._effects[effectIndex].updateEffect();
  81072. }
  81073. };
  81074. /**
  81075. * Internal
  81076. * @returns if all the contained post processes are ready.
  81077. * @hidden
  81078. */
  81079. DepthOfFieldEffect.prototype._isReady = function () {
  81080. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81081. if (!this._effects[effectIndex].isReady()) {
  81082. return false;
  81083. }
  81084. }
  81085. return true;
  81086. };
  81087. return DepthOfFieldEffect;
  81088. }(BABYLON.PostProcessRenderEffect));
  81089. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  81090. })(BABYLON || (BABYLON = {}));
  81091. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  81092. var BABYLON;
  81093. (function (BABYLON) {
  81094. /**
  81095. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  81096. */
  81097. var BloomMergePostProcess = /** @class */ (function (_super) {
  81098. __extends(BloomMergePostProcess, _super);
  81099. /**
  81100. * Creates a new instance of @see BloomMergePostProcess
  81101. * @param name The name of the effect.
  81102. * @param originalFromInput Post process which's input will be used for the merge.
  81103. * @param blurred Blurred highlights post process which's output will be used.
  81104. * @param weight Weight of the bloom to be added to the original input.
  81105. * @param options The required width/height ratio to downsize to before computing the render pass.
  81106. * @param camera The camera to apply the render pass to.
  81107. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81108. * @param engine The engine which the post process will be applied. (default: current engine)
  81109. * @param reusable If the post process can be reused on the same frame. (default: false)
  81110. * @param textureType Type of textures used when performing the post process. (default: 0)
  81111. * @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)
  81112. */
  81113. function BloomMergePostProcess(name, originalFromInput, blurred,
  81114. /** Weight of the bloom to be added to the original input. */
  81115. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81116. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81117. if (blockCompilation === void 0) { blockCompilation = false; }
  81118. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  81119. _this.weight = weight;
  81120. _this.onApplyObservable.add(function (effect) {
  81121. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  81122. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  81123. effect.setFloat("bloomWeight", _this.weight);
  81124. });
  81125. if (!blockCompilation) {
  81126. _this.updateEffect();
  81127. }
  81128. return _this;
  81129. }
  81130. return BloomMergePostProcess;
  81131. }(BABYLON.PostProcess));
  81132. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  81133. })(BABYLON || (BABYLON = {}));
  81134. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  81135. var BABYLON;
  81136. (function (BABYLON) {
  81137. /**
  81138. * 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.
  81139. */
  81140. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  81141. __extends(ExtractHighlightsPostProcess, _super);
  81142. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81143. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81144. if (blockCompilation === void 0) { blockCompilation = false; }
  81145. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  81146. /**
  81147. * The luminance threshold, pixels below this value will be set to black.
  81148. */
  81149. _this.threshold = 0.9;
  81150. /** @hidden */
  81151. _this._exposure = 1;
  81152. /**
  81153. * Post process which has the input texture to be used when performing highlight extraction
  81154. * @hidden
  81155. */
  81156. _this._inputPostProcess = null;
  81157. _this.onApplyObservable.add(function (effect) {
  81158. if (_this._inputPostProcess) {
  81159. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  81160. }
  81161. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  81162. effect.setFloat('exposure', _this._exposure);
  81163. });
  81164. return _this;
  81165. }
  81166. return ExtractHighlightsPostProcess;
  81167. }(BABYLON.PostProcess));
  81168. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  81169. })(BABYLON || (BABYLON = {}));
  81170. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  81171. var BABYLON;
  81172. (function (BABYLON) {
  81173. /**
  81174. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  81175. */
  81176. var BloomEffect = /** @class */ (function (_super) {
  81177. __extends(BloomEffect, _super);
  81178. /**
  81179. * Creates a new instance of @see BloomEffect
  81180. * @param scene The scene the effect belongs to.
  81181. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  81182. * @param bloomKernel The size of the kernel to be used when applying the blur.
  81183. * @param bloomWeight The the strength of bloom.
  81184. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  81185. * @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)
  81186. */
  81187. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  81188. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  81189. if (blockCompilation === void 0) { blockCompilation = false; }
  81190. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  81191. return _this._effects;
  81192. }, true) || this;
  81193. _this.bloomScale = bloomScale;
  81194. /**
  81195. * @hidden Internal
  81196. */
  81197. _this._effects = [];
  81198. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81199. _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);
  81200. _this._blurX.alwaysForcePOT = true;
  81201. _this._blurX.autoClear = false;
  81202. _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);
  81203. _this._blurY.alwaysForcePOT = true;
  81204. _this._blurY.autoClear = false;
  81205. _this.kernel = bloomKernel;
  81206. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  81207. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81208. _this._merge.autoClear = false;
  81209. _this._effects.push(_this._merge);
  81210. return _this;
  81211. }
  81212. Object.defineProperty(BloomEffect.prototype, "threshold", {
  81213. /**
  81214. * The luminance threshold to find bright areas of the image to bloom.
  81215. */
  81216. get: function () {
  81217. return this._downscale.threshold;
  81218. },
  81219. set: function (value) {
  81220. this._downscale.threshold = value;
  81221. },
  81222. enumerable: true,
  81223. configurable: true
  81224. });
  81225. Object.defineProperty(BloomEffect.prototype, "weight", {
  81226. /**
  81227. * The strength of the bloom.
  81228. */
  81229. get: function () {
  81230. return this._merge.weight;
  81231. },
  81232. set: function (value) {
  81233. this._merge.weight = value;
  81234. },
  81235. enumerable: true,
  81236. configurable: true
  81237. });
  81238. Object.defineProperty(BloomEffect.prototype, "kernel", {
  81239. /**
  81240. * Specifies the size of the bloom blur kernel, relative to the final output size
  81241. */
  81242. get: function () {
  81243. return this._blurX.kernel / this.bloomScale;
  81244. },
  81245. set: function (value) {
  81246. this._blurX.kernel = value * this.bloomScale;
  81247. this._blurY.kernel = value * this.bloomScale;
  81248. },
  81249. enumerable: true,
  81250. configurable: true
  81251. });
  81252. /**
  81253. * Disposes each of the internal effects for a given camera.
  81254. * @param camera The camera to dispose the effect on.
  81255. */
  81256. BloomEffect.prototype.disposeEffects = function (camera) {
  81257. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81258. this._effects[effectIndex].dispose(camera);
  81259. }
  81260. };
  81261. /**
  81262. * @hidden Internal
  81263. */
  81264. BloomEffect.prototype._updateEffects = function () {
  81265. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81266. this._effects[effectIndex].updateEffect();
  81267. }
  81268. };
  81269. /**
  81270. * Internal
  81271. * @returns if all the contained post processes are ready.
  81272. * @hidden
  81273. */
  81274. BloomEffect.prototype._isReady = function () {
  81275. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81276. if (!this._effects[effectIndex].isReady()) {
  81277. return false;
  81278. }
  81279. }
  81280. return true;
  81281. };
  81282. return BloomEffect;
  81283. }(BABYLON.PostProcessRenderEffect));
  81284. BABYLON.BloomEffect = BloomEffect;
  81285. })(BABYLON || (BABYLON = {}));
  81286. //# sourceMappingURL=babylon.bloomEffect.js.map
  81287. var BABYLON;
  81288. (function (BABYLON) {
  81289. /**
  81290. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  81291. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  81292. */
  81293. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  81294. __extends(DefaultRenderingPipeline, _super);
  81295. /**
  81296. * @constructor
  81297. * @param {string} name - The rendering pipeline name (default: "")
  81298. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  81299. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  81300. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  81301. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  81302. */
  81303. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  81304. if (name === void 0) { name = ""; }
  81305. if (hdr === void 0) { hdr = true; }
  81306. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  81307. if (automaticBuild === void 0) { automaticBuild = true; }
  81308. var _this = _super.call(this, scene.getEngine(), name) || this;
  81309. _this._camerasToBeAttached = [];
  81310. /**
  81311. * ID of the sharpen post process,
  81312. */
  81313. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  81314. /**
  81315. * ID of the image processing post process;
  81316. */
  81317. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  81318. /**
  81319. * ID of the Fast Approximate Anti-Aliasing post process;
  81320. */
  81321. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  81322. /**
  81323. * ID of the chromatic aberration post process,
  81324. */
  81325. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  81326. /**
  81327. * ID of the grain post process
  81328. */
  81329. _this.GrainPostProcessId = "GrainPostProcessEffect";
  81330. /**
  81331. * Glow post process which adds a glow to emmisive areas of the image
  81332. */
  81333. _this._glowLayer = null;
  81334. /**
  81335. * Animations which can be used to tweak settings over a period of time
  81336. */
  81337. _this.animations = [];
  81338. _this._imageProcessingConfigurationObserver = null;
  81339. // Values
  81340. _this._sharpenEnabled = false;
  81341. _this._bloomEnabled = false;
  81342. _this._depthOfFieldEnabled = false;
  81343. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  81344. _this._fxaaEnabled = false;
  81345. _this._imageProcessingEnabled = true;
  81346. _this._bloomScale = 0.5;
  81347. _this._chromaticAberrationEnabled = false;
  81348. _this._grainEnabled = false;
  81349. _this._buildAllowed = true;
  81350. _this._resizeObserver = null;
  81351. _this._hardwareScaleLevel = 1.0;
  81352. _this._bloomKernel = 64;
  81353. /**
  81354. * Specifies the weight of the bloom in the final rendering
  81355. */
  81356. _this._bloomWeight = 0.15;
  81357. /**
  81358. * Specifies the luma threshold for the area that will be blurred by the bloom
  81359. */
  81360. _this._bloomThreshold = 0.9;
  81361. _this._samples = 1;
  81362. _this._hasCleared = false;
  81363. _this._prevPostProcess = null;
  81364. _this._prevPrevPostProcess = null;
  81365. _this._depthOfFieldSceneObserver = null;
  81366. _this._cameras = cameras || scene.cameras;
  81367. _this._cameras = _this._cameras.slice();
  81368. _this._camerasToBeAttached = _this._cameras.slice();
  81369. _this._buildAllowed = automaticBuild;
  81370. // Initialize
  81371. _this._scene = scene;
  81372. var caps = _this._scene.getEngine().getCaps();
  81373. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  81374. // Misc
  81375. if (_this._hdr) {
  81376. if (caps.textureHalfFloatRender) {
  81377. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81378. }
  81379. else if (caps.textureFloatRender) {
  81380. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81381. }
  81382. }
  81383. else {
  81384. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81385. }
  81386. // Attach
  81387. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81388. var engine = _this._scene.getEngine();
  81389. // Create post processes before hand so they can be modified before enabled.
  81390. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  81391. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81392. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  81393. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  81394. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  81395. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81396. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  81397. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81398. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  81399. _this._resizeObserver = engine.onResizeObservable.add(function () {
  81400. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  81401. _this.bloomKernel = _this.bloomKernel;
  81402. });
  81403. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  81404. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  81405. });
  81406. _this._buildPipeline();
  81407. return _this;
  81408. }
  81409. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  81410. get: function () {
  81411. return this._sharpenEnabled;
  81412. },
  81413. /**
  81414. * Enable or disable the sharpen process from the pipeline
  81415. */
  81416. set: function (enabled) {
  81417. if (this._sharpenEnabled === enabled) {
  81418. return;
  81419. }
  81420. this._sharpenEnabled = enabled;
  81421. this._buildPipeline();
  81422. },
  81423. enumerable: true,
  81424. configurable: true
  81425. });
  81426. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  81427. /**
  81428. * Specifies the size of the bloom blur kernel, relative to the final output size
  81429. */
  81430. get: function () {
  81431. return this._bloomKernel;
  81432. },
  81433. set: function (value) {
  81434. this._bloomKernel = value;
  81435. this.bloom.kernel = value / this._hardwareScaleLevel;
  81436. },
  81437. enumerable: true,
  81438. configurable: true
  81439. });
  81440. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  81441. get: function () {
  81442. return this._bloomWeight;
  81443. },
  81444. /**
  81445. * The strength of the bloom.
  81446. */
  81447. set: function (value) {
  81448. if (this._bloomWeight === value) {
  81449. return;
  81450. }
  81451. this.bloom.weight = value;
  81452. this._bloomWeight = value;
  81453. },
  81454. enumerable: true,
  81455. configurable: true
  81456. });
  81457. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  81458. get: function () {
  81459. return this._bloomThreshold;
  81460. },
  81461. /**
  81462. * The strength of the bloom.
  81463. */
  81464. set: function (value) {
  81465. if (this._bloomThreshold === value) {
  81466. return;
  81467. }
  81468. this.bloom.threshold = value;
  81469. this._bloomThreshold = value;
  81470. },
  81471. enumerable: true,
  81472. configurable: true
  81473. });
  81474. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  81475. get: function () {
  81476. return this._bloomScale;
  81477. },
  81478. /**
  81479. * The scale of the bloom, lower value will provide better performance.
  81480. */
  81481. set: function (value) {
  81482. if (this._bloomScale === value) {
  81483. return;
  81484. }
  81485. this._bloomScale = value;
  81486. // recreate bloom and dispose old as this setting is not dynamic
  81487. this._rebuildBloom();
  81488. this._buildPipeline();
  81489. },
  81490. enumerable: true,
  81491. configurable: true
  81492. });
  81493. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  81494. get: function () {
  81495. return this._bloomEnabled;
  81496. },
  81497. /**
  81498. * Enable or disable the bloom from the pipeline
  81499. */
  81500. set: function (enabled) {
  81501. if (this._bloomEnabled === enabled) {
  81502. return;
  81503. }
  81504. this._bloomEnabled = enabled;
  81505. this._buildPipeline();
  81506. },
  81507. enumerable: true,
  81508. configurable: true
  81509. });
  81510. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  81511. // recreate bloom and dispose old as this setting is not dynamic
  81512. var oldBloom = this.bloom;
  81513. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  81514. this.bloom.threshold = oldBloom.threshold;
  81515. for (var i = 0; i < this._cameras.length; i++) {
  81516. oldBloom.disposeEffects(this._cameras[i]);
  81517. }
  81518. };
  81519. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  81520. /**
  81521. * If the depth of field is enabled.
  81522. */
  81523. get: function () {
  81524. return this._depthOfFieldEnabled;
  81525. },
  81526. set: function (enabled) {
  81527. if (this._depthOfFieldEnabled === enabled) {
  81528. return;
  81529. }
  81530. this._depthOfFieldEnabled = enabled;
  81531. this._buildPipeline();
  81532. },
  81533. enumerable: true,
  81534. configurable: true
  81535. });
  81536. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  81537. /**
  81538. * Blur level of the depth of field effect. (Higher blur will effect performance)
  81539. */
  81540. get: function () {
  81541. return this._depthOfFieldBlurLevel;
  81542. },
  81543. set: function (value) {
  81544. if (this._depthOfFieldBlurLevel === value) {
  81545. return;
  81546. }
  81547. this._depthOfFieldBlurLevel = value;
  81548. // recreate dof and dispose old as this setting is not dynamic
  81549. var oldDof = this.depthOfField;
  81550. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  81551. this.depthOfField.focalLength = oldDof.focalLength;
  81552. this.depthOfField.focusDistance = oldDof.focusDistance;
  81553. this.depthOfField.fStop = oldDof.fStop;
  81554. this.depthOfField.lensSize = oldDof.lensSize;
  81555. for (var i = 0; i < this._cameras.length; i++) {
  81556. oldDof.disposeEffects(this._cameras[i]);
  81557. }
  81558. this._buildPipeline();
  81559. },
  81560. enumerable: true,
  81561. configurable: true
  81562. });
  81563. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  81564. get: function () {
  81565. return this._fxaaEnabled;
  81566. },
  81567. /**
  81568. * If the anti aliasing is enabled.
  81569. */
  81570. set: function (enabled) {
  81571. if (this._fxaaEnabled === enabled) {
  81572. return;
  81573. }
  81574. this._fxaaEnabled = enabled;
  81575. this._buildPipeline();
  81576. },
  81577. enumerable: true,
  81578. configurable: true
  81579. });
  81580. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  81581. get: function () {
  81582. return this._samples;
  81583. },
  81584. /**
  81585. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81586. */
  81587. set: function (sampleCount) {
  81588. if (this._samples === sampleCount) {
  81589. return;
  81590. }
  81591. this._samples = sampleCount;
  81592. this._buildPipeline();
  81593. },
  81594. enumerable: true,
  81595. configurable: true
  81596. });
  81597. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  81598. get: function () {
  81599. return this._imageProcessingEnabled;
  81600. },
  81601. /**
  81602. * If image processing is enabled.
  81603. */
  81604. set: function (enabled) {
  81605. if (this._imageProcessingEnabled === enabled) {
  81606. return;
  81607. }
  81608. this._imageProcessingEnabled = enabled;
  81609. this._buildPipeline();
  81610. },
  81611. enumerable: true,
  81612. configurable: true
  81613. });
  81614. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  81615. get: function () {
  81616. return this._glowLayer == null;
  81617. },
  81618. /**
  81619. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  81620. */
  81621. set: function (enabled) {
  81622. if (enabled && !this._glowLayer) {
  81623. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  81624. }
  81625. else if (!enabled && this._glowLayer) {
  81626. this._glowLayer.dispose();
  81627. this._glowLayer = null;
  81628. }
  81629. },
  81630. enumerable: true,
  81631. configurable: true
  81632. });
  81633. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  81634. get: function () {
  81635. return this._chromaticAberrationEnabled;
  81636. },
  81637. /**
  81638. * Enable or disable the chromaticAberration process from the pipeline
  81639. */
  81640. set: function (enabled) {
  81641. if (this._chromaticAberrationEnabled === enabled) {
  81642. return;
  81643. }
  81644. this._chromaticAberrationEnabled = enabled;
  81645. this._buildPipeline();
  81646. },
  81647. enumerable: true,
  81648. configurable: true
  81649. });
  81650. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  81651. get: function () {
  81652. return this._grainEnabled;
  81653. },
  81654. /**
  81655. * Enable or disable the grain process from the pipeline
  81656. */
  81657. set: function (enabled) {
  81658. if (this._grainEnabled === enabled) {
  81659. return;
  81660. }
  81661. this._grainEnabled = enabled;
  81662. this._buildPipeline();
  81663. },
  81664. enumerable: true,
  81665. configurable: true
  81666. });
  81667. /**
  81668. * Force the compilation of the entire pipeline.
  81669. */
  81670. DefaultRenderingPipeline.prototype.prepare = function () {
  81671. var previousState = this._buildAllowed;
  81672. this._buildAllowed = true;
  81673. this._buildPipeline();
  81674. this._buildAllowed = previousState;
  81675. };
  81676. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  81677. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  81678. if (this._hasCleared) {
  81679. postProcess.autoClear = false;
  81680. }
  81681. else {
  81682. postProcess.autoClear = true;
  81683. this._scene.autoClear = false;
  81684. this._hasCleared = true;
  81685. }
  81686. if (!skipTextureSharing) {
  81687. if (this._prevPrevPostProcess) {
  81688. postProcess.shareOutputWith(this._prevPrevPostProcess);
  81689. }
  81690. else {
  81691. postProcess.useOwnOutput();
  81692. }
  81693. if (this._prevPostProcess) {
  81694. this._prevPrevPostProcess = this._prevPostProcess;
  81695. }
  81696. this._prevPostProcess = postProcess;
  81697. }
  81698. };
  81699. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  81700. var _this = this;
  81701. if (!this._buildAllowed) {
  81702. return;
  81703. }
  81704. this._scene.autoClear = true;
  81705. var engine = this._scene.getEngine();
  81706. this._disposePostProcesses();
  81707. if (this._cameras !== null) {
  81708. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81709. // get back cameras to be used to reattach pipeline
  81710. this._cameras = this._camerasToBeAttached.slice();
  81711. }
  81712. this._reset();
  81713. this._prevPostProcess = null;
  81714. this._prevPrevPostProcess = null;
  81715. this._hasCleared = false;
  81716. if (this.depthOfFieldEnabled) {
  81717. // Multi camera suport
  81718. if (this._cameras.length > 1) {
  81719. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  81720. var camera = _a[_i];
  81721. var depthRenderer = this._scene.enableDepthRenderer(camera);
  81722. depthRenderer.useOnlyInActiveCamera = true;
  81723. }
  81724. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  81725. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  81726. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  81727. }
  81728. });
  81729. }
  81730. else {
  81731. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81732. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  81733. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  81734. }
  81735. if (!this.depthOfField._isReady()) {
  81736. this.depthOfField._updateEffects();
  81737. }
  81738. this.addEffect(this.depthOfField);
  81739. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  81740. }
  81741. else {
  81742. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81743. }
  81744. if (this.bloomEnabled) {
  81745. if (!this.bloom._isReady()) {
  81746. this.bloom._updateEffects();
  81747. }
  81748. this.addEffect(this.bloom);
  81749. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  81750. }
  81751. if (this._imageProcessingEnabled) {
  81752. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81753. if (this._hdr) {
  81754. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  81755. this._setAutoClearAndTextureSharing(this.imageProcessing);
  81756. }
  81757. else {
  81758. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  81759. }
  81760. }
  81761. if (this.sharpenEnabled) {
  81762. if (!this.sharpen.isReady()) {
  81763. this.sharpen.updateEffect();
  81764. }
  81765. this.addEffect(this._sharpenEffect);
  81766. this._setAutoClearAndTextureSharing(this.sharpen);
  81767. }
  81768. if (this.grainEnabled) {
  81769. if (!this.grain.isReady()) {
  81770. this.grain.updateEffect();
  81771. }
  81772. this.addEffect(this._grainEffect);
  81773. this._setAutoClearAndTextureSharing(this.grain);
  81774. }
  81775. if (this.chromaticAberrationEnabled) {
  81776. if (!this.chromaticAberration.isReady()) {
  81777. this.chromaticAberration.updateEffect();
  81778. }
  81779. this.addEffect(this._chromaticAberrationEffect);
  81780. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  81781. }
  81782. if (this.fxaaEnabled) {
  81783. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81784. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  81785. this._setAutoClearAndTextureSharing(this.fxaa, true);
  81786. }
  81787. if (this._cameras !== null) {
  81788. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81789. }
  81790. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  81791. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81792. }
  81793. };
  81794. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  81795. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  81796. for (var i = 0; i < this._cameras.length; i++) {
  81797. var camera = this._cameras[i];
  81798. if (this.imageProcessing) {
  81799. this.imageProcessing.dispose(camera);
  81800. }
  81801. if (this.fxaa) {
  81802. this.fxaa.dispose(camera);
  81803. }
  81804. // These are created in the constructor and should not be disposed on every pipeline change
  81805. if (disposeNonRecreated) {
  81806. if (this.sharpen) {
  81807. this.sharpen.dispose(camera);
  81808. }
  81809. if (this.depthOfField) {
  81810. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81811. this.depthOfField.disposeEffects(camera);
  81812. }
  81813. if (this.bloom) {
  81814. this.bloom.disposeEffects(camera);
  81815. }
  81816. if (this.chromaticAberration) {
  81817. this.chromaticAberration.dispose(camera);
  81818. }
  81819. if (this.grain) {
  81820. this.grain.dispose(camera);
  81821. }
  81822. if (this._glowLayer) {
  81823. this._glowLayer.dispose();
  81824. }
  81825. }
  81826. }
  81827. this.imageProcessing = null;
  81828. this.fxaa = null;
  81829. if (disposeNonRecreated) {
  81830. this.sharpen = null;
  81831. this._sharpenEffect = null;
  81832. this.depthOfField = null;
  81833. this.bloom = null;
  81834. this.chromaticAberration = null;
  81835. this._chromaticAberrationEffect = null;
  81836. this.grain = null;
  81837. this._grainEffect = null;
  81838. this._glowLayer = null;
  81839. }
  81840. };
  81841. /**
  81842. * Adds a camera to the pipeline
  81843. * @param camera the camera to be added
  81844. */
  81845. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  81846. this._camerasToBeAttached.push(camera);
  81847. this._buildPipeline();
  81848. };
  81849. /**
  81850. * Removes a camera from the pipeline
  81851. * @param camera the camera to remove
  81852. */
  81853. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  81854. var index = this._camerasToBeAttached.indexOf(camera);
  81855. this._camerasToBeAttached.splice(index, 1);
  81856. this._buildPipeline();
  81857. };
  81858. /**
  81859. * Dispose of the pipeline and stop all post processes
  81860. */
  81861. DefaultRenderingPipeline.prototype.dispose = function () {
  81862. this._disposePostProcesses(true);
  81863. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81864. this._scene.autoClear = true;
  81865. if (this._resizeObserver) {
  81866. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  81867. this._resizeObserver = null;
  81868. }
  81869. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  81870. _super.prototype.dispose.call(this);
  81871. };
  81872. /**
  81873. * Serialize the rendering pipeline (Used when exporting)
  81874. * @returns the serialized object
  81875. */
  81876. DefaultRenderingPipeline.prototype.serialize = function () {
  81877. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81878. serializationObject.customType = "DefaultRenderingPipeline";
  81879. return serializationObject;
  81880. };
  81881. /**
  81882. * Parse the serialized pipeline
  81883. * @param source Source pipeline.
  81884. * @param scene The scene to load the pipeline to.
  81885. * @param rootUrl The URL of the serialized pipeline.
  81886. * @returns An instantiated pipeline from the serialized object.
  81887. */
  81888. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81889. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  81890. };
  81891. __decorate([
  81892. BABYLON.serialize()
  81893. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  81894. __decorate([
  81895. BABYLON.serialize()
  81896. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  81897. __decorate([
  81898. BABYLON.serialize()
  81899. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  81900. __decorate([
  81901. BABYLON.serialize()
  81902. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  81903. __decorate([
  81904. BABYLON.serialize()
  81905. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  81906. __decorate([
  81907. BABYLON.serialize()
  81908. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  81909. __decorate([
  81910. BABYLON.serialize()
  81911. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  81912. __decorate([
  81913. BABYLON.serialize()
  81914. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  81915. __decorate([
  81916. BABYLON.serialize()
  81917. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  81918. __decorate([
  81919. BABYLON.serialize()
  81920. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  81921. __decorate([
  81922. BABYLON.serialize()
  81923. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  81924. __decorate([
  81925. BABYLON.serialize()
  81926. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  81927. __decorate([
  81928. BABYLON.serialize()
  81929. ], DefaultRenderingPipeline.prototype, "samples", null);
  81930. __decorate([
  81931. BABYLON.serialize()
  81932. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  81933. __decorate([
  81934. BABYLON.serialize()
  81935. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  81936. __decorate([
  81937. BABYLON.serialize()
  81938. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  81939. __decorate([
  81940. BABYLON.serialize()
  81941. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  81942. return DefaultRenderingPipeline;
  81943. }(BABYLON.PostProcessRenderPipeline));
  81944. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  81945. })(BABYLON || (BABYLON = {}));
  81946. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  81947. var BABYLON;
  81948. (function (BABYLON) {
  81949. /**
  81950. * @hidden
  81951. */
  81952. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  81953. __extends(ImageProcessingConfigurationDefines, _super);
  81954. function ImageProcessingConfigurationDefines() {
  81955. var _this = _super.call(this) || this;
  81956. _this.IMAGEPROCESSING = false;
  81957. _this.VIGNETTE = false;
  81958. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  81959. _this.VIGNETTEBLENDMODEOPAQUE = false;
  81960. _this.TONEMAPPING = false;
  81961. _this.TONEMAPPING_ACES = false;
  81962. _this.CONTRAST = false;
  81963. _this.COLORCURVES = false;
  81964. _this.COLORGRADING = false;
  81965. _this.COLORGRADING3D = false;
  81966. _this.SAMPLER3DGREENDEPTH = false;
  81967. _this.SAMPLER3DBGRMAP = false;
  81968. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  81969. _this.EXPOSURE = false;
  81970. _this.rebuild();
  81971. return _this;
  81972. }
  81973. return ImageProcessingConfigurationDefines;
  81974. }(BABYLON.MaterialDefines));
  81975. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  81976. /**
  81977. * This groups together the common properties used for image processing either in direct forward pass
  81978. * or through post processing effect depending on the use of the image processing pipeline in your scene
  81979. * or not.
  81980. */
  81981. var ImageProcessingConfiguration = /** @class */ (function () {
  81982. function ImageProcessingConfiguration() {
  81983. /**
  81984. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  81985. */
  81986. this.colorCurves = new BABYLON.ColorCurves();
  81987. this._colorCurvesEnabled = false;
  81988. this._colorGradingEnabled = false;
  81989. this._colorGradingWithGreenDepth = true;
  81990. this._colorGradingBGR = true;
  81991. /** @hidden */
  81992. this._exposure = 1.0;
  81993. this._toneMappingEnabled = false;
  81994. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  81995. this._contrast = 1.0;
  81996. /**
  81997. * Vignette stretch size.
  81998. */
  81999. this.vignetteStretch = 0;
  82000. /**
  82001. * Vignette centre X Offset.
  82002. */
  82003. this.vignetteCentreX = 0;
  82004. /**
  82005. * Vignette centre Y Offset.
  82006. */
  82007. this.vignetteCentreY = 0;
  82008. /**
  82009. * Vignette weight or intensity of the vignette effect.
  82010. */
  82011. this.vignetteWeight = 1.5;
  82012. /**
  82013. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82014. * if vignetteEnabled is set to true.
  82015. */
  82016. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82017. /**
  82018. * Camera field of view used by the Vignette effect.
  82019. */
  82020. this.vignetteCameraFov = 0.5;
  82021. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  82022. this._vignetteEnabled = false;
  82023. this._applyByPostProcess = false;
  82024. this._isEnabled = true;
  82025. /**
  82026. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  82027. */
  82028. this.onUpdateParameters = new BABYLON.Observable();
  82029. }
  82030. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  82031. /**
  82032. * Gets wether the color curves effect is enabled.
  82033. */
  82034. get: function () {
  82035. return this._colorCurvesEnabled;
  82036. },
  82037. /**
  82038. * Sets wether the color curves effect is enabled.
  82039. */
  82040. set: function (value) {
  82041. if (this._colorCurvesEnabled === value) {
  82042. return;
  82043. }
  82044. this._colorCurvesEnabled = value;
  82045. this._updateParameters();
  82046. },
  82047. enumerable: true,
  82048. configurable: true
  82049. });
  82050. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  82051. /**
  82052. * Gets wether the color grading effect is enabled.
  82053. */
  82054. get: function () {
  82055. return this._colorGradingEnabled;
  82056. },
  82057. /**
  82058. * Sets wether the color grading effect is enabled.
  82059. */
  82060. set: function (value) {
  82061. if (this._colorGradingEnabled === value) {
  82062. return;
  82063. }
  82064. this._colorGradingEnabled = value;
  82065. this._updateParameters();
  82066. },
  82067. enumerable: true,
  82068. configurable: true
  82069. });
  82070. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  82071. /**
  82072. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  82073. */
  82074. get: function () {
  82075. return this._colorGradingWithGreenDepth;
  82076. },
  82077. /**
  82078. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  82079. */
  82080. set: function (value) {
  82081. if (this._colorGradingWithGreenDepth === value) {
  82082. return;
  82083. }
  82084. this._colorGradingWithGreenDepth = value;
  82085. this._updateParameters();
  82086. },
  82087. enumerable: true,
  82088. configurable: true
  82089. });
  82090. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  82091. /**
  82092. * Gets wether the color grading texture contains BGR values.
  82093. */
  82094. get: function () {
  82095. return this._colorGradingBGR;
  82096. },
  82097. /**
  82098. * Sets wether the color grading texture contains BGR values.
  82099. */
  82100. set: function (value) {
  82101. if (this._colorGradingBGR === value) {
  82102. return;
  82103. }
  82104. this._colorGradingBGR = value;
  82105. this._updateParameters();
  82106. },
  82107. enumerable: true,
  82108. configurable: true
  82109. });
  82110. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  82111. /**
  82112. * Gets the Exposure used in the effect.
  82113. */
  82114. get: function () {
  82115. return this._exposure;
  82116. },
  82117. /**
  82118. * Sets the Exposure used in the effect.
  82119. */
  82120. set: function (value) {
  82121. if (this._exposure === value) {
  82122. return;
  82123. }
  82124. this._exposure = value;
  82125. this._updateParameters();
  82126. },
  82127. enumerable: true,
  82128. configurable: true
  82129. });
  82130. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  82131. /**
  82132. * Gets wether the tone mapping effect is enabled.
  82133. */
  82134. get: function () {
  82135. return this._toneMappingEnabled;
  82136. },
  82137. /**
  82138. * Sets wether the tone mapping effect is enabled.
  82139. */
  82140. set: function (value) {
  82141. if (this._toneMappingEnabled === value) {
  82142. return;
  82143. }
  82144. this._toneMappingEnabled = value;
  82145. this._updateParameters();
  82146. },
  82147. enumerable: true,
  82148. configurable: true
  82149. });
  82150. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  82151. /**
  82152. * Gets the type of tone mapping effect.
  82153. */
  82154. get: function () {
  82155. return this._toneMappingType;
  82156. },
  82157. /**
  82158. * Sets the type of tone mapping effect used in BabylonJS.
  82159. */
  82160. set: function (value) {
  82161. if (this._toneMappingType === value) {
  82162. return;
  82163. }
  82164. this._toneMappingType = value;
  82165. this._updateParameters();
  82166. },
  82167. enumerable: true,
  82168. configurable: true
  82169. });
  82170. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  82171. /**
  82172. * Gets the contrast used in the effect.
  82173. */
  82174. get: function () {
  82175. return this._contrast;
  82176. },
  82177. /**
  82178. * Sets the contrast used in the effect.
  82179. */
  82180. set: function (value) {
  82181. if (this._contrast === value) {
  82182. return;
  82183. }
  82184. this._contrast = value;
  82185. this._updateParameters();
  82186. },
  82187. enumerable: true,
  82188. configurable: true
  82189. });
  82190. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  82191. /**
  82192. * Gets the vignette blend mode allowing different kind of effect.
  82193. */
  82194. get: function () {
  82195. return this._vignetteBlendMode;
  82196. },
  82197. /**
  82198. * Sets the vignette blend mode allowing different kind of effect.
  82199. */
  82200. set: function (value) {
  82201. if (this._vignetteBlendMode === value) {
  82202. return;
  82203. }
  82204. this._vignetteBlendMode = value;
  82205. this._updateParameters();
  82206. },
  82207. enumerable: true,
  82208. configurable: true
  82209. });
  82210. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  82211. /**
  82212. * Gets wether the vignette effect is enabled.
  82213. */
  82214. get: function () {
  82215. return this._vignetteEnabled;
  82216. },
  82217. /**
  82218. * Sets wether the vignette effect is enabled.
  82219. */
  82220. set: function (value) {
  82221. if (this._vignetteEnabled === value) {
  82222. return;
  82223. }
  82224. this._vignetteEnabled = value;
  82225. this._updateParameters();
  82226. },
  82227. enumerable: true,
  82228. configurable: true
  82229. });
  82230. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  82231. /**
  82232. * Gets wether the image processing is applied through a post process or not.
  82233. */
  82234. get: function () {
  82235. return this._applyByPostProcess;
  82236. },
  82237. /**
  82238. * Sets wether the image processing is applied through a post process or not.
  82239. */
  82240. set: function (value) {
  82241. if (this._applyByPostProcess === value) {
  82242. return;
  82243. }
  82244. this._applyByPostProcess = value;
  82245. this._updateParameters();
  82246. },
  82247. enumerable: true,
  82248. configurable: true
  82249. });
  82250. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  82251. /**
  82252. * Gets wether the image processing is enabled or not.
  82253. */
  82254. get: function () {
  82255. return this._isEnabled;
  82256. },
  82257. /**
  82258. * Sets wether the image processing is enabled or not.
  82259. */
  82260. set: function (value) {
  82261. if (this._isEnabled === value) {
  82262. return;
  82263. }
  82264. this._isEnabled = value;
  82265. this._updateParameters();
  82266. },
  82267. enumerable: true,
  82268. configurable: true
  82269. });
  82270. /**
  82271. * Method called each time the image processing information changes requires to recompile the effect.
  82272. */
  82273. ImageProcessingConfiguration.prototype._updateParameters = function () {
  82274. this.onUpdateParameters.notifyObservers(this);
  82275. };
  82276. ImageProcessingConfiguration.prototype.getClassName = function () {
  82277. return "ImageProcessingConfiguration";
  82278. };
  82279. /**
  82280. * Prepare the list of uniforms associated with the Image Processing effects.
  82281. * @param uniformsList The list of uniforms used in the effect
  82282. * @param defines the list of defines currently in use
  82283. */
  82284. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  82285. if (defines.EXPOSURE) {
  82286. uniforms.push("exposureLinear");
  82287. }
  82288. if (defines.CONTRAST) {
  82289. uniforms.push("contrast");
  82290. }
  82291. if (defines.COLORGRADING) {
  82292. uniforms.push("colorTransformSettings");
  82293. }
  82294. if (defines.VIGNETTE) {
  82295. uniforms.push("vInverseScreenSize");
  82296. uniforms.push("vignetteSettings1");
  82297. uniforms.push("vignetteSettings2");
  82298. }
  82299. if (defines.COLORCURVES) {
  82300. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  82301. }
  82302. };
  82303. /**
  82304. * Prepare the list of samplers associated with the Image Processing effects.
  82305. * @param uniformsList The list of uniforms used in the effect
  82306. * @param defines the list of defines currently in use
  82307. */
  82308. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  82309. if (defines.COLORGRADING) {
  82310. samplersList.push("txColorTransform");
  82311. }
  82312. };
  82313. /**
  82314. * Prepare the list of defines associated to the shader.
  82315. * @param defines the list of defines to complete
  82316. */
  82317. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  82318. if (forPostProcess === void 0) { forPostProcess = false; }
  82319. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  82320. defines.VIGNETTE = false;
  82321. defines.TONEMAPPING = false;
  82322. defines.TONEMAPPING_ACES = false;
  82323. defines.CONTRAST = false;
  82324. defines.EXPOSURE = false;
  82325. defines.COLORCURVES = false;
  82326. defines.COLORGRADING = false;
  82327. defines.COLORGRADING3D = false;
  82328. defines.IMAGEPROCESSING = false;
  82329. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  82330. return;
  82331. }
  82332. defines.VIGNETTE = this.vignetteEnabled;
  82333. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  82334. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  82335. defines.TONEMAPPING = this.toneMappingEnabled;
  82336. switch (this._toneMappingType) {
  82337. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  82338. defines.TONEMAPPING_ACES = true;
  82339. break;
  82340. }
  82341. defines.CONTRAST = (this.contrast !== 1.0);
  82342. defines.EXPOSURE = (this.exposure !== 1.0);
  82343. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  82344. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  82345. if (defines.COLORGRADING) {
  82346. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  82347. }
  82348. else {
  82349. defines.COLORGRADING3D = false;
  82350. }
  82351. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  82352. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  82353. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  82354. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  82355. };
  82356. /**
  82357. * Returns true if all the image processing information are ready.
  82358. */
  82359. ImageProcessingConfiguration.prototype.isReady = function () {
  82360. // Color Grading texure can not be none blocking.
  82361. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  82362. };
  82363. /**
  82364. * Binds the image processing to the shader.
  82365. * @param effect The effect to bind to
  82366. */
  82367. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  82368. if (aspectRatio === void 0) { aspectRatio = 1; }
  82369. // Color Curves
  82370. if (this._colorCurvesEnabled && this.colorCurves) {
  82371. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  82372. }
  82373. // Vignette
  82374. if (this._vignetteEnabled) {
  82375. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  82376. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  82377. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  82378. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  82379. var vignetteScaleX = vignetteScaleY * aspectRatio;
  82380. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  82381. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  82382. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  82383. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  82384. var vignettePower = -2.0 * this.vignetteWeight;
  82385. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  82386. }
  82387. // Exposure
  82388. effect.setFloat("exposureLinear", this.exposure);
  82389. // Contrast
  82390. effect.setFloat("contrast", this.contrast);
  82391. // Color transform settings
  82392. if (this.colorGradingTexture) {
  82393. effect.setTexture("txColorTransform", this.colorGradingTexture);
  82394. var textureSize = this.colorGradingTexture.getSize().height;
  82395. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  82396. 0.5 / textureSize, // textureOffset
  82397. textureSize, // textureSize
  82398. this.colorGradingTexture.level // weight
  82399. );
  82400. }
  82401. };
  82402. /**
  82403. * Clones the current image processing instance.
  82404. * @return The cloned image processing
  82405. */
  82406. ImageProcessingConfiguration.prototype.clone = function () {
  82407. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  82408. };
  82409. /**
  82410. * Serializes the current image processing instance to a json representation.
  82411. * @return a JSON representation
  82412. */
  82413. ImageProcessingConfiguration.prototype.serialize = function () {
  82414. return BABYLON.SerializationHelper.Serialize(this);
  82415. };
  82416. /**
  82417. * Parses the image processing from a json representation.
  82418. * @param source the JSON source to parse
  82419. * @return The parsed image processing
  82420. */
  82421. ImageProcessingConfiguration.Parse = function (source) {
  82422. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  82423. };
  82424. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  82425. /**
  82426. * Used to apply the vignette as a mix with the pixel color.
  82427. */
  82428. get: function () {
  82429. return this._VIGNETTEMODE_MULTIPLY;
  82430. },
  82431. enumerable: true,
  82432. configurable: true
  82433. });
  82434. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  82435. /**
  82436. * Used to apply the vignette as a replacement of the pixel color.
  82437. */
  82438. get: function () {
  82439. return this._VIGNETTEMODE_OPAQUE;
  82440. },
  82441. enumerable: true,
  82442. configurable: true
  82443. });
  82444. /**
  82445. * Default tone mapping applied in BabylonJS.
  82446. */
  82447. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  82448. /**
  82449. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  82450. * to other engines rendering to increase portability.
  82451. */
  82452. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  82453. // Static constants associated to the image processing.
  82454. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  82455. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  82456. __decorate([
  82457. BABYLON.serializeAsColorCurves()
  82458. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  82459. __decorate([
  82460. BABYLON.serialize()
  82461. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  82462. __decorate([
  82463. BABYLON.serializeAsTexture()
  82464. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  82465. __decorate([
  82466. BABYLON.serialize()
  82467. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  82468. __decorate([
  82469. BABYLON.serialize()
  82470. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  82471. __decorate([
  82472. BABYLON.serialize()
  82473. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  82474. __decorate([
  82475. BABYLON.serialize()
  82476. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  82477. __decorate([
  82478. BABYLON.serialize()
  82479. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  82480. __decorate([
  82481. BABYLON.serialize()
  82482. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  82483. __decorate([
  82484. BABYLON.serialize()
  82485. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  82486. __decorate([
  82487. BABYLON.serialize()
  82488. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  82489. __decorate([
  82490. BABYLON.serialize()
  82491. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  82492. __decorate([
  82493. BABYLON.serialize()
  82494. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  82495. __decorate([
  82496. BABYLON.serialize()
  82497. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  82498. __decorate([
  82499. BABYLON.serializeAsColor4()
  82500. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  82501. __decorate([
  82502. BABYLON.serialize()
  82503. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  82504. __decorate([
  82505. BABYLON.serialize()
  82506. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  82507. __decorate([
  82508. BABYLON.serialize()
  82509. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  82510. __decorate([
  82511. BABYLON.serialize()
  82512. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  82513. __decorate([
  82514. BABYLON.serialize()
  82515. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  82516. return ImageProcessingConfiguration;
  82517. }());
  82518. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  82519. })(BABYLON || (BABYLON = {}));
  82520. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  82521. var BABYLON;
  82522. (function (BABYLON) {
  82523. /**
  82524. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  82525. * It can help converting any input color in a desired output one. This can then be used to create effects
  82526. * from sepia, black and white to sixties or futuristic rendering...
  82527. *
  82528. * The only supported format is currently 3dl.
  82529. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  82530. */
  82531. var ColorGradingTexture = /** @class */ (function (_super) {
  82532. __extends(ColorGradingTexture, _super);
  82533. /**
  82534. * Instantiates a ColorGradingTexture from the following parameters.
  82535. *
  82536. * @param url The location of the color gradind data (currently only supporting 3dl)
  82537. * @param scene The scene the texture will be used in
  82538. */
  82539. function ColorGradingTexture(url, scene) {
  82540. var _this = _super.call(this, scene) || this;
  82541. if (!url) {
  82542. return _this;
  82543. }
  82544. _this._engine = scene.getEngine();
  82545. _this._textureMatrix = BABYLON.Matrix.Identity();
  82546. _this.name = url;
  82547. _this.url = url;
  82548. _this.hasAlpha = false;
  82549. _this.isCube = false;
  82550. _this.is3D = _this._engine.webGLVersion > 1;
  82551. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82552. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82553. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82554. _this.anisotropicFilteringLevel = 1;
  82555. _this._texture = _this._getFromCache(url, true);
  82556. if (!_this._texture) {
  82557. if (!scene.useDelayedTextureLoading) {
  82558. _this.loadTexture();
  82559. }
  82560. else {
  82561. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82562. }
  82563. }
  82564. return _this;
  82565. }
  82566. /**
  82567. * Returns the texture matrix used in most of the material.
  82568. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  82569. */
  82570. ColorGradingTexture.prototype.getTextureMatrix = function () {
  82571. return this._textureMatrix;
  82572. };
  82573. /**
  82574. * Occurs when the file being loaded is a .3dl LUT file.
  82575. */
  82576. ColorGradingTexture.prototype.load3dlTexture = function () {
  82577. var engine = this._engine;
  82578. var texture;
  82579. if (engine.webGLVersion === 1) {
  82580. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82581. }
  82582. else {
  82583. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82584. }
  82585. this._texture = texture;
  82586. var callback = function (text) {
  82587. if (typeof text !== "string") {
  82588. return;
  82589. }
  82590. var data = null;
  82591. var tempData = null;
  82592. var line;
  82593. var lines = text.split('\n');
  82594. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  82595. var maxColor = 0;
  82596. for (var i = 0; i < lines.length; i++) {
  82597. line = lines[i];
  82598. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  82599. continue;
  82600. if (line.indexOf('#') === 0)
  82601. continue;
  82602. var words = line.split(" ");
  82603. if (size === 0) {
  82604. // Number of space + one
  82605. size = words.length;
  82606. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  82607. tempData = new Float32Array(size * size * size * 4);
  82608. continue;
  82609. }
  82610. if (size != 0) {
  82611. var r = Math.max(parseInt(words[0]), 0);
  82612. var g = Math.max(parseInt(words[1]), 0);
  82613. var b = Math.max(parseInt(words[2]), 0);
  82614. maxColor = Math.max(r, maxColor);
  82615. maxColor = Math.max(g, maxColor);
  82616. maxColor = Math.max(b, maxColor);
  82617. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  82618. if (tempData) {
  82619. tempData[pixelStorageIndex + 0] = r;
  82620. tempData[pixelStorageIndex + 1] = g;
  82621. tempData[pixelStorageIndex + 2] = b;
  82622. }
  82623. pixelIndexSlice++;
  82624. if (pixelIndexSlice % size == 0) {
  82625. pixelIndexH++;
  82626. pixelIndexSlice = 0;
  82627. if (pixelIndexH % size == 0) {
  82628. pixelIndexW++;
  82629. pixelIndexH = 0;
  82630. }
  82631. }
  82632. }
  82633. }
  82634. if (tempData && data) {
  82635. for (var i = 0; i < tempData.length; i++) {
  82636. if (i > 0 && (i + 1) % 4 === 0) {
  82637. data[i] = 255;
  82638. }
  82639. else {
  82640. var value = tempData[i];
  82641. data[i] = (value / maxColor * 255);
  82642. }
  82643. }
  82644. }
  82645. if (texture.is3D) {
  82646. texture.updateSize(size, size, size);
  82647. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82648. }
  82649. else {
  82650. texture.updateSize(size * size, size);
  82651. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82652. }
  82653. };
  82654. var scene = this.getScene();
  82655. if (scene) {
  82656. scene._loadFile(this.url, callback);
  82657. }
  82658. else {
  82659. this._engine._loadFile(this.url, callback);
  82660. }
  82661. return this._texture;
  82662. };
  82663. /**
  82664. * Starts the loading process of the texture.
  82665. */
  82666. ColorGradingTexture.prototype.loadTexture = function () {
  82667. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  82668. this.load3dlTexture();
  82669. }
  82670. };
  82671. /**
  82672. * Clones the color gradind texture.
  82673. */
  82674. ColorGradingTexture.prototype.clone = function () {
  82675. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  82676. // Base texture
  82677. newTexture.level = this.level;
  82678. return newTexture;
  82679. };
  82680. /**
  82681. * Called during delayed load for textures.
  82682. */
  82683. ColorGradingTexture.prototype.delayLoad = function () {
  82684. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82685. return;
  82686. }
  82687. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82688. this._texture = this._getFromCache(this.url, true);
  82689. if (!this._texture) {
  82690. this.loadTexture();
  82691. }
  82692. };
  82693. /**
  82694. * Parses a color grading texture serialized by Babylon.
  82695. * @param parsedTexture The texture information being parsedTexture
  82696. * @param scene The scene to load the texture in
  82697. * @param rootUrl The root url of the data assets to load
  82698. * @return A color gradind texture
  82699. */
  82700. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82701. var texture = null;
  82702. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82703. texture = new ColorGradingTexture(parsedTexture.name, scene);
  82704. texture.name = parsedTexture.name;
  82705. texture.level = parsedTexture.level;
  82706. }
  82707. return texture;
  82708. };
  82709. /**
  82710. * Serializes the LUT texture to json format.
  82711. */
  82712. ColorGradingTexture.prototype.serialize = function () {
  82713. if (!this.name) {
  82714. return null;
  82715. }
  82716. var serializationObject = {};
  82717. serializationObject.name = this.name;
  82718. serializationObject.level = this.level;
  82719. serializationObject.customType = "BABYLON.ColorGradingTexture";
  82720. return serializationObject;
  82721. };
  82722. /**
  82723. * Empty line regex stored for GC.
  82724. */
  82725. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  82726. return ColorGradingTexture;
  82727. }(BABYLON.BaseTexture));
  82728. BABYLON.ColorGradingTexture = ColorGradingTexture;
  82729. })(BABYLON || (BABYLON = {}));
  82730. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  82731. var BABYLON;
  82732. (function (BABYLON) {
  82733. /**
  82734. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82735. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82736. * 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;
  82737. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82738. */
  82739. var ColorCurves = /** @class */ (function () {
  82740. function ColorCurves() {
  82741. this._dirty = true;
  82742. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  82743. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  82744. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82745. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  82746. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82747. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  82748. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  82749. this._globalHue = 30;
  82750. this._globalDensity = 0;
  82751. this._globalSaturation = 0;
  82752. this._globalExposure = 0;
  82753. this._highlightsHue = 30;
  82754. this._highlightsDensity = 0;
  82755. this._highlightsSaturation = 0;
  82756. this._highlightsExposure = 0;
  82757. this._midtonesHue = 30;
  82758. this._midtonesDensity = 0;
  82759. this._midtonesSaturation = 0;
  82760. this._midtonesExposure = 0;
  82761. this._shadowsHue = 30;
  82762. this._shadowsDensity = 0;
  82763. this._shadowsSaturation = 0;
  82764. this._shadowsExposure = 0;
  82765. }
  82766. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  82767. /**
  82768. * Gets the global Hue value.
  82769. * 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).
  82770. */
  82771. get: function () {
  82772. return this._globalHue;
  82773. },
  82774. /**
  82775. * Sets the global Hue value.
  82776. * 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).
  82777. */
  82778. set: function (value) {
  82779. this._globalHue = value;
  82780. this._dirty = true;
  82781. },
  82782. enumerable: true,
  82783. configurable: true
  82784. });
  82785. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  82786. /**
  82787. * Gets the global Density value.
  82788. * 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.
  82789. * Values less than zero provide a filter of opposite hue.
  82790. */
  82791. get: function () {
  82792. return this._globalDensity;
  82793. },
  82794. /**
  82795. * Sets the global Density value.
  82796. * 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.
  82797. * Values less than zero provide a filter of opposite hue.
  82798. */
  82799. set: function (value) {
  82800. this._globalDensity = value;
  82801. this._dirty = true;
  82802. },
  82803. enumerable: true,
  82804. configurable: true
  82805. });
  82806. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  82807. /**
  82808. * Gets the global Saturation value.
  82809. * 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.
  82810. */
  82811. get: function () {
  82812. return this._globalSaturation;
  82813. },
  82814. /**
  82815. * Sets the global Saturation value.
  82816. * 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.
  82817. */
  82818. set: function (value) {
  82819. this._globalSaturation = value;
  82820. this._dirty = true;
  82821. },
  82822. enumerable: true,
  82823. configurable: true
  82824. });
  82825. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  82826. /**
  82827. * Gets the global Exposure value.
  82828. * 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.
  82829. */
  82830. get: function () {
  82831. return this._globalExposure;
  82832. },
  82833. /**
  82834. * Sets the global Exposure value.
  82835. * 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.
  82836. */
  82837. set: function (value) {
  82838. this._globalExposure = value;
  82839. this._dirty = true;
  82840. },
  82841. enumerable: true,
  82842. configurable: true
  82843. });
  82844. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  82845. /**
  82846. * Gets the highlights Hue value.
  82847. * 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).
  82848. */
  82849. get: function () {
  82850. return this._highlightsHue;
  82851. },
  82852. /**
  82853. * Sets the highlights Hue value.
  82854. * 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).
  82855. */
  82856. set: function (value) {
  82857. this._highlightsHue = value;
  82858. this._dirty = true;
  82859. },
  82860. enumerable: true,
  82861. configurable: true
  82862. });
  82863. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  82864. /**
  82865. * Gets the highlights Density value.
  82866. * 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.
  82867. * Values less than zero provide a filter of opposite hue.
  82868. */
  82869. get: function () {
  82870. return this._highlightsDensity;
  82871. },
  82872. /**
  82873. * Sets the highlights Density value.
  82874. * 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.
  82875. * Values less than zero provide a filter of opposite hue.
  82876. */
  82877. set: function (value) {
  82878. this._highlightsDensity = value;
  82879. this._dirty = true;
  82880. },
  82881. enumerable: true,
  82882. configurable: true
  82883. });
  82884. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  82885. /**
  82886. * Gets the highlights Saturation value.
  82887. * 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.
  82888. */
  82889. get: function () {
  82890. return this._highlightsSaturation;
  82891. },
  82892. /**
  82893. * Sets the highlights Saturation value.
  82894. * 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.
  82895. */
  82896. set: function (value) {
  82897. this._highlightsSaturation = value;
  82898. this._dirty = true;
  82899. },
  82900. enumerable: true,
  82901. configurable: true
  82902. });
  82903. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  82904. /**
  82905. * Gets the highlights Exposure value.
  82906. * 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.
  82907. */
  82908. get: function () {
  82909. return this._highlightsExposure;
  82910. },
  82911. /**
  82912. * Sets the highlights Exposure value.
  82913. * 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.
  82914. */
  82915. set: function (value) {
  82916. this._highlightsExposure = value;
  82917. this._dirty = true;
  82918. },
  82919. enumerable: true,
  82920. configurable: true
  82921. });
  82922. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  82923. /**
  82924. * Gets the midtones Hue value.
  82925. * 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).
  82926. */
  82927. get: function () {
  82928. return this._midtonesHue;
  82929. },
  82930. /**
  82931. * Sets the midtones Hue value.
  82932. * 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).
  82933. */
  82934. set: function (value) {
  82935. this._midtonesHue = value;
  82936. this._dirty = true;
  82937. },
  82938. enumerable: true,
  82939. configurable: true
  82940. });
  82941. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  82942. /**
  82943. * Gets the midtones Density value.
  82944. * 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.
  82945. * Values less than zero provide a filter of opposite hue.
  82946. */
  82947. get: function () {
  82948. return this._midtonesDensity;
  82949. },
  82950. /**
  82951. * Sets the midtones Density value.
  82952. * 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.
  82953. * Values less than zero provide a filter of opposite hue.
  82954. */
  82955. set: function (value) {
  82956. this._midtonesDensity = value;
  82957. this._dirty = true;
  82958. },
  82959. enumerable: true,
  82960. configurable: true
  82961. });
  82962. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  82963. /**
  82964. * Gets the midtones Saturation value.
  82965. * 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.
  82966. */
  82967. get: function () {
  82968. return this._midtonesSaturation;
  82969. },
  82970. /**
  82971. * Sets the midtones Saturation value.
  82972. * 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.
  82973. */
  82974. set: function (value) {
  82975. this._midtonesSaturation = value;
  82976. this._dirty = true;
  82977. },
  82978. enumerable: true,
  82979. configurable: true
  82980. });
  82981. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  82982. /**
  82983. * Gets the midtones Exposure value.
  82984. * 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.
  82985. */
  82986. get: function () {
  82987. return this._midtonesExposure;
  82988. },
  82989. /**
  82990. * Sets the midtones Exposure value.
  82991. * 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.
  82992. */
  82993. set: function (value) {
  82994. this._midtonesExposure = value;
  82995. this._dirty = true;
  82996. },
  82997. enumerable: true,
  82998. configurable: true
  82999. });
  83000. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  83001. /**
  83002. * Gets the shadows Hue value.
  83003. * 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).
  83004. */
  83005. get: function () {
  83006. return this._shadowsHue;
  83007. },
  83008. /**
  83009. * Sets the shadows Hue value.
  83010. * 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).
  83011. */
  83012. set: function (value) {
  83013. this._shadowsHue = value;
  83014. this._dirty = true;
  83015. },
  83016. enumerable: true,
  83017. configurable: true
  83018. });
  83019. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  83020. /**
  83021. * Gets the shadows Density value.
  83022. * 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.
  83023. * Values less than zero provide a filter of opposite hue.
  83024. */
  83025. get: function () {
  83026. return this._shadowsDensity;
  83027. },
  83028. /**
  83029. * Sets the shadows Density value.
  83030. * 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.
  83031. * Values less than zero provide a filter of opposite hue.
  83032. */
  83033. set: function (value) {
  83034. this._shadowsDensity = value;
  83035. this._dirty = true;
  83036. },
  83037. enumerable: true,
  83038. configurable: true
  83039. });
  83040. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  83041. /**
  83042. * Gets the shadows Saturation value.
  83043. * 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.
  83044. */
  83045. get: function () {
  83046. return this._shadowsSaturation;
  83047. },
  83048. /**
  83049. * Sets the shadows Saturation value.
  83050. * 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.
  83051. */
  83052. set: function (value) {
  83053. this._shadowsSaturation = value;
  83054. this._dirty = true;
  83055. },
  83056. enumerable: true,
  83057. configurable: true
  83058. });
  83059. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  83060. /**
  83061. * Gets the shadows Exposure value.
  83062. * 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.
  83063. */
  83064. get: function () {
  83065. return this._shadowsExposure;
  83066. },
  83067. /**
  83068. * Sets the shadows Exposure value.
  83069. * 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.
  83070. */
  83071. set: function (value) {
  83072. this._shadowsExposure = value;
  83073. this._dirty = true;
  83074. },
  83075. enumerable: true,
  83076. configurable: true
  83077. });
  83078. ColorCurves.prototype.getClassName = function () {
  83079. return "ColorCurves";
  83080. };
  83081. /**
  83082. * Binds the color curves to the shader.
  83083. * @param colorCurves The color curve to bind
  83084. * @param effect The effect to bind to
  83085. */
  83086. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  83087. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  83088. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  83089. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  83090. if (colorCurves._dirty) {
  83091. colorCurves._dirty = false;
  83092. // Fill in global info.
  83093. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  83094. // Compute highlights info.
  83095. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  83096. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  83097. // Compute midtones info.
  83098. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  83099. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  83100. // Compute shadows info.
  83101. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  83102. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  83103. // Compute deltas (neutral is midtones).
  83104. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  83105. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  83106. }
  83107. if (effect) {
  83108. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  83109. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  83110. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  83111. }
  83112. };
  83113. /**
  83114. * Prepare the list of uniforms associated with the ColorCurves effects.
  83115. * @param uniformsList The list of uniforms used in the effect
  83116. */
  83117. ColorCurves.PrepareUniforms = function (uniformsList) {
  83118. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  83119. };
  83120. /**
  83121. * Returns color grading data based on a hue, density, saturation and exposure value.
  83122. * @param filterHue The hue of the color filter.
  83123. * @param filterDensity The density of the color filter.
  83124. * @param saturation The saturation.
  83125. * @param exposure The exposure.
  83126. * @param result The result data container.
  83127. */
  83128. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  83129. if (hue == null) {
  83130. return;
  83131. }
  83132. hue = ColorCurves.clamp(hue, 0, 360);
  83133. density = ColorCurves.clamp(density, -100, 100);
  83134. saturation = ColorCurves.clamp(saturation, -100, 100);
  83135. exposure = ColorCurves.clamp(exposure, -100, 100);
  83136. // Remap the slider/config filter density with non-linear mapping and also scale by half
  83137. // so that the maximum filter density is only 50% control. This provides fine control
  83138. // for small values and reasonable range.
  83139. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  83140. density *= 0.5;
  83141. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  83142. if (density < 0) {
  83143. density *= -1;
  83144. hue = (hue + 180) % 360;
  83145. }
  83146. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  83147. result.scaleToRef(2, result);
  83148. result.a = 1 + 0.01 * saturation;
  83149. };
  83150. /**
  83151. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  83152. * @param value The input slider value in range [-100,100].
  83153. * @returns Adjusted value.
  83154. */
  83155. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  83156. value /= 100;
  83157. var x = Math.abs(value);
  83158. x = Math.pow(x, 2);
  83159. if (value < 0) {
  83160. x *= -1;
  83161. }
  83162. x *= 100;
  83163. return x;
  83164. };
  83165. /**
  83166. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  83167. * @param hue The hue (H) input.
  83168. * @param saturation The saturation (S) input.
  83169. * @param brightness The brightness (B) input.
  83170. * @result An RGBA color represented as Vector4.
  83171. */
  83172. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  83173. var h = ColorCurves.clamp(hue, 0, 360);
  83174. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  83175. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  83176. if (s === 0) {
  83177. result.r = v;
  83178. result.g = v;
  83179. result.b = v;
  83180. }
  83181. else {
  83182. // sector 0 to 5
  83183. h /= 60;
  83184. var i = Math.floor(h);
  83185. // fractional part of h
  83186. var f = h - i;
  83187. var p = v * (1 - s);
  83188. var q = v * (1 - s * f);
  83189. var t = v * (1 - s * (1 - f));
  83190. switch (i) {
  83191. case 0:
  83192. result.r = v;
  83193. result.g = t;
  83194. result.b = p;
  83195. break;
  83196. case 1:
  83197. result.r = q;
  83198. result.g = v;
  83199. result.b = p;
  83200. break;
  83201. case 2:
  83202. result.r = p;
  83203. result.g = v;
  83204. result.b = t;
  83205. break;
  83206. case 3:
  83207. result.r = p;
  83208. result.g = q;
  83209. result.b = v;
  83210. break;
  83211. case 4:
  83212. result.r = t;
  83213. result.g = p;
  83214. result.b = v;
  83215. break;
  83216. default: // case 5:
  83217. result.r = v;
  83218. result.g = p;
  83219. result.b = q;
  83220. break;
  83221. }
  83222. }
  83223. result.a = 1;
  83224. };
  83225. /**
  83226. * Returns a value clamped between min and max
  83227. * @param value The value to clamp
  83228. * @param min The minimum of value
  83229. * @param max The maximum of value
  83230. * @returns The clamped value.
  83231. */
  83232. ColorCurves.clamp = function (value, min, max) {
  83233. return Math.min(Math.max(value, min), max);
  83234. };
  83235. /**
  83236. * Clones the current color curve instance.
  83237. * @return The cloned curves
  83238. */
  83239. ColorCurves.prototype.clone = function () {
  83240. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  83241. };
  83242. /**
  83243. * Serializes the current color curve instance to a json representation.
  83244. * @return a JSON representation
  83245. */
  83246. ColorCurves.prototype.serialize = function () {
  83247. return BABYLON.SerializationHelper.Serialize(this);
  83248. };
  83249. /**
  83250. * Parses the color curve from a json representation.
  83251. * @param source the JSON source to parse
  83252. * @return The parsed curves
  83253. */
  83254. ColorCurves.Parse = function (source) {
  83255. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  83256. };
  83257. __decorate([
  83258. BABYLON.serialize()
  83259. ], ColorCurves.prototype, "_globalHue", void 0);
  83260. __decorate([
  83261. BABYLON.serialize()
  83262. ], ColorCurves.prototype, "_globalDensity", void 0);
  83263. __decorate([
  83264. BABYLON.serialize()
  83265. ], ColorCurves.prototype, "_globalSaturation", void 0);
  83266. __decorate([
  83267. BABYLON.serialize()
  83268. ], ColorCurves.prototype, "_globalExposure", void 0);
  83269. __decorate([
  83270. BABYLON.serialize()
  83271. ], ColorCurves.prototype, "_highlightsHue", void 0);
  83272. __decorate([
  83273. BABYLON.serialize()
  83274. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  83275. __decorate([
  83276. BABYLON.serialize()
  83277. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  83278. __decorate([
  83279. BABYLON.serialize()
  83280. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  83281. __decorate([
  83282. BABYLON.serialize()
  83283. ], ColorCurves.prototype, "_midtonesHue", void 0);
  83284. __decorate([
  83285. BABYLON.serialize()
  83286. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  83287. __decorate([
  83288. BABYLON.serialize()
  83289. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  83290. __decorate([
  83291. BABYLON.serialize()
  83292. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  83293. return ColorCurves;
  83294. }());
  83295. BABYLON.ColorCurves = ColorCurves;
  83296. })(BABYLON || (BABYLON = {}));
  83297. //# sourceMappingURL=babylon.colorCurves.js.map
  83298. var BABYLON;
  83299. (function (BABYLON) {
  83300. var RefractionPostProcess = /** @class */ (function (_super) {
  83301. __extends(RefractionPostProcess, _super);
  83302. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  83303. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  83304. _this.color = color;
  83305. _this.depth = depth;
  83306. _this.colorLevel = colorLevel;
  83307. _this._ownRefractionTexture = true;
  83308. _this.onActivateObservable.add(function (cam) {
  83309. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  83310. });
  83311. _this.onApplyObservable.add(function (effect) {
  83312. effect.setColor3("baseColor", _this.color);
  83313. effect.setFloat("depth", _this.depth);
  83314. effect.setFloat("colorLevel", _this.colorLevel);
  83315. effect.setTexture("refractionSampler", _this._refTexture);
  83316. });
  83317. return _this;
  83318. }
  83319. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  83320. /**
  83321. * Gets or sets the refraction texture
  83322. * Please note that you are responsible for disposing the texture if you set it manually
  83323. */
  83324. get: function () {
  83325. return this._refTexture;
  83326. },
  83327. set: function (value) {
  83328. if (this._refTexture && this._ownRefractionTexture) {
  83329. this._refTexture.dispose();
  83330. }
  83331. this._refTexture = value;
  83332. this._ownRefractionTexture = false;
  83333. },
  83334. enumerable: true,
  83335. configurable: true
  83336. });
  83337. // Methods
  83338. RefractionPostProcess.prototype.dispose = function (camera) {
  83339. if (this._refTexture && this._ownRefractionTexture) {
  83340. this._refTexture.dispose();
  83341. this._refTexture = null;
  83342. }
  83343. _super.prototype.dispose.call(this, camera);
  83344. };
  83345. return RefractionPostProcess;
  83346. }(BABYLON.PostProcess));
  83347. BABYLON.RefractionPostProcess = RefractionPostProcess;
  83348. })(BABYLON || (BABYLON = {}));
  83349. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  83350. var BABYLON;
  83351. (function (BABYLON) {
  83352. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  83353. __extends(BlackAndWhitePostProcess, _super);
  83354. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  83355. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  83356. _this.degree = 1;
  83357. _this.onApplyObservable.add(function (effect) {
  83358. effect.setFloat("degree", _this.degree);
  83359. });
  83360. return _this;
  83361. }
  83362. return BlackAndWhitePostProcess;
  83363. }(BABYLON.PostProcess));
  83364. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  83365. })(BABYLON || (BABYLON = {}));
  83366. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  83367. var BABYLON;
  83368. (function (BABYLON) {
  83369. /**
  83370. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  83371. * input texture to perform effects such as edge detection or sharpening
  83372. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83373. */
  83374. var ConvolutionPostProcess = /** @class */ (function (_super) {
  83375. __extends(ConvolutionPostProcess, _super);
  83376. /**
  83377. * Creates a new instance ConvolutionPostProcess
  83378. * @param name The name of the effect.
  83379. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  83380. * @param options The required width/height ratio to downsize to before computing the render pass.
  83381. * @param camera The camera to apply the render pass to.
  83382. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83383. * @param engine The engine which the post process will be applied. (default: current engine)
  83384. * @param reusable If the post process can be reused on the same frame. (default: false)
  83385. * @param textureType Type of textures used when performing the post process. (default: 0)
  83386. */
  83387. function ConvolutionPostProcess(name,
  83388. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  83389. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  83390. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83391. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83392. _this.kernel = kernel;
  83393. _this.onApply = function (effect) {
  83394. effect.setFloat2("screenSize", _this.width, _this.height);
  83395. effect.setArray("kernel", _this.kernel);
  83396. };
  83397. return _this;
  83398. }
  83399. // Statics
  83400. /**
  83401. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83402. */
  83403. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  83404. /**
  83405. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83406. */
  83407. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  83408. /**
  83409. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83410. */
  83411. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  83412. /**
  83413. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83414. */
  83415. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  83416. /**
  83417. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83418. */
  83419. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  83420. /**
  83421. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83422. */
  83423. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  83424. return ConvolutionPostProcess;
  83425. }(BABYLON.PostProcess));
  83426. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  83427. })(BABYLON || (BABYLON = {}));
  83428. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  83429. var BABYLON;
  83430. (function (BABYLON) {
  83431. var FilterPostProcess = /** @class */ (function (_super) {
  83432. __extends(FilterPostProcess, _super);
  83433. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  83434. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  83435. _this.kernelMatrix = kernelMatrix;
  83436. _this.onApply = function (effect) {
  83437. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  83438. };
  83439. return _this;
  83440. }
  83441. return FilterPostProcess;
  83442. }(BABYLON.PostProcess));
  83443. BABYLON.FilterPostProcess = FilterPostProcess;
  83444. })(BABYLON || (BABYLON = {}));
  83445. //# sourceMappingURL=babylon.filterPostProcess.js.map
  83446. var BABYLON;
  83447. (function (BABYLON) {
  83448. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  83449. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  83450. __extends(VolumetricLightScatteringPostProcess, _super);
  83451. /**
  83452. * @constructor
  83453. * @param {string} name - The post-process name
  83454. * @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)
  83455. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  83456. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  83457. * @param {number} samples - The post-process quality, default 100
  83458. * @param {number} samplingMode - The post-process filtering mode
  83459. * @param {BABYLON.Engine} engine - The babylon engine
  83460. * @param {boolean} reusable - If the post-process is reusable
  83461. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  83462. */
  83463. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  83464. if (samples === void 0) { samples = 100; }
  83465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83466. 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;
  83467. _this._screenCoordinates = BABYLON.Vector2.Zero();
  83468. /**
  83469. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  83470. */
  83471. _this.customMeshPosition = BABYLON.Vector3.Zero();
  83472. /**
  83473. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  83474. */
  83475. _this.useCustomMeshPosition = false;
  83476. /**
  83477. * If the post-process should inverse the light scattering direction
  83478. */
  83479. _this.invert = true;
  83480. /**
  83481. * Array containing the excluded meshes not rendered in the internal pass
  83482. */
  83483. _this.excludedMeshes = new Array();
  83484. /**
  83485. * Controls the overall intensity of the post-process
  83486. */
  83487. _this.exposure = 0.3;
  83488. /**
  83489. * Dissipates each sample's contribution in range [0, 1]
  83490. */
  83491. _this.decay = 0.96815;
  83492. /**
  83493. * Controls the overall intensity of each sample
  83494. */
  83495. _this.weight = 0.58767;
  83496. /**
  83497. * Controls the density of each sample
  83498. */
  83499. _this.density = 0.926;
  83500. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  83501. engine = scene.getEngine();
  83502. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  83503. // Configure mesh
  83504. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  83505. // Configure
  83506. _this._createPass(scene, ratio.passRatio || ratio);
  83507. _this.onActivate = function (camera) {
  83508. if (!_this.isSupported) {
  83509. _this.dispose(camera);
  83510. }
  83511. _this.onActivate = null;
  83512. };
  83513. _this.onApplyObservable.add(function (effect) {
  83514. _this._updateMeshScreenCoordinates(scene);
  83515. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  83516. effect.setFloat("exposure", _this.exposure);
  83517. effect.setFloat("decay", _this.decay);
  83518. effect.setFloat("weight", _this.weight);
  83519. effect.setFloat("density", _this.density);
  83520. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  83521. });
  83522. return _this;
  83523. }
  83524. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  83525. get: function () {
  83526. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83527. return false;
  83528. },
  83529. set: function (useDiffuseColor) {
  83530. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83531. },
  83532. enumerable: true,
  83533. configurable: true
  83534. });
  83535. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  83536. return "VolumetricLightScatteringPostProcess";
  83537. };
  83538. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  83539. var mesh = subMesh.getMesh();
  83540. // Render this.mesh as default
  83541. if (mesh === this.mesh && mesh.material) {
  83542. return mesh.material.isReady(mesh);
  83543. }
  83544. var defines = [];
  83545. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83546. var material = subMesh.getMaterial();
  83547. // Alpha test
  83548. if (material) {
  83549. if (material.needAlphaTesting()) {
  83550. defines.push("#define ALPHATEST");
  83551. }
  83552. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83553. attribs.push(BABYLON.VertexBuffer.UVKind);
  83554. defines.push("#define UV1");
  83555. }
  83556. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83557. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83558. defines.push("#define UV2");
  83559. }
  83560. }
  83561. // Bones
  83562. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83563. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83564. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83565. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83566. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83567. }
  83568. else {
  83569. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83570. }
  83571. // Instances
  83572. if (useInstances) {
  83573. defines.push("#define INSTANCES");
  83574. attribs.push("world0");
  83575. attribs.push("world1");
  83576. attribs.push("world2");
  83577. attribs.push("world3");
  83578. }
  83579. // Get correct effect
  83580. var join = defines.join("\n");
  83581. if (this._cachedDefines !== join) {
  83582. this._cachedDefines = join;
  83583. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  83584. }
  83585. return this._volumetricLightScatteringPass.isReady();
  83586. };
  83587. /**
  83588. * Sets the new light position for light scattering effect
  83589. * @param {BABYLON.Vector3} The new custom light position
  83590. */
  83591. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  83592. this.customMeshPosition = position;
  83593. };
  83594. /**
  83595. * Returns the light position for light scattering effect
  83596. * @return {BABYLON.Vector3} The custom light position
  83597. */
  83598. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  83599. return this.customMeshPosition;
  83600. };
  83601. /**
  83602. * Disposes the internal assets and detaches the post-process from the camera
  83603. */
  83604. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  83605. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  83606. if (rttIndex !== -1) {
  83607. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  83608. }
  83609. this._volumetricLightScatteringRTT.dispose();
  83610. _super.prototype.dispose.call(this, camera);
  83611. };
  83612. /**
  83613. * Returns the render target texture used by the post-process
  83614. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  83615. */
  83616. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  83617. return this._volumetricLightScatteringRTT;
  83618. };
  83619. // Private methods
  83620. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  83621. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  83622. return true;
  83623. }
  83624. return false;
  83625. };
  83626. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  83627. var _this = this;
  83628. var engine = scene.getEngine();
  83629. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83630. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83631. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83632. this._volumetricLightScatteringRTT.renderList = null;
  83633. this._volumetricLightScatteringRTT.renderParticles = false;
  83634. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  83635. var camera = this.getCamera();
  83636. if (camera) {
  83637. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83638. }
  83639. else {
  83640. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83641. }
  83642. // Custom render function for submeshes
  83643. var renderSubMesh = function (subMesh) {
  83644. var mesh = subMesh.getRenderingMesh();
  83645. if (_this._meshExcluded(mesh)) {
  83646. return;
  83647. }
  83648. var material = subMesh.getMaterial();
  83649. if (!material) {
  83650. return;
  83651. }
  83652. var scene = mesh.getScene();
  83653. var engine = scene.getEngine();
  83654. // Culling
  83655. engine.setState(material.backFaceCulling);
  83656. // Managing instances
  83657. var batch = mesh._getInstancesRenderList(subMesh._id);
  83658. if (batch.mustReturn) {
  83659. return;
  83660. }
  83661. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83662. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  83663. var effect = _this._volumetricLightScatteringPass;
  83664. if (mesh === _this.mesh) {
  83665. if (subMesh.effect) {
  83666. effect = subMesh.effect;
  83667. }
  83668. else {
  83669. effect = material.getEffect();
  83670. }
  83671. }
  83672. engine.enableEffect(effect);
  83673. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  83674. if (mesh === _this.mesh) {
  83675. material.bind(mesh.getWorldMatrix(), mesh);
  83676. }
  83677. else {
  83678. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  83679. // Alpha test
  83680. if (material && material.needAlphaTesting()) {
  83681. var alphaTexture = material.getAlphaTestTexture();
  83682. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  83683. if (alphaTexture) {
  83684. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83685. }
  83686. }
  83687. // Bones
  83688. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83689. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83690. }
  83691. }
  83692. // Draw
  83693. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  83694. }
  83695. };
  83696. // Render target texture callbacks
  83697. var savedSceneClearColor;
  83698. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  83699. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  83700. savedSceneClearColor = scene.clearColor;
  83701. scene.clearColor = sceneClearColor;
  83702. });
  83703. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  83704. scene.clearColor = savedSceneClearColor;
  83705. });
  83706. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83707. var engine = scene.getEngine();
  83708. var index;
  83709. if (depthOnlySubMeshes.length) {
  83710. engine.setColorWrite(false);
  83711. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83712. renderSubMesh(depthOnlySubMeshes.data[index]);
  83713. }
  83714. engine.setColorWrite(true);
  83715. }
  83716. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83717. renderSubMesh(opaqueSubMeshes.data[index]);
  83718. }
  83719. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83720. renderSubMesh(alphaTestSubMeshes.data[index]);
  83721. }
  83722. if (transparentSubMeshes.length) {
  83723. // Sort sub meshes
  83724. for (index = 0; index < transparentSubMeshes.length; index++) {
  83725. var submesh = transparentSubMeshes.data[index];
  83726. var boundingInfo = submesh.getBoundingInfo();
  83727. if (boundingInfo && scene.activeCamera) {
  83728. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  83729. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  83730. }
  83731. }
  83732. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  83733. sortedArray.sort(function (a, b) {
  83734. // Alpha index first
  83735. if (a._alphaIndex > b._alphaIndex) {
  83736. return 1;
  83737. }
  83738. if (a._alphaIndex < b._alphaIndex) {
  83739. return -1;
  83740. }
  83741. // Then distance to camera
  83742. if (a._distanceToCamera < b._distanceToCamera) {
  83743. return 1;
  83744. }
  83745. if (a._distanceToCamera > b._distanceToCamera) {
  83746. return -1;
  83747. }
  83748. return 0;
  83749. });
  83750. // Render sub meshes
  83751. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  83752. for (index = 0; index < sortedArray.length; index++) {
  83753. renderSubMesh(sortedArray[index]);
  83754. }
  83755. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83756. }
  83757. };
  83758. };
  83759. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  83760. var transform = scene.getTransformMatrix();
  83761. var meshPosition;
  83762. if (this.useCustomMeshPosition) {
  83763. meshPosition = this.customMeshPosition;
  83764. }
  83765. else if (this.attachedNode) {
  83766. meshPosition = this.attachedNode.position;
  83767. }
  83768. else {
  83769. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  83770. }
  83771. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  83772. this._screenCoordinates.x = pos.x / this._viewPort.width;
  83773. this._screenCoordinates.y = pos.y / this._viewPort.height;
  83774. if (this.invert)
  83775. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  83776. };
  83777. // Static methods
  83778. /**
  83779. * Creates a default mesh for the Volumeric Light Scattering post-process
  83780. * @param {string} The mesh name
  83781. * @param {BABYLON.Scene} The scene where to create the mesh
  83782. * @return {BABYLON.Mesh} the default mesh
  83783. */
  83784. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  83785. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  83786. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  83787. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  83788. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  83789. mesh.material = material;
  83790. return mesh;
  83791. };
  83792. __decorate([
  83793. BABYLON.serializeAsVector3()
  83794. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  83795. __decorate([
  83796. BABYLON.serialize()
  83797. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  83798. __decorate([
  83799. BABYLON.serialize()
  83800. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  83801. __decorate([
  83802. BABYLON.serializeAsMeshReference()
  83803. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  83804. __decorate([
  83805. BABYLON.serialize()
  83806. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  83807. __decorate([
  83808. BABYLON.serialize()
  83809. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  83810. __decorate([
  83811. BABYLON.serialize()
  83812. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  83813. __decorate([
  83814. BABYLON.serialize()
  83815. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  83816. __decorate([
  83817. BABYLON.serialize()
  83818. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  83819. return VolumetricLightScatteringPostProcess;
  83820. }(BABYLON.PostProcess));
  83821. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  83822. })(BABYLON || (BABYLON = {}));
  83823. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  83824. //
  83825. // This post-process allows the modification of rendered colors by using
  83826. // a 'look-up table' (LUT). This effect is also called Color Grading.
  83827. //
  83828. // The object needs to be provided an url to a texture containing the color
  83829. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  83830. // Use an image editing software to tweak the LUT to match your needs.
  83831. //
  83832. // For an example of a color LUT, see here:
  83833. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  83834. // For explanations on color grading, see here:
  83835. // http://udn.epicgames.com/Three/ColorGrading.html
  83836. //
  83837. var BABYLON;
  83838. (function (BABYLON) {
  83839. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  83840. __extends(ColorCorrectionPostProcess, _super);
  83841. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  83842. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  83843. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83844. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  83845. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83846. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83847. _this.onApply = function (effect) {
  83848. effect.setTexture("colorTable", _this._colorTableTexture);
  83849. };
  83850. return _this;
  83851. }
  83852. return ColorCorrectionPostProcess;
  83853. }(BABYLON.PostProcess));
  83854. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  83855. })(BABYLON || (BABYLON = {}));
  83856. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  83857. var BABYLON;
  83858. (function (BABYLON) {
  83859. /** Defines operator used for tonemapping */
  83860. var TonemappingOperator;
  83861. (function (TonemappingOperator) {
  83862. /** Hable */
  83863. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  83864. /** Reinhard */
  83865. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  83866. /** HejiDawson */
  83867. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  83868. /** Photographic */
  83869. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  83870. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  83871. ;
  83872. /**
  83873. * Defines a post process to apply tone mapping
  83874. */
  83875. var TonemapPostProcess = /** @class */ (function (_super) {
  83876. __extends(TonemapPostProcess, _super);
  83877. /**
  83878. * Creates a new TonemapPostProcess
  83879. * @param name defines the name of the postprocess
  83880. * @param _operator defines the operator to use
  83881. * @param exposureAdjustment defines the required exposure adjustement
  83882. * @param camera defines the camera to use (can be null)
  83883. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  83884. * @param engine defines the hosting engine (can be ignore if camera is set)
  83885. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  83886. */
  83887. function TonemapPostProcess(name, _operator,
  83888. /** Defines the required exposure adjustement */
  83889. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  83890. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83891. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83892. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  83893. _this._operator = _operator;
  83894. _this.exposureAdjustment = exposureAdjustment;
  83895. var defines = "#define ";
  83896. if (_this._operator === TonemappingOperator.Hable)
  83897. defines += "HABLE_TONEMAPPING";
  83898. else if (_this._operator === TonemappingOperator.Reinhard)
  83899. defines += "REINHARD_TONEMAPPING";
  83900. else if (_this._operator === TonemappingOperator.HejiDawson)
  83901. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  83902. else if (_this._operator === TonemappingOperator.Photographic)
  83903. defines += "PHOTOGRAPHIC_TONEMAPPING";
  83904. //sadly a second call to create the effect.
  83905. _this.updateEffect(defines);
  83906. _this.onApply = function (effect) {
  83907. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  83908. };
  83909. return _this;
  83910. }
  83911. return TonemapPostProcess;
  83912. }(BABYLON.PostProcess));
  83913. BABYLON.TonemapPostProcess = TonemapPostProcess;
  83914. })(BABYLON || (BABYLON = {}));
  83915. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  83916. var BABYLON;
  83917. (function (BABYLON) {
  83918. var DisplayPassPostProcess = /** @class */ (function (_super) {
  83919. __extends(DisplayPassPostProcess, _super);
  83920. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  83921. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  83922. }
  83923. return DisplayPassPostProcess;
  83924. }(BABYLON.PostProcess));
  83925. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  83926. })(BABYLON || (BABYLON = {}));
  83927. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  83928. var BABYLON;
  83929. (function (BABYLON) {
  83930. var HighlightsPostProcess = /** @class */ (function (_super) {
  83931. __extends(HighlightsPostProcess, _super);
  83932. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83933. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83934. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83935. }
  83936. return HighlightsPostProcess;
  83937. }(BABYLON.PostProcess));
  83938. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  83939. })(BABYLON || (BABYLON = {}));
  83940. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  83941. var BABYLON;
  83942. (function (BABYLON) {
  83943. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  83944. __extends(ImageProcessingPostProcess, _super);
  83945. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  83946. if (camera === void 0) { camera = null; }
  83947. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83948. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  83949. _this._fromLinearSpace = true;
  83950. /**
  83951. * Defines cache preventing GC.
  83952. */
  83953. _this._defines = {
  83954. IMAGEPROCESSING: false,
  83955. VIGNETTE: false,
  83956. VIGNETTEBLENDMODEMULTIPLY: false,
  83957. VIGNETTEBLENDMODEOPAQUE: false,
  83958. TONEMAPPING: false,
  83959. TONEMAPPING_ACES: false,
  83960. CONTRAST: false,
  83961. COLORCURVES: false,
  83962. COLORGRADING: false,
  83963. COLORGRADING3D: false,
  83964. FROMLINEARSPACE: false,
  83965. SAMPLER3DGREENDEPTH: false,
  83966. SAMPLER3DBGRMAP: false,
  83967. IMAGEPROCESSINGPOSTPROCESS: false,
  83968. EXPOSURE: false,
  83969. };
  83970. // Setup the configuration as forced by the constructor. This would then not force the
  83971. // scene materials output in linear space and let untouched the default forward pass.
  83972. if (imageProcessingConfiguration) {
  83973. imageProcessingConfiguration.applyByPostProcess = true;
  83974. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  83975. // This will cause the shader to be compiled
  83976. _this.fromLinearSpace = false;
  83977. }
  83978. // Setup the default processing configuration to the scene.
  83979. else {
  83980. _this._attachImageProcessingConfiguration(null, true);
  83981. _this.imageProcessingConfiguration.applyByPostProcess = true;
  83982. }
  83983. _this.onApply = function (effect) {
  83984. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  83985. };
  83986. return _this;
  83987. }
  83988. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  83989. /**
  83990. * Gets the image processing configuration used either in this material.
  83991. */
  83992. get: function () {
  83993. return this._imageProcessingConfiguration;
  83994. },
  83995. /**
  83996. * Sets the Default image processing configuration used either in the this material.
  83997. *
  83998. * If sets to null, the scene one is in use.
  83999. */
  84000. set: function (value) {
  84001. this._attachImageProcessingConfiguration(value);
  84002. },
  84003. enumerable: true,
  84004. configurable: true
  84005. });
  84006. /**
  84007. * Attaches a new image processing configuration to the PBR Material.
  84008. * @param configuration
  84009. */
  84010. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  84011. var _this = this;
  84012. if (doNotBuild === void 0) { doNotBuild = false; }
  84013. if (configuration === this._imageProcessingConfiguration) {
  84014. return;
  84015. }
  84016. // Detaches observer.
  84017. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84018. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84019. }
  84020. // Pick the scene configuration if needed.
  84021. if (!configuration) {
  84022. var scene = null;
  84023. var engine = this.getEngine();
  84024. var camera = this.getCamera();
  84025. if (camera) {
  84026. scene = camera.getScene();
  84027. }
  84028. else if (engine && engine.scenes) {
  84029. var scenes = engine.scenes;
  84030. scene = scenes[scenes.length - 1];
  84031. }
  84032. else {
  84033. scene = BABYLON.Engine.LastCreatedScene;
  84034. }
  84035. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  84036. }
  84037. else {
  84038. this._imageProcessingConfiguration = configuration;
  84039. }
  84040. // Attaches observer.
  84041. if (this._imageProcessingConfiguration) {
  84042. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  84043. _this._updateParameters();
  84044. });
  84045. }
  84046. // Ensure the effect will be rebuilt.
  84047. if (!doNotBuild) {
  84048. this._updateParameters();
  84049. }
  84050. };
  84051. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  84052. /**
  84053. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  84054. */
  84055. get: function () {
  84056. return this.imageProcessingConfiguration.colorCurves;
  84057. },
  84058. /**
  84059. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  84060. */
  84061. set: function (value) {
  84062. this.imageProcessingConfiguration.colorCurves = value;
  84063. },
  84064. enumerable: true,
  84065. configurable: true
  84066. });
  84067. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  84068. /**
  84069. * Gets wether the color curves effect is enabled.
  84070. */
  84071. get: function () {
  84072. return this.imageProcessingConfiguration.colorCurvesEnabled;
  84073. },
  84074. /**
  84075. * Sets wether the color curves effect is enabled.
  84076. */
  84077. set: function (value) {
  84078. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  84079. },
  84080. enumerable: true,
  84081. configurable: true
  84082. });
  84083. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  84084. /**
  84085. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  84086. */
  84087. get: function () {
  84088. return this.imageProcessingConfiguration.colorGradingTexture;
  84089. },
  84090. /**
  84091. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  84092. */
  84093. set: function (value) {
  84094. this.imageProcessingConfiguration.colorGradingTexture = value;
  84095. },
  84096. enumerable: true,
  84097. configurable: true
  84098. });
  84099. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  84100. /**
  84101. * Gets wether the color grading effect is enabled.
  84102. */
  84103. get: function () {
  84104. return this.imageProcessingConfiguration.colorGradingEnabled;
  84105. },
  84106. /**
  84107. * Gets wether the color grading effect is enabled.
  84108. */
  84109. set: function (value) {
  84110. this.imageProcessingConfiguration.colorGradingEnabled = value;
  84111. },
  84112. enumerable: true,
  84113. configurable: true
  84114. });
  84115. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  84116. /**
  84117. * Gets exposure used in the effect.
  84118. */
  84119. get: function () {
  84120. return this.imageProcessingConfiguration.exposure;
  84121. },
  84122. /**
  84123. * Sets exposure used in the effect.
  84124. */
  84125. set: function (value) {
  84126. this.imageProcessingConfiguration.exposure = value;
  84127. },
  84128. enumerable: true,
  84129. configurable: true
  84130. });
  84131. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  84132. /**
  84133. * Gets wether tonemapping is enabled or not.
  84134. */
  84135. get: function () {
  84136. return this._imageProcessingConfiguration.toneMappingEnabled;
  84137. },
  84138. /**
  84139. * Sets wether tonemapping is enabled or not
  84140. */
  84141. set: function (value) {
  84142. this._imageProcessingConfiguration.toneMappingEnabled = value;
  84143. },
  84144. enumerable: true,
  84145. configurable: true
  84146. });
  84147. ;
  84148. ;
  84149. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  84150. /**
  84151. * Gets contrast used in the effect.
  84152. */
  84153. get: function () {
  84154. return this.imageProcessingConfiguration.contrast;
  84155. },
  84156. /**
  84157. * Sets contrast used in the effect.
  84158. */
  84159. set: function (value) {
  84160. this.imageProcessingConfiguration.contrast = value;
  84161. },
  84162. enumerable: true,
  84163. configurable: true
  84164. });
  84165. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  84166. /**
  84167. * Gets Vignette stretch size.
  84168. */
  84169. get: function () {
  84170. return this.imageProcessingConfiguration.vignetteStretch;
  84171. },
  84172. /**
  84173. * Sets Vignette stretch size.
  84174. */
  84175. set: function (value) {
  84176. this.imageProcessingConfiguration.vignetteStretch = value;
  84177. },
  84178. enumerable: true,
  84179. configurable: true
  84180. });
  84181. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  84182. /**
  84183. * Gets Vignette centre X Offset.
  84184. */
  84185. get: function () {
  84186. return this.imageProcessingConfiguration.vignetteCentreX;
  84187. },
  84188. /**
  84189. * Sets Vignette centre X Offset.
  84190. */
  84191. set: function (value) {
  84192. this.imageProcessingConfiguration.vignetteCentreX = value;
  84193. },
  84194. enumerable: true,
  84195. configurable: true
  84196. });
  84197. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  84198. /**
  84199. * Gets Vignette centre Y Offset.
  84200. */
  84201. get: function () {
  84202. return this.imageProcessingConfiguration.vignetteCentreY;
  84203. },
  84204. /**
  84205. * Sets Vignette centre Y Offset.
  84206. */
  84207. set: function (value) {
  84208. this.imageProcessingConfiguration.vignetteCentreY = value;
  84209. },
  84210. enumerable: true,
  84211. configurable: true
  84212. });
  84213. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  84214. /**
  84215. * Gets Vignette weight or intensity of the vignette effect.
  84216. */
  84217. get: function () {
  84218. return this.imageProcessingConfiguration.vignetteWeight;
  84219. },
  84220. /**
  84221. * Sets Vignette weight or intensity of the vignette effect.
  84222. */
  84223. set: function (value) {
  84224. this.imageProcessingConfiguration.vignetteWeight = value;
  84225. },
  84226. enumerable: true,
  84227. configurable: true
  84228. });
  84229. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  84230. /**
  84231. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84232. * if vignetteEnabled is set to true.
  84233. */
  84234. get: function () {
  84235. return this.imageProcessingConfiguration.vignetteColor;
  84236. },
  84237. /**
  84238. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84239. * if vignetteEnabled is set to true.
  84240. */
  84241. set: function (value) {
  84242. this.imageProcessingConfiguration.vignetteColor = value;
  84243. },
  84244. enumerable: true,
  84245. configurable: true
  84246. });
  84247. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  84248. /**
  84249. * Gets Camera field of view used by the Vignette effect.
  84250. */
  84251. get: function () {
  84252. return this.imageProcessingConfiguration.vignetteCameraFov;
  84253. },
  84254. /**
  84255. * Sets Camera field of view used by the Vignette effect.
  84256. */
  84257. set: function (value) {
  84258. this.imageProcessingConfiguration.vignetteCameraFov = value;
  84259. },
  84260. enumerable: true,
  84261. configurable: true
  84262. });
  84263. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  84264. /**
  84265. * Gets the vignette blend mode allowing different kind of effect.
  84266. */
  84267. get: function () {
  84268. return this.imageProcessingConfiguration.vignetteBlendMode;
  84269. },
  84270. /**
  84271. * Sets the vignette blend mode allowing different kind of effect.
  84272. */
  84273. set: function (value) {
  84274. this.imageProcessingConfiguration.vignetteBlendMode = value;
  84275. },
  84276. enumerable: true,
  84277. configurable: true
  84278. });
  84279. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  84280. /**
  84281. * Gets wether the vignette effect is enabled.
  84282. */
  84283. get: function () {
  84284. return this.imageProcessingConfiguration.vignetteEnabled;
  84285. },
  84286. /**
  84287. * Sets wether the vignette effect is enabled.
  84288. */
  84289. set: function (value) {
  84290. this.imageProcessingConfiguration.vignetteEnabled = value;
  84291. },
  84292. enumerable: true,
  84293. configurable: true
  84294. });
  84295. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  84296. /**
  84297. * Gets wether the input of the processing is in Gamma or Linear Space.
  84298. */
  84299. get: function () {
  84300. return this._fromLinearSpace;
  84301. },
  84302. /**
  84303. * Sets wether the input of the processing is in Gamma or Linear Space.
  84304. */
  84305. set: function (value) {
  84306. if (this._fromLinearSpace === value) {
  84307. return;
  84308. }
  84309. this._fromLinearSpace = value;
  84310. this._updateParameters();
  84311. },
  84312. enumerable: true,
  84313. configurable: true
  84314. });
  84315. ImageProcessingPostProcess.prototype.getClassName = function () {
  84316. return "ImageProcessingPostProcess";
  84317. };
  84318. ImageProcessingPostProcess.prototype._updateParameters = function () {
  84319. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  84320. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  84321. var defines = "";
  84322. for (var define in this._defines) {
  84323. if (this._defines[define]) {
  84324. defines += "#define " + define + ";\r\n";
  84325. }
  84326. }
  84327. var samplers = ["textureSampler"];
  84328. var uniforms = ["scale"];
  84329. if (BABYLON.ImageProcessingConfiguration) {
  84330. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  84331. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  84332. }
  84333. this.updateEffect(defines, uniforms, samplers);
  84334. };
  84335. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  84336. _super.prototype.dispose.call(this, camera);
  84337. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84338. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84339. }
  84340. if (this._imageProcessingConfiguration) {
  84341. this.imageProcessingConfiguration.applyByPostProcess = false;
  84342. }
  84343. };
  84344. __decorate([
  84345. BABYLON.serialize()
  84346. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  84347. return ImageProcessingPostProcess;
  84348. }(BABYLON.PostProcess));
  84349. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  84350. })(BABYLON || (BABYLON = {}));
  84351. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  84352. var BABYLON;
  84353. (function (BABYLON) {
  84354. /**
  84355. * Class used to store bone information
  84356. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84357. */
  84358. var Bone = /** @class */ (function (_super) {
  84359. __extends(Bone, _super);
  84360. /**
  84361. * Create a new bone
  84362. * @param name defines the bone name
  84363. * @param skeleton defines the parent skeleton
  84364. * @param parentBone defines the parent (can be null if the bone is the root)
  84365. * @param localMatrix defines the local matrix
  84366. * @param restPose defines the rest pose matrix
  84367. * @param baseMatrix defines the base matrix
  84368. * @param index defines index of the bone in the hiearchy
  84369. */
  84370. function Bone(
  84371. /**
  84372. * defines the bone name
  84373. */
  84374. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  84375. if (parentBone === void 0) { parentBone = null; }
  84376. if (localMatrix === void 0) { localMatrix = null; }
  84377. if (restPose === void 0) { restPose = null; }
  84378. if (baseMatrix === void 0) { baseMatrix = null; }
  84379. if (index === void 0) { index = null; }
  84380. var _this = _super.call(this, name, skeleton.getScene()) || this;
  84381. _this.name = name;
  84382. /**
  84383. * Gets the list of child bones
  84384. */
  84385. _this.children = new Array();
  84386. /** Gets the animations associated with this bone */
  84387. _this.animations = new Array();
  84388. /**
  84389. * @hidden Internal only
  84390. * Set this value to map this bone to a different index in the transform matrices
  84391. * Set this value to -1 to exclude the bone from the transform matrices
  84392. */
  84393. _this._index = null;
  84394. _this._absoluteTransform = new BABYLON.Matrix();
  84395. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  84396. _this._scalingDeterminant = 1;
  84397. _this._worldTransform = new BABYLON.Matrix();
  84398. _this._needToDecompose = true;
  84399. _this._needToCompose = false;
  84400. _this._skeleton = skeleton;
  84401. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  84402. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  84403. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  84404. _this._index = index;
  84405. skeleton.bones.push(_this);
  84406. _this.setParent(parentBone, false);
  84407. if (baseMatrix || localMatrix) {
  84408. _this._updateDifferenceMatrix();
  84409. }
  84410. return _this;
  84411. }
  84412. Object.defineProperty(Bone.prototype, "_matrix", {
  84413. /** @hidden */
  84414. get: function () {
  84415. this._compose();
  84416. return this._localMatrix;
  84417. },
  84418. /** @hidden */
  84419. set: function (value) {
  84420. this._localMatrix.copyFrom(value);
  84421. this._needToDecompose = true;
  84422. },
  84423. enumerable: true,
  84424. configurable: true
  84425. });
  84426. // Members
  84427. /**
  84428. * Gets the parent skeleton
  84429. * @returns a skeleton
  84430. */
  84431. Bone.prototype.getSkeleton = function () {
  84432. return this._skeleton;
  84433. };
  84434. /**
  84435. * Gets parent bone
  84436. * @returns a bone or null if the bone is the root of the bone hierarchy
  84437. */
  84438. Bone.prototype.getParent = function () {
  84439. return this._parent;
  84440. };
  84441. /**
  84442. * Sets the parent bone
  84443. * @param parent defines the parent (can be null if the bone is the root)
  84444. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84445. */
  84446. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  84447. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84448. if (this._parent === parent) {
  84449. return;
  84450. }
  84451. if (this._parent) {
  84452. var index = this._parent.children.indexOf(this);
  84453. if (index !== -1) {
  84454. this._parent.children.splice(index, 1);
  84455. }
  84456. }
  84457. this._parent = parent;
  84458. if (this._parent) {
  84459. this._parent.children.push(this);
  84460. }
  84461. if (updateDifferenceMatrix) {
  84462. this._updateDifferenceMatrix();
  84463. }
  84464. this.markAsDirty();
  84465. };
  84466. /**
  84467. * Gets the local matrix
  84468. * @returns a matrix
  84469. */
  84470. Bone.prototype.getLocalMatrix = function () {
  84471. this._compose();
  84472. return this._localMatrix;
  84473. };
  84474. /**
  84475. * Gets the base matrix (initial matrix which remains unchanged)
  84476. * @returns a matrix
  84477. */
  84478. Bone.prototype.getBaseMatrix = function () {
  84479. return this._baseMatrix;
  84480. };
  84481. /**
  84482. * Gets the rest pose matrix
  84483. * @returns a matrix
  84484. */
  84485. Bone.prototype.getRestPose = function () {
  84486. return this._restPose;
  84487. };
  84488. /**
  84489. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  84490. */
  84491. Bone.prototype.getWorldMatrix = function () {
  84492. return this._worldTransform;
  84493. };
  84494. /**
  84495. * Sets the local matrix to rest pose matrix
  84496. */
  84497. Bone.prototype.returnToRest = function () {
  84498. this.updateMatrix(this._restPose.clone());
  84499. };
  84500. /**
  84501. * Gets the inverse of the absolute transform matrix.
  84502. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  84503. * @returns a matrix
  84504. */
  84505. Bone.prototype.getInvertedAbsoluteTransform = function () {
  84506. return this._invertedAbsoluteTransform;
  84507. };
  84508. /**
  84509. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  84510. * @returns a matrix
  84511. */
  84512. Bone.prototype.getAbsoluteTransform = function () {
  84513. return this._absoluteTransform;
  84514. };
  84515. Object.defineProperty(Bone.prototype, "position", {
  84516. // Properties (matches AbstractMesh properties)
  84517. /** Gets or sets current position (in local space) */
  84518. get: function () {
  84519. this._decompose();
  84520. return this._localPosition;
  84521. },
  84522. set: function (newPosition) {
  84523. this._decompose();
  84524. this._localPosition.copyFrom(newPosition);
  84525. this._markAsDirtyAndCompose();
  84526. },
  84527. enumerable: true,
  84528. configurable: true
  84529. });
  84530. Object.defineProperty(Bone.prototype, "rotation", {
  84531. /** Gets or sets current rotation (in local space) */
  84532. get: function () {
  84533. return this.getRotation();
  84534. },
  84535. set: function (newRotation) {
  84536. this.setRotation(newRotation);
  84537. },
  84538. enumerable: true,
  84539. configurable: true
  84540. });
  84541. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  84542. /** Gets or sets current rotation quaternion (in local space) */
  84543. get: function () {
  84544. this._decompose();
  84545. return this._localRotation;
  84546. },
  84547. set: function (newRotation) {
  84548. this.setRotationQuaternion(newRotation);
  84549. },
  84550. enumerable: true,
  84551. configurable: true
  84552. });
  84553. Object.defineProperty(Bone.prototype, "scaling", {
  84554. /** Gets or sets current scaling (in local space) */
  84555. get: function () {
  84556. return this.getScale();
  84557. },
  84558. set: function (newScaling) {
  84559. this.setScale(newScaling);
  84560. },
  84561. enumerable: true,
  84562. configurable: true
  84563. });
  84564. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  84565. /**
  84566. * Gets the animation properties override
  84567. */
  84568. get: function () {
  84569. return this._skeleton.animationPropertiesOverride;
  84570. },
  84571. enumerable: true,
  84572. configurable: true
  84573. });
  84574. // Methods
  84575. Bone.prototype._decompose = function () {
  84576. if (!this._needToDecompose) {
  84577. return;
  84578. }
  84579. this._needToDecompose = false;
  84580. if (!this._localScaling) {
  84581. this._localScaling = BABYLON.Vector3.Zero();
  84582. this._localRotation = BABYLON.Quaternion.Zero();
  84583. this._localPosition = BABYLON.Vector3.Zero();
  84584. }
  84585. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  84586. };
  84587. Bone.prototype._compose = function () {
  84588. if (!this._needToCompose) {
  84589. return;
  84590. }
  84591. this._needToCompose = false;
  84592. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  84593. };
  84594. /**
  84595. * Update the base and local matrices
  84596. * @param matrix defines the new base or local matrix
  84597. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84598. * @param updateLocalMatrix defines if the local matrix should be updated
  84599. */
  84600. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  84601. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84602. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  84603. this._baseMatrix.copyFrom(matrix);
  84604. if (updateDifferenceMatrix) {
  84605. this._updateDifferenceMatrix();
  84606. }
  84607. if (updateLocalMatrix) {
  84608. this._localMatrix.copyFrom(matrix);
  84609. this._markAsDirtyAndDecompose();
  84610. }
  84611. else {
  84612. this.markAsDirty();
  84613. }
  84614. };
  84615. /** @hidden */
  84616. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  84617. if (updateChildren === void 0) { updateChildren = true; }
  84618. if (!rootMatrix) {
  84619. rootMatrix = this._baseMatrix;
  84620. }
  84621. if (this._parent) {
  84622. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84623. }
  84624. else {
  84625. this._absoluteTransform.copyFrom(rootMatrix);
  84626. }
  84627. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  84628. if (updateChildren) {
  84629. for (var index = 0; index < this.children.length; index++) {
  84630. this.children[index]._updateDifferenceMatrix();
  84631. }
  84632. }
  84633. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  84634. };
  84635. /**
  84636. * Flag the bone as dirty (Forcing it to update everything)
  84637. */
  84638. Bone.prototype.markAsDirty = function () {
  84639. this._currentRenderId++;
  84640. this._childRenderId++;
  84641. this._skeleton._markAsDirty();
  84642. };
  84643. Bone.prototype._markAsDirtyAndCompose = function () {
  84644. this.markAsDirty();
  84645. this._needToCompose = true;
  84646. };
  84647. Bone.prototype._markAsDirtyAndDecompose = function () {
  84648. this.markAsDirty();
  84649. this._needToDecompose = true;
  84650. };
  84651. /**
  84652. * Copy an animation range from another bone
  84653. * @param source defines the source bone
  84654. * @param rangeName defines the range name to copy
  84655. * @param frameOffset defines the frame offset
  84656. * @param rescaleAsRequired defines if rescaling must be applied if required
  84657. * @param skelDimensionsRatio defines the scaling ratio
  84658. * @returns true if operation was successful
  84659. */
  84660. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  84661. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84662. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  84663. // all animation may be coming from a library skeleton, so may need to create animation
  84664. if (this.animations.length === 0) {
  84665. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  84666. this.animations[0].setKeys([]);
  84667. }
  84668. // get animation info / verify there is such a range from the source bone
  84669. var sourceRange = source.animations[0].getRange(rangeName);
  84670. if (!sourceRange) {
  84671. return false;
  84672. }
  84673. var from = sourceRange.from;
  84674. var to = sourceRange.to;
  84675. var sourceKeys = source.animations[0].getKeys();
  84676. // rescaling prep
  84677. var sourceBoneLength = source.length;
  84678. var sourceParent = source.getParent();
  84679. var parent = this.getParent();
  84680. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  84681. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  84682. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  84683. var destKeys = this.animations[0].getKeys();
  84684. // loop vars declaration
  84685. var orig;
  84686. var origTranslation;
  84687. var mat;
  84688. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  84689. orig = sourceKeys[key];
  84690. if (orig.frame >= from && orig.frame <= to) {
  84691. if (rescaleAsRequired) {
  84692. mat = orig.value.clone();
  84693. // scale based on parent ratio, when bone has parent
  84694. if (parentScalingReqd) {
  84695. origTranslation = mat.getTranslation();
  84696. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  84697. // scale based on skeleton dimension ratio when root bone, and value is passed
  84698. }
  84699. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  84700. origTranslation = mat.getTranslation();
  84701. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  84702. // use original when root bone, and no data for skelDimensionsRatio
  84703. }
  84704. else {
  84705. mat = orig.value;
  84706. }
  84707. }
  84708. else {
  84709. mat = orig.value;
  84710. }
  84711. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  84712. }
  84713. }
  84714. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  84715. return true;
  84716. };
  84717. /**
  84718. * Translate the bone in local or world space
  84719. * @param vec The amount to translate the bone
  84720. * @param space The space that the translation is in
  84721. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84722. */
  84723. Bone.prototype.translate = function (vec, space, mesh) {
  84724. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84725. var lm = this.getLocalMatrix();
  84726. if (space == BABYLON.Space.LOCAL) {
  84727. lm.m[12] += vec.x;
  84728. lm.m[13] += vec.y;
  84729. lm.m[14] += vec.z;
  84730. }
  84731. else {
  84732. var wm = null;
  84733. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84734. if (mesh) {
  84735. wm = mesh.getWorldMatrix();
  84736. }
  84737. this._skeleton.computeAbsoluteTransforms();
  84738. var tmat = Bone._tmpMats[0];
  84739. var tvec = Bone._tmpVecs[0];
  84740. if (this._parent) {
  84741. if (mesh && wm) {
  84742. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84743. tmat.multiplyToRef(wm, tmat);
  84744. }
  84745. else {
  84746. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84747. }
  84748. }
  84749. tmat.m[12] = 0;
  84750. tmat.m[13] = 0;
  84751. tmat.m[14] = 0;
  84752. tmat.invert();
  84753. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  84754. lm.m[12] += tvec.x;
  84755. lm.m[13] += tvec.y;
  84756. lm.m[14] += tvec.z;
  84757. }
  84758. this._markAsDirtyAndDecompose();
  84759. };
  84760. /**
  84761. * Set the postion of the bone in local or world space
  84762. * @param position The position to set the bone
  84763. * @param space The space that the position is in
  84764. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84765. */
  84766. Bone.prototype.setPosition = function (position, space, mesh) {
  84767. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84768. var lm = this.getLocalMatrix();
  84769. if (space == BABYLON.Space.LOCAL) {
  84770. lm.m[12] = position.x;
  84771. lm.m[13] = position.y;
  84772. lm.m[14] = position.z;
  84773. }
  84774. else {
  84775. var wm = null;
  84776. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84777. if (mesh) {
  84778. wm = mesh.getWorldMatrix();
  84779. }
  84780. this._skeleton.computeAbsoluteTransforms();
  84781. var tmat = Bone._tmpMats[0];
  84782. var vec = Bone._tmpVecs[0];
  84783. if (this._parent) {
  84784. if (mesh && wm) {
  84785. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84786. tmat.multiplyToRef(wm, tmat);
  84787. }
  84788. else {
  84789. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84790. }
  84791. }
  84792. tmat.invert();
  84793. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  84794. lm.m[12] = vec.x;
  84795. lm.m[13] = vec.y;
  84796. lm.m[14] = vec.z;
  84797. }
  84798. this._markAsDirtyAndDecompose();
  84799. };
  84800. /**
  84801. * Set the absolute position of the bone (world space)
  84802. * @param position The position to set the bone
  84803. * @param mesh The mesh that this bone is attached to
  84804. */
  84805. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  84806. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  84807. };
  84808. /**
  84809. * Scale the bone on the x, y and z axes (in local space)
  84810. * @param x The amount to scale the bone on the x axis
  84811. * @param y The amount to scale the bone on the y axis
  84812. * @param z The amount to scale the bone on the z axis
  84813. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  84814. */
  84815. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  84816. if (scaleChildren === void 0) { scaleChildren = false; }
  84817. var locMat = this.getLocalMatrix();
  84818. // Apply new scaling on top of current local matrix
  84819. var scaleMat = Bone._tmpMats[0];
  84820. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  84821. scaleMat.multiplyToRef(locMat, locMat);
  84822. // Invert scaling matrix and apply the inverse to all children
  84823. scaleMat.invert();
  84824. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  84825. var child = _a[_i];
  84826. var cm = child.getLocalMatrix();
  84827. cm.multiplyToRef(scaleMat, cm);
  84828. cm.m[12] *= x;
  84829. cm.m[13] *= y;
  84830. cm.m[14] *= z;
  84831. child._markAsDirtyAndDecompose();
  84832. }
  84833. this._markAsDirtyAndDecompose();
  84834. if (scaleChildren) {
  84835. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  84836. var child = _c[_b];
  84837. child.scale(x, y, z, scaleChildren);
  84838. }
  84839. }
  84840. };
  84841. /**
  84842. * Set the bone scaling in local space
  84843. * @param scale defines the scaling vector
  84844. */
  84845. Bone.prototype.setScale = function (scale) {
  84846. this._decompose();
  84847. this._localScaling.copyFrom(scale);
  84848. this._markAsDirtyAndCompose();
  84849. };
  84850. /**
  84851. * Gets the current scaling in local space
  84852. * @returns the current scaling vector
  84853. */
  84854. Bone.prototype.getScale = function () {
  84855. this._decompose();
  84856. return this._localScaling;
  84857. };
  84858. /**
  84859. * Gets the current scaling in local space and stores it in a target vector
  84860. * @param result defines the target vector
  84861. */
  84862. Bone.prototype.getScaleToRef = function (result) {
  84863. this._decompose();
  84864. result.copyFrom(this._localScaling);
  84865. };
  84866. /**
  84867. * Set the yaw, pitch, and roll of the bone in local or world space
  84868. * @param yaw The rotation of the bone on the y axis
  84869. * @param pitch The rotation of the bone on the x axis
  84870. * @param roll The rotation of the bone on the z axis
  84871. * @param space The space that the axes of rotation are in
  84872. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84873. */
  84874. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  84875. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84876. if (space === BABYLON.Space.LOCAL) {
  84877. var quat = Bone._tmpQuat;
  84878. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  84879. this.setRotationQuaternion(quat, space, mesh);
  84880. return;
  84881. }
  84882. var rotMatInv = Bone._tmpMats[0];
  84883. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84884. return;
  84885. }
  84886. var rotMat = Bone._tmpMats[1];
  84887. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  84888. rotMatInv.multiplyToRef(rotMat, rotMat);
  84889. this._rotateWithMatrix(rotMat, space, mesh);
  84890. };
  84891. /**
  84892. * Add a rotation to the bone on an axis in local or world space
  84893. * @param axis The axis to rotate the bone on
  84894. * @param amount The amount to rotate the bone
  84895. * @param space The space that the axis is in
  84896. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84897. */
  84898. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  84899. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84900. var rmat = Bone._tmpMats[0];
  84901. rmat.m[12] = 0;
  84902. rmat.m[13] = 0;
  84903. rmat.m[14] = 0;
  84904. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  84905. this._rotateWithMatrix(rmat, space, mesh);
  84906. };
  84907. /**
  84908. * Set the rotation of the bone to a particular axis angle in local or world space
  84909. * @param axis The axis to rotate the bone on
  84910. * @param angle The angle that the bone should be rotated to
  84911. * @param space The space that the axis is in
  84912. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84913. */
  84914. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  84915. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84916. if (space === BABYLON.Space.LOCAL) {
  84917. var quat = Bone._tmpQuat;
  84918. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  84919. this.setRotationQuaternion(quat, space, mesh);
  84920. return;
  84921. }
  84922. var rotMatInv = Bone._tmpMats[0];
  84923. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84924. return;
  84925. }
  84926. var rotMat = Bone._tmpMats[1];
  84927. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  84928. rotMatInv.multiplyToRef(rotMat, rotMat);
  84929. this._rotateWithMatrix(rotMat, space, mesh);
  84930. };
  84931. /**
  84932. * Set the euler rotation of the bone in local of world space
  84933. * @param rotation The euler rotation that the bone should be set to
  84934. * @param space The space that the rotation is in
  84935. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84936. */
  84937. Bone.prototype.setRotation = function (rotation, space, mesh) {
  84938. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84939. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  84940. };
  84941. /**
  84942. * Set the quaternion rotation of the bone in local of world space
  84943. * @param quat The quaternion rotation that the bone should be set to
  84944. * @param space The space that the rotation is in
  84945. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84946. */
  84947. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  84948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84949. if (space === BABYLON.Space.LOCAL) {
  84950. this._decompose();
  84951. this._localRotation.copyFrom(quat);
  84952. this._markAsDirtyAndCompose();
  84953. return;
  84954. }
  84955. var rotMatInv = Bone._tmpMats[0];
  84956. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84957. return;
  84958. }
  84959. var rotMat = Bone._tmpMats[1];
  84960. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  84961. rotMatInv.multiplyToRef(rotMat, rotMat);
  84962. this._rotateWithMatrix(rotMat, space, mesh);
  84963. };
  84964. /**
  84965. * Set the rotation matrix of the bone in local of world space
  84966. * @param rotMat The rotation matrix that the bone should be set to
  84967. * @param space The space that the rotation is in
  84968. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84969. */
  84970. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  84971. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84972. if (space === BABYLON.Space.LOCAL) {
  84973. var quat = Bone._tmpQuat;
  84974. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  84975. this.setRotationQuaternion(quat, space, mesh);
  84976. return;
  84977. }
  84978. var rotMatInv = Bone._tmpMats[0];
  84979. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84980. return;
  84981. }
  84982. var rotMat2 = Bone._tmpMats[1];
  84983. rotMat2.copyFrom(rotMat);
  84984. rotMatInv.multiplyToRef(rotMat, rotMat2);
  84985. this._rotateWithMatrix(rotMat2, space, mesh);
  84986. };
  84987. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  84988. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84989. var lmat = this.getLocalMatrix();
  84990. var lx = lmat.m[12];
  84991. var ly = lmat.m[13];
  84992. var lz = lmat.m[14];
  84993. var parent = this.getParent();
  84994. var parentScale = Bone._tmpMats[3];
  84995. var parentScaleInv = Bone._tmpMats[4];
  84996. if (parent && space == BABYLON.Space.WORLD) {
  84997. if (mesh) {
  84998. parentScale.copyFrom(mesh.getWorldMatrix());
  84999. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  85000. }
  85001. else {
  85002. parentScale.copyFrom(parent.getAbsoluteTransform());
  85003. }
  85004. parentScaleInv.copyFrom(parentScale);
  85005. parentScaleInv.invert();
  85006. lmat.multiplyToRef(parentScale, lmat);
  85007. lmat.multiplyToRef(rmat, lmat);
  85008. lmat.multiplyToRef(parentScaleInv, lmat);
  85009. }
  85010. else {
  85011. if (space == BABYLON.Space.WORLD && mesh) {
  85012. parentScale.copyFrom(mesh.getWorldMatrix());
  85013. parentScaleInv.copyFrom(parentScale);
  85014. parentScaleInv.invert();
  85015. lmat.multiplyToRef(parentScale, lmat);
  85016. lmat.multiplyToRef(rmat, lmat);
  85017. lmat.multiplyToRef(parentScaleInv, lmat);
  85018. }
  85019. else {
  85020. lmat.multiplyToRef(rmat, lmat);
  85021. }
  85022. }
  85023. lmat.m[12] = lx;
  85024. lmat.m[13] = ly;
  85025. lmat.m[14] = lz;
  85026. this.computeAbsoluteTransforms();
  85027. this._markAsDirtyAndDecompose();
  85028. };
  85029. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  85030. var scaleMatrix = Bone._tmpMats[2];
  85031. rotMatInv.copyFrom(this.getAbsoluteTransform());
  85032. if (mesh) {
  85033. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  85034. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  85035. }
  85036. rotMatInv.invert();
  85037. if (isNaN(rotMatInv.m[0])) {
  85038. // Matrix failed to invert.
  85039. // This can happen if scale is zero for example.
  85040. return false;
  85041. }
  85042. scaleMatrix.m[0] *= this._scalingDeterminant;
  85043. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  85044. return true;
  85045. };
  85046. /**
  85047. * Get the position of the bone in local or world space
  85048. * @param space The space that the returned position is in
  85049. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85050. * @returns The position of the bone
  85051. */
  85052. Bone.prototype.getPosition = function (space, mesh) {
  85053. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85054. if (mesh === void 0) { mesh = null; }
  85055. var pos = BABYLON.Vector3.Zero();
  85056. this.getPositionToRef(space, mesh, pos);
  85057. return pos;
  85058. };
  85059. /**
  85060. * Copy the position of the bone to a vector3 in local or world space
  85061. * @param space The space that the returned position is in
  85062. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85063. * @param result The vector3 to copy the position to
  85064. */
  85065. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  85066. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85067. if (space == BABYLON.Space.LOCAL) {
  85068. var lm = this.getLocalMatrix();
  85069. result.x = lm.m[12];
  85070. result.y = lm.m[13];
  85071. result.z = lm.m[14];
  85072. }
  85073. else {
  85074. var wm = null;
  85075. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85076. if (mesh) {
  85077. wm = mesh.getWorldMatrix();
  85078. }
  85079. this._skeleton.computeAbsoluteTransforms();
  85080. var tmat = Bone._tmpMats[0];
  85081. if (mesh && wm) {
  85082. tmat.copyFrom(this.getAbsoluteTransform());
  85083. tmat.multiplyToRef(wm, tmat);
  85084. }
  85085. else {
  85086. tmat = this.getAbsoluteTransform();
  85087. }
  85088. result.x = tmat.m[12];
  85089. result.y = tmat.m[13];
  85090. result.z = tmat.m[14];
  85091. }
  85092. };
  85093. /**
  85094. * Get the absolute position of the bone (world space)
  85095. * @param mesh The mesh that this bone is attached to
  85096. * @returns The absolute position of the bone
  85097. */
  85098. Bone.prototype.getAbsolutePosition = function (mesh) {
  85099. if (mesh === void 0) { mesh = null; }
  85100. var pos = BABYLON.Vector3.Zero();
  85101. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  85102. return pos;
  85103. };
  85104. /**
  85105. * Copy the absolute position of the bone (world space) to the result param
  85106. * @param mesh The mesh that this bone is attached to
  85107. * @param result The vector3 to copy the absolute position to
  85108. */
  85109. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  85110. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  85111. };
  85112. /**
  85113. * Compute the absolute transforms of this bone and its children
  85114. */
  85115. Bone.prototype.computeAbsoluteTransforms = function () {
  85116. this._compose();
  85117. if (this._parent) {
  85118. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  85119. }
  85120. else {
  85121. this._absoluteTransform.copyFrom(this._localMatrix);
  85122. var poseMatrix = this._skeleton.getPoseMatrix();
  85123. if (poseMatrix) {
  85124. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  85125. }
  85126. }
  85127. var children = this.children;
  85128. var len = children.length;
  85129. for (var i = 0; i < len; i++) {
  85130. children[i].computeAbsoluteTransforms();
  85131. }
  85132. };
  85133. /**
  85134. * Get the world direction from an axis that is in the local space of the bone
  85135. * @param localAxis The local direction that is used to compute the world direction
  85136. * @param mesh The mesh that this bone is attached to
  85137. * @returns The world direction
  85138. */
  85139. Bone.prototype.getDirection = function (localAxis, mesh) {
  85140. if (mesh === void 0) { mesh = null; }
  85141. var result = BABYLON.Vector3.Zero();
  85142. this.getDirectionToRef(localAxis, mesh, result);
  85143. return result;
  85144. };
  85145. /**
  85146. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  85147. * @param localAxis The local direction that is used to compute the world direction
  85148. * @param mesh The mesh that this bone is attached to
  85149. * @param result The vector3 that the world direction will be copied to
  85150. */
  85151. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  85152. if (mesh === void 0) { mesh = null; }
  85153. var wm = null;
  85154. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85155. if (mesh) {
  85156. wm = mesh.getWorldMatrix();
  85157. }
  85158. this._skeleton.computeAbsoluteTransforms();
  85159. var mat = Bone._tmpMats[0];
  85160. mat.copyFrom(this.getAbsoluteTransform());
  85161. if (mesh && wm) {
  85162. mat.multiplyToRef(wm, mat);
  85163. }
  85164. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  85165. result.normalize();
  85166. };
  85167. /**
  85168. * Get the euler rotation of the bone in local or world space
  85169. * @param space The space that the rotation should be in
  85170. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85171. * @returns The euler rotation
  85172. */
  85173. Bone.prototype.getRotation = function (space, mesh) {
  85174. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85175. if (mesh === void 0) { mesh = null; }
  85176. var result = BABYLON.Vector3.Zero();
  85177. this.getRotationToRef(space, mesh, result);
  85178. return result;
  85179. };
  85180. /**
  85181. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  85182. * @param space The space that the rotation should be in
  85183. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85184. * @param result The vector3 that the rotation should be copied to
  85185. */
  85186. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  85187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85188. if (mesh === void 0) { mesh = null; }
  85189. var quat = Bone._tmpQuat;
  85190. this.getRotationQuaternionToRef(space, mesh, quat);
  85191. quat.toEulerAnglesToRef(result);
  85192. };
  85193. /**
  85194. * Get the quaternion rotation of the bone in either local or world space
  85195. * @param space The space that the rotation should be in
  85196. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85197. * @returns The quaternion rotation
  85198. */
  85199. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  85200. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85201. if (mesh === void 0) { mesh = null; }
  85202. var result = BABYLON.Quaternion.Identity();
  85203. this.getRotationQuaternionToRef(space, mesh, result);
  85204. return result;
  85205. };
  85206. /**
  85207. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  85208. * @param space The space that the rotation should be in
  85209. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85210. * @param result The quaternion that the rotation should be copied to
  85211. */
  85212. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  85213. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85214. if (mesh === void 0) { mesh = null; }
  85215. if (space == BABYLON.Space.LOCAL) {
  85216. this._decompose();
  85217. result.copyFrom(this._localRotation);
  85218. }
  85219. else {
  85220. var mat = Bone._tmpMats[0];
  85221. var amat = this.getAbsoluteTransform();
  85222. if (mesh) {
  85223. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85224. }
  85225. else {
  85226. mat.copyFrom(amat);
  85227. }
  85228. mat.m[0] *= this._scalingDeterminant;
  85229. mat.m[1] *= this._scalingDeterminant;
  85230. mat.m[2] *= this._scalingDeterminant;
  85231. mat.decompose(undefined, result, undefined);
  85232. }
  85233. };
  85234. /**
  85235. * Get the rotation matrix of the bone in local or world space
  85236. * @param space The space that the rotation should be in
  85237. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85238. * @returns The rotation matrix
  85239. */
  85240. Bone.prototype.getRotationMatrix = function (space, mesh) {
  85241. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85242. var result = BABYLON.Matrix.Identity();
  85243. this.getRotationMatrixToRef(space, mesh, result);
  85244. return result;
  85245. };
  85246. /**
  85247. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  85248. * @param space The space that the rotation should be in
  85249. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85250. * @param result The quaternion that the rotation should be copied to
  85251. */
  85252. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  85253. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85254. if (space == BABYLON.Space.LOCAL) {
  85255. this.getLocalMatrix().getRotationMatrixToRef(result);
  85256. }
  85257. else {
  85258. var mat = Bone._tmpMats[0];
  85259. var amat = this.getAbsoluteTransform();
  85260. if (mesh) {
  85261. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85262. }
  85263. else {
  85264. mat.copyFrom(amat);
  85265. }
  85266. mat.m[0] *= this._scalingDeterminant;
  85267. mat.m[1] *= this._scalingDeterminant;
  85268. mat.m[2] *= this._scalingDeterminant;
  85269. mat.getRotationMatrixToRef(result);
  85270. }
  85271. };
  85272. /**
  85273. * Get the world position of a point that is in the local space of the bone
  85274. * @param position The local position
  85275. * @param mesh The mesh that this bone is attached to
  85276. * @returns The world position
  85277. */
  85278. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  85279. if (mesh === void 0) { mesh = null; }
  85280. var result = BABYLON.Vector3.Zero();
  85281. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  85282. return result;
  85283. };
  85284. /**
  85285. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  85286. * @param position The local position
  85287. * @param mesh The mesh that this bone is attached to
  85288. * @param result The vector3 that the world position should be copied to
  85289. */
  85290. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  85291. if (mesh === void 0) { mesh = null; }
  85292. var wm = null;
  85293. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85294. if (mesh) {
  85295. wm = mesh.getWorldMatrix();
  85296. }
  85297. this._skeleton.computeAbsoluteTransforms();
  85298. var tmat = Bone._tmpMats[0];
  85299. if (mesh && wm) {
  85300. tmat.copyFrom(this.getAbsoluteTransform());
  85301. tmat.multiplyToRef(wm, tmat);
  85302. }
  85303. else {
  85304. tmat = this.getAbsoluteTransform();
  85305. }
  85306. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85307. };
  85308. /**
  85309. * Get the local position of a point that is in world space
  85310. * @param position The world position
  85311. * @param mesh The mesh that this bone is attached to
  85312. * @returns The local position
  85313. */
  85314. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  85315. if (mesh === void 0) { mesh = null; }
  85316. var result = BABYLON.Vector3.Zero();
  85317. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  85318. return result;
  85319. };
  85320. /**
  85321. * Get the local position of a point that is in world space and copy it to the result param
  85322. * @param position The world position
  85323. * @param mesh The mesh that this bone is attached to
  85324. * @param result The vector3 that the local position should be copied to
  85325. */
  85326. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  85327. if (mesh === void 0) { mesh = null; }
  85328. var wm = null;
  85329. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85330. if (mesh) {
  85331. wm = mesh.getWorldMatrix();
  85332. }
  85333. this._skeleton.computeAbsoluteTransforms();
  85334. var tmat = Bone._tmpMats[0];
  85335. tmat.copyFrom(this.getAbsoluteTransform());
  85336. if (mesh && wm) {
  85337. tmat.multiplyToRef(wm, tmat);
  85338. }
  85339. tmat.invert();
  85340. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85341. };
  85342. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85343. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  85344. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85345. return Bone;
  85346. }(BABYLON.Node));
  85347. BABYLON.Bone = Bone;
  85348. })(BABYLON || (BABYLON = {}));
  85349. //# sourceMappingURL=babylon.bone.js.map
  85350. var BABYLON;
  85351. (function (BABYLON) {
  85352. /**
  85353. * Class used to apply inverse kinematics to bones
  85354. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  85355. */
  85356. var BoneIKController = /** @class */ (function () {
  85357. /**
  85358. * Creates a new BoneIKController
  85359. * @param mesh defines the mesh to control
  85360. * @param bone defines the bone to control
  85361. * @param options defines options to set up the controller
  85362. */
  85363. function BoneIKController(mesh, bone, options) {
  85364. /**
  85365. * Gets or sets the target position
  85366. */
  85367. this.targetPosition = BABYLON.Vector3.Zero();
  85368. /**
  85369. * Gets or sets the pole target position
  85370. */
  85371. this.poleTargetPosition = BABYLON.Vector3.Zero();
  85372. /**
  85373. * Gets or sets the pole target local offset
  85374. */
  85375. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  85376. /**
  85377. * Gets or sets the pole angle
  85378. */
  85379. this.poleAngle = 0;
  85380. /**
  85381. * 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)
  85382. */
  85383. this.slerpAmount = 1;
  85384. this._bone1Quat = BABYLON.Quaternion.Identity();
  85385. this._bone1Mat = BABYLON.Matrix.Identity();
  85386. this._bone2Ang = Math.PI;
  85387. this._maxAngle = Math.PI;
  85388. this._rightHandedSystem = false;
  85389. this._bendAxis = BABYLON.Vector3.Right();
  85390. this._slerping = false;
  85391. this._adjustRoll = 0;
  85392. this._bone2 = bone;
  85393. this._bone1 = bone.getParent();
  85394. if (!this._bone1) {
  85395. return;
  85396. }
  85397. this.mesh = mesh;
  85398. var bonePos = bone.getPosition();
  85399. if (bone.getAbsoluteTransform().determinant() > 0) {
  85400. this._rightHandedSystem = true;
  85401. this._bendAxis.x = 0;
  85402. this._bendAxis.y = 0;
  85403. this._bendAxis.z = -1;
  85404. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  85405. this._adjustRoll = Math.PI * .5;
  85406. this._bendAxis.z = 1;
  85407. }
  85408. }
  85409. if (this._bone1.length) {
  85410. var boneScale1 = this._bone1.getScale();
  85411. var boneScale2 = this._bone2.getScale();
  85412. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  85413. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  85414. }
  85415. else if (this._bone1.children[0]) {
  85416. mesh.computeWorldMatrix(true);
  85417. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  85418. var pos2 = this._bone2.getAbsolutePosition(mesh);
  85419. var pos3 = this._bone1.getAbsolutePosition(mesh);
  85420. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  85421. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  85422. }
  85423. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  85424. this.maxAngle = Math.PI;
  85425. if (options) {
  85426. if (options.targetMesh) {
  85427. this.targetMesh = options.targetMesh;
  85428. this.targetMesh.computeWorldMatrix(true);
  85429. }
  85430. if (options.poleTargetMesh) {
  85431. this.poleTargetMesh = options.poleTargetMesh;
  85432. this.poleTargetMesh.computeWorldMatrix(true);
  85433. }
  85434. else if (options.poleTargetBone) {
  85435. this.poleTargetBone = options.poleTargetBone;
  85436. }
  85437. else if (this._bone1.getParent()) {
  85438. this.poleTargetBone = this._bone1.getParent();
  85439. }
  85440. if (options.poleTargetLocalOffset) {
  85441. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  85442. }
  85443. if (options.poleAngle) {
  85444. this.poleAngle = options.poleAngle;
  85445. }
  85446. if (options.bendAxis) {
  85447. this._bendAxis.copyFrom(options.bendAxis);
  85448. }
  85449. if (options.maxAngle) {
  85450. this.maxAngle = options.maxAngle;
  85451. }
  85452. if (options.slerpAmount) {
  85453. this.slerpAmount = options.slerpAmount;
  85454. }
  85455. }
  85456. }
  85457. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  85458. /**
  85459. * Gets or sets maximum allowed angle
  85460. */
  85461. get: function () {
  85462. return this._maxAngle;
  85463. },
  85464. set: function (value) {
  85465. this._setMaxAngle(value);
  85466. },
  85467. enumerable: true,
  85468. configurable: true
  85469. });
  85470. BoneIKController.prototype._setMaxAngle = function (ang) {
  85471. if (ang < 0) {
  85472. ang = 0;
  85473. }
  85474. if (ang > Math.PI || ang == undefined) {
  85475. ang = Math.PI;
  85476. }
  85477. this._maxAngle = ang;
  85478. var a = this._bone1Length;
  85479. var b = this._bone2Length;
  85480. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  85481. };
  85482. /**
  85483. * Force the controller to update the bones
  85484. */
  85485. BoneIKController.prototype.update = function () {
  85486. var bone1 = this._bone1;
  85487. if (!bone1) {
  85488. return;
  85489. }
  85490. var target = this.targetPosition;
  85491. var poleTarget = this.poleTargetPosition;
  85492. var mat1 = BoneIKController._tmpMats[0];
  85493. var mat2 = BoneIKController._tmpMats[1];
  85494. if (this.targetMesh) {
  85495. target.copyFrom(this.targetMesh.getAbsolutePosition());
  85496. }
  85497. if (this.poleTargetBone) {
  85498. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  85499. }
  85500. else if (this.poleTargetMesh) {
  85501. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  85502. }
  85503. var bonePos = BoneIKController._tmpVecs[0];
  85504. var zaxis = BoneIKController._tmpVecs[1];
  85505. var xaxis = BoneIKController._tmpVecs[2];
  85506. var yaxis = BoneIKController._tmpVecs[3];
  85507. var upAxis = BoneIKController._tmpVecs[4];
  85508. var _tmpQuat = BoneIKController._tmpQuat;
  85509. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  85510. poleTarget.subtractToRef(bonePos, upAxis);
  85511. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  85512. upAxis.y = 1;
  85513. }
  85514. else {
  85515. upAxis.normalize();
  85516. }
  85517. target.subtractToRef(bonePos, yaxis);
  85518. yaxis.normalize();
  85519. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  85520. zaxis.normalize();
  85521. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  85522. xaxis.normalize();
  85523. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  85524. var a = this._bone1Length;
  85525. var b = this._bone2Length;
  85526. var c = BABYLON.Vector3.Distance(bonePos, target);
  85527. if (this._maxReach > 0) {
  85528. c = Math.min(this._maxReach, c);
  85529. }
  85530. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  85531. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  85532. if (acosa > 1) {
  85533. acosa = 1;
  85534. }
  85535. if (acosb > 1) {
  85536. acosb = 1;
  85537. }
  85538. if (acosa < -1) {
  85539. acosa = -1;
  85540. }
  85541. if (acosb < -1) {
  85542. acosb = -1;
  85543. }
  85544. var angA = Math.acos(acosa);
  85545. var angB = Math.acos(acosb);
  85546. var angC = -angA - angB;
  85547. if (this._rightHandedSystem) {
  85548. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  85549. mat2.multiplyToRef(mat1, mat1);
  85550. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  85551. mat2.multiplyToRef(mat1, mat1);
  85552. }
  85553. else {
  85554. var _tmpVec = BoneIKController._tmpVecs[5];
  85555. _tmpVec.copyFrom(this._bendAxis);
  85556. _tmpVec.x *= -1;
  85557. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  85558. mat2.multiplyToRef(mat1, mat1);
  85559. }
  85560. if (this.poleAngle) {
  85561. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  85562. mat1.multiplyToRef(mat2, mat1);
  85563. }
  85564. if (this._bone1) {
  85565. if (this.slerpAmount < 1) {
  85566. if (!this._slerping) {
  85567. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  85568. }
  85569. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  85570. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  85571. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  85572. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  85573. this._slerping = true;
  85574. }
  85575. else {
  85576. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  85577. this._bone1Mat.copyFrom(mat1);
  85578. this._slerping = false;
  85579. }
  85580. }
  85581. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  85582. this._bone2Ang = angC;
  85583. };
  85584. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85585. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  85586. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85587. return BoneIKController;
  85588. }());
  85589. BABYLON.BoneIKController = BoneIKController;
  85590. })(BABYLON || (BABYLON = {}));
  85591. //# sourceMappingURL=babylon.boneIKController.js.map
  85592. var BABYLON;
  85593. (function (BABYLON) {
  85594. /**
  85595. * Class used to make a bone look toward a point in space
  85596. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  85597. */
  85598. var BoneLookController = /** @class */ (function () {
  85599. /**
  85600. * Create a BoneLookController
  85601. * @param mesh the mesh that the bone belongs to
  85602. * @param bone the bone that will be looking to the target
  85603. * @param target the target Vector3 to look at
  85604. * @param settings optional settings:
  85605. * * maxYaw: the maximum angle the bone will yaw to
  85606. * * minYaw: the minimum angle the bone will yaw to
  85607. * * maxPitch: the maximum angle the bone will pitch to
  85608. * * minPitch: the minimum angle the bone will yaw to
  85609. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  85610. * * upAxis: the up axis of the coordinate system
  85611. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  85612. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  85613. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  85614. * * adjustYaw: used to make an adjustment to the yaw of the bone
  85615. * * adjustPitch: used to make an adjustment to the pitch of the bone
  85616. * * adjustRoll: used to make an adjustment to the roll of the bone
  85617. **/
  85618. function BoneLookController(mesh, bone, target, options) {
  85619. /**
  85620. * The up axis of the coordinate system that is used when the bone is rotated
  85621. */
  85622. this.upAxis = BABYLON.Vector3.Up();
  85623. /**
  85624. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  85625. */
  85626. this.upAxisSpace = BABYLON.Space.LOCAL;
  85627. /**
  85628. * Used to make an adjustment to the yaw of the bone
  85629. */
  85630. this.adjustYaw = 0;
  85631. /**
  85632. * Used to make an adjustment to the pitch of the bone
  85633. */
  85634. this.adjustPitch = 0;
  85635. /**
  85636. * Used to make an adjustment to the roll of the bone
  85637. */
  85638. this.adjustRoll = 0;
  85639. /**
  85640. * 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)
  85641. */
  85642. this.slerpAmount = 1;
  85643. this._boneQuat = BABYLON.Quaternion.Identity();
  85644. this._slerping = false;
  85645. this._firstFrameSkipped = false;
  85646. this._fowardAxis = BABYLON.Vector3.Forward();
  85647. this.mesh = mesh;
  85648. this.bone = bone;
  85649. this.target = target;
  85650. if (options) {
  85651. if (options.adjustYaw) {
  85652. this.adjustYaw = options.adjustYaw;
  85653. }
  85654. if (options.adjustPitch) {
  85655. this.adjustPitch = options.adjustPitch;
  85656. }
  85657. if (options.adjustRoll) {
  85658. this.adjustRoll = options.adjustRoll;
  85659. }
  85660. if (options.maxYaw != null) {
  85661. this.maxYaw = options.maxYaw;
  85662. }
  85663. else {
  85664. this.maxYaw = Math.PI;
  85665. }
  85666. if (options.minYaw != null) {
  85667. this.minYaw = options.minYaw;
  85668. }
  85669. else {
  85670. this.minYaw = -Math.PI;
  85671. }
  85672. if (options.maxPitch != null) {
  85673. this.maxPitch = options.maxPitch;
  85674. }
  85675. else {
  85676. this.maxPitch = Math.PI;
  85677. }
  85678. if (options.minPitch != null) {
  85679. this.minPitch = options.minPitch;
  85680. }
  85681. else {
  85682. this.minPitch = -Math.PI;
  85683. }
  85684. if (options.slerpAmount != null) {
  85685. this.slerpAmount = options.slerpAmount;
  85686. }
  85687. if (options.upAxis != null) {
  85688. this.upAxis = options.upAxis;
  85689. }
  85690. if (options.upAxisSpace != null) {
  85691. this.upAxisSpace = options.upAxisSpace;
  85692. }
  85693. if (options.yawAxis != null || options.pitchAxis != null) {
  85694. var newYawAxis = BABYLON.Axis.Y;
  85695. var newPitchAxis = BABYLON.Axis.X;
  85696. if (options.yawAxis != null) {
  85697. newYawAxis = options.yawAxis.clone();
  85698. newYawAxis.normalize();
  85699. }
  85700. if (options.pitchAxis != null) {
  85701. newPitchAxis = options.pitchAxis.clone();
  85702. newPitchAxis.normalize();
  85703. }
  85704. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  85705. this._transformYawPitch = BABYLON.Matrix.Identity();
  85706. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  85707. this._transformYawPitchInv = this._transformYawPitch.clone();
  85708. this._transformYawPitch.invert();
  85709. }
  85710. }
  85711. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  85712. this.upAxisSpace = BABYLON.Space.LOCAL;
  85713. }
  85714. }
  85715. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  85716. /**
  85717. * Gets or sets the minimum yaw angle that the bone can look to
  85718. */
  85719. get: function () {
  85720. return this._minYaw;
  85721. },
  85722. set: function (value) {
  85723. this._minYaw = value;
  85724. this._minYawSin = Math.sin(value);
  85725. this._minYawCos = Math.cos(value);
  85726. if (this._maxYaw != null) {
  85727. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85728. this._yawRange = this._maxYaw - this._minYaw;
  85729. }
  85730. },
  85731. enumerable: true,
  85732. configurable: true
  85733. });
  85734. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  85735. /**
  85736. * Gets or sets the maximum yaw angle that the bone can look to
  85737. */
  85738. get: function () {
  85739. return this._maxYaw;
  85740. },
  85741. set: function (value) {
  85742. this._maxYaw = value;
  85743. this._maxYawSin = Math.sin(value);
  85744. this._maxYawCos = Math.cos(value);
  85745. if (this._minYaw != null) {
  85746. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85747. this._yawRange = this._maxYaw - this._minYaw;
  85748. }
  85749. },
  85750. enumerable: true,
  85751. configurable: true
  85752. });
  85753. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  85754. /**
  85755. * Gets or sets the minimum pitch angle that the bone can look to
  85756. */
  85757. get: function () {
  85758. return this._minPitch;
  85759. },
  85760. set: function (value) {
  85761. this._minPitch = value;
  85762. this._minPitchTan = Math.tan(value);
  85763. },
  85764. enumerable: true,
  85765. configurable: true
  85766. });
  85767. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  85768. /**
  85769. * Gets or sets the maximum pitch angle that the bone can look to
  85770. */
  85771. get: function () {
  85772. return this._maxPitch;
  85773. },
  85774. set: function (value) {
  85775. this._maxPitch = value;
  85776. this._maxPitchTan = Math.tan(value);
  85777. },
  85778. enumerable: true,
  85779. configurable: true
  85780. });
  85781. /**
  85782. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  85783. */
  85784. BoneLookController.prototype.update = function () {
  85785. //skip the first frame when slerping so that the mesh rotation is correct
  85786. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  85787. this._firstFrameSkipped = true;
  85788. return;
  85789. }
  85790. var bone = this.bone;
  85791. var bonePos = BoneLookController._tmpVecs[0];
  85792. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  85793. var target = this.target;
  85794. var _tmpMat1 = BoneLookController._tmpMats[0];
  85795. var _tmpMat2 = BoneLookController._tmpMats[1];
  85796. var mesh = this.mesh;
  85797. var parentBone = bone.getParent();
  85798. var upAxis = BoneLookController._tmpVecs[1];
  85799. upAxis.copyFrom(this.upAxis);
  85800. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  85801. if (this._transformYawPitch) {
  85802. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  85803. }
  85804. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  85805. }
  85806. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  85807. mesh.getDirectionToRef(upAxis, upAxis);
  85808. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  85809. upAxis.normalize();
  85810. }
  85811. }
  85812. var checkYaw = false;
  85813. var checkPitch = false;
  85814. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  85815. checkYaw = true;
  85816. }
  85817. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  85818. checkPitch = true;
  85819. }
  85820. if (checkYaw || checkPitch) {
  85821. var spaceMat = BoneLookController._tmpMats[2];
  85822. var spaceMatInv = BoneLookController._tmpMats[3];
  85823. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  85824. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  85825. }
  85826. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  85827. spaceMat.copyFrom(mesh.getWorldMatrix());
  85828. }
  85829. else {
  85830. var forwardAxis = BoneLookController._tmpVecs[2];
  85831. forwardAxis.copyFrom(this._fowardAxis);
  85832. if (this._transformYawPitch) {
  85833. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  85834. }
  85835. if (parentBone) {
  85836. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  85837. }
  85838. else {
  85839. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  85840. }
  85841. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  85842. rightAxis.normalize();
  85843. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  85844. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  85845. }
  85846. spaceMat.invertToRef(spaceMatInv);
  85847. var xzlen = null;
  85848. if (checkPitch) {
  85849. var localTarget = BoneLookController._tmpVecs[3];
  85850. target.subtractToRef(bonePos, localTarget);
  85851. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85852. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85853. var pitch = Math.atan2(localTarget.y, xzlen);
  85854. var newPitch = pitch;
  85855. if (pitch > this._maxPitch) {
  85856. localTarget.y = this._maxPitchTan * xzlen;
  85857. newPitch = this._maxPitch;
  85858. }
  85859. else if (pitch < this._minPitch) {
  85860. localTarget.y = this._minPitchTan * xzlen;
  85861. newPitch = this._minPitch;
  85862. }
  85863. if (pitch != newPitch) {
  85864. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85865. localTarget.addInPlace(bonePos);
  85866. target = localTarget;
  85867. }
  85868. }
  85869. if (checkYaw) {
  85870. var localTarget = BoneLookController._tmpVecs[4];
  85871. target.subtractToRef(bonePos, localTarget);
  85872. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85873. var yaw = Math.atan2(localTarget.x, localTarget.z);
  85874. var newYaw = yaw;
  85875. if (yaw > this._maxYaw || yaw < this._minYaw) {
  85876. if (xzlen == null) {
  85877. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85878. }
  85879. if (this._yawRange > Math.PI) {
  85880. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  85881. localTarget.z = this._maxYawCos * xzlen;
  85882. localTarget.x = this._maxYawSin * xzlen;
  85883. newYaw = this._maxYaw;
  85884. }
  85885. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  85886. localTarget.z = this._minYawCos * xzlen;
  85887. localTarget.x = this._minYawSin * xzlen;
  85888. newYaw = this._minYaw;
  85889. }
  85890. }
  85891. else {
  85892. if (yaw > this._maxYaw) {
  85893. localTarget.z = this._maxYawCos * xzlen;
  85894. localTarget.x = this._maxYawSin * xzlen;
  85895. newYaw = this._maxYaw;
  85896. }
  85897. else if (yaw < this._minYaw) {
  85898. localTarget.z = this._minYawCos * xzlen;
  85899. localTarget.x = this._minYawSin * xzlen;
  85900. newYaw = this._minYaw;
  85901. }
  85902. }
  85903. }
  85904. if (this._slerping && this._yawRange > Math.PI) {
  85905. //are we going to be crossing into the min/max region?
  85906. var boneFwd = BoneLookController._tmpVecs[8];
  85907. boneFwd.copyFrom(BABYLON.Axis.Z);
  85908. if (this._transformYawPitch) {
  85909. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  85910. }
  85911. var boneRotMat = BoneLookController._tmpMats[4];
  85912. this._boneQuat.toRotationMatrix(boneRotMat);
  85913. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  85914. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  85915. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  85916. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  85917. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  85918. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  85919. if (angBtwTar > angBtwMidYaw) {
  85920. if (xzlen == null) {
  85921. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85922. }
  85923. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  85924. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  85925. if (angBtwMin < angBtwMax) {
  85926. newYaw = boneYaw + Math.PI * .75;
  85927. localTarget.z = Math.cos(newYaw) * xzlen;
  85928. localTarget.x = Math.sin(newYaw) * xzlen;
  85929. }
  85930. else {
  85931. newYaw = boneYaw - Math.PI * .75;
  85932. localTarget.z = Math.cos(newYaw) * xzlen;
  85933. localTarget.x = Math.sin(newYaw) * xzlen;
  85934. }
  85935. }
  85936. }
  85937. if (yaw != newYaw) {
  85938. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85939. localTarget.addInPlace(bonePos);
  85940. target = localTarget;
  85941. }
  85942. }
  85943. }
  85944. var zaxis = BoneLookController._tmpVecs[5];
  85945. var xaxis = BoneLookController._tmpVecs[6];
  85946. var yaxis = BoneLookController._tmpVecs[7];
  85947. var _tmpQuat = BoneLookController._tmpQuat;
  85948. target.subtractToRef(bonePos, zaxis);
  85949. zaxis.normalize();
  85950. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  85951. xaxis.normalize();
  85952. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  85953. yaxis.normalize();
  85954. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  85955. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  85956. return;
  85957. }
  85958. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  85959. return;
  85960. }
  85961. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  85962. return;
  85963. }
  85964. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  85965. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  85966. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  85967. }
  85968. if (this.slerpAmount < 1) {
  85969. if (!this._slerping) {
  85970. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  85971. }
  85972. if (this._transformYawPitch) {
  85973. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85974. }
  85975. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  85976. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  85977. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  85978. this._slerping = true;
  85979. }
  85980. else {
  85981. if (this._transformYawPitch) {
  85982. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85983. }
  85984. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  85985. this._slerping = false;
  85986. }
  85987. };
  85988. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  85989. var angDiff = ang2 - ang1;
  85990. angDiff %= Math.PI * 2;
  85991. if (angDiff > Math.PI) {
  85992. angDiff -= Math.PI * 2;
  85993. }
  85994. else if (angDiff < -Math.PI) {
  85995. angDiff += Math.PI * 2;
  85996. }
  85997. return angDiff;
  85998. };
  85999. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  86000. ang1 %= (2 * Math.PI);
  86001. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  86002. ang2 %= (2 * Math.PI);
  86003. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  86004. var ab = 0;
  86005. if (ang1 < ang2) {
  86006. ab = ang2 - ang1;
  86007. }
  86008. else {
  86009. ab = ang1 - ang2;
  86010. }
  86011. if (ab > Math.PI) {
  86012. ab = Math.PI * 2 - ab;
  86013. }
  86014. return ab;
  86015. };
  86016. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  86017. ang %= (2 * Math.PI);
  86018. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  86019. ang1 %= (2 * Math.PI);
  86020. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  86021. ang2 %= (2 * Math.PI);
  86022. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  86023. if (ang1 < ang2) {
  86024. if (ang > ang1 && ang < ang2) {
  86025. return true;
  86026. }
  86027. }
  86028. else {
  86029. if (ang > ang2 && ang < ang1) {
  86030. return true;
  86031. }
  86032. }
  86033. return false;
  86034. };
  86035. 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()];
  86036. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  86037. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  86038. return BoneLookController;
  86039. }());
  86040. BABYLON.BoneLookController = BoneLookController;
  86041. })(BABYLON || (BABYLON = {}));
  86042. //# sourceMappingURL=babylon.boneLookController.js.map
  86043. var BABYLON;
  86044. (function (BABYLON) {
  86045. /**
  86046. * Class used to handle skinning animations
  86047. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86048. */
  86049. var Skeleton = /** @class */ (function () {
  86050. /**
  86051. * Creates a new skeleton
  86052. * @param name defines the skeleton name
  86053. * @param id defines the skeleton Id
  86054. * @param scene defines the hosting scene
  86055. */
  86056. function Skeleton(
  86057. /** defines the skeleton name */
  86058. name,
  86059. /** defines the skeleton Id */
  86060. id, scene) {
  86061. this.name = name;
  86062. this.id = id;
  86063. /**
  86064. * Gets the list of child bones
  86065. */
  86066. this.bones = new Array();
  86067. /**
  86068. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  86069. */
  86070. this.needInitialSkinMatrix = false;
  86071. this._isDirty = true;
  86072. this._meshesWithPoseMatrix = new Array();
  86073. this._identity = BABYLON.Matrix.Identity();
  86074. this._ranges = {};
  86075. this._lastAbsoluteTransformsUpdateId = -1;
  86076. /**
  86077. * Specifies if the skeleton should be serialized
  86078. */
  86079. this.doNotSerialize = false;
  86080. this._animationPropertiesOverride = null;
  86081. // Events
  86082. /**
  86083. * An observable triggered before computing the skeleton's matrices
  86084. */
  86085. this.onBeforeComputeObservable = new BABYLON.Observable();
  86086. this.bones = [];
  86087. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86088. scene.skeletons.push(this);
  86089. //make sure it will recalculate the matrix next time prepare is called.
  86090. this._isDirty = true;
  86091. }
  86092. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  86093. /**
  86094. * Gets or sets the animation properties override
  86095. */
  86096. get: function () {
  86097. if (!this._animationPropertiesOverride) {
  86098. return this._scene.animationPropertiesOverride;
  86099. }
  86100. return this._animationPropertiesOverride;
  86101. },
  86102. set: function (value) {
  86103. this._animationPropertiesOverride = value;
  86104. },
  86105. enumerable: true,
  86106. configurable: true
  86107. });
  86108. // Members
  86109. /**
  86110. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  86111. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  86112. * @returns a Float32Array containing matrices data
  86113. */
  86114. Skeleton.prototype.getTransformMatrices = function (mesh) {
  86115. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  86116. return mesh._bonesTransformMatrices;
  86117. }
  86118. if (!this._transformMatrices) {
  86119. this.prepare();
  86120. }
  86121. return this._transformMatrices;
  86122. };
  86123. /**
  86124. * Gets the current hosting scene
  86125. * @returns a scene object
  86126. */
  86127. Skeleton.prototype.getScene = function () {
  86128. return this._scene;
  86129. };
  86130. // Methods
  86131. /**
  86132. * Gets a string representing the current skeleton data
  86133. * @param fullDetails defines a boolean indicating if we want a verbose version
  86134. * @returns a string representing the current skeleton data
  86135. */
  86136. Skeleton.prototype.toString = function (fullDetails) {
  86137. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  86138. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  86139. if (fullDetails) {
  86140. ret += ", Ranges: {";
  86141. var first = true;
  86142. for (var name_1 in this._ranges) {
  86143. if (first) {
  86144. ret += ", ";
  86145. first = false;
  86146. }
  86147. ret += name_1;
  86148. }
  86149. ret += "}";
  86150. }
  86151. return ret;
  86152. };
  86153. /**
  86154. * Get bone's index searching by name
  86155. * @param name defines bone's name to search for
  86156. * @return the indice of the bone. Returns -1 if not found
  86157. */
  86158. Skeleton.prototype.getBoneIndexByName = function (name) {
  86159. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  86160. if (this.bones[boneIndex].name === name) {
  86161. return boneIndex;
  86162. }
  86163. }
  86164. return -1;
  86165. };
  86166. /**
  86167. * Creater a new animation range
  86168. * @param name defines the name of the range
  86169. * @param from defines the start key
  86170. * @param to defines the end key
  86171. */
  86172. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  86173. // check name not already in use
  86174. if (!this._ranges[name]) {
  86175. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  86176. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86177. if (this.bones[i].animations[0]) {
  86178. this.bones[i].animations[0].createRange(name, from, to);
  86179. }
  86180. }
  86181. }
  86182. };
  86183. /**
  86184. * Delete a specific animation range
  86185. * @param name defines the name of the range
  86186. * @param deleteFrames defines if frames must be removed as well
  86187. */
  86188. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  86189. if (deleteFrames === void 0) { deleteFrames = true; }
  86190. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86191. if (this.bones[i].animations[0]) {
  86192. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  86193. }
  86194. }
  86195. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  86196. };
  86197. /**
  86198. * Gets a specific animation range
  86199. * @param name defines the name of the range to look for
  86200. * @returns the requested animation range or null if not found
  86201. */
  86202. Skeleton.prototype.getAnimationRange = function (name) {
  86203. return this._ranges[name];
  86204. };
  86205. /**
  86206. * Gets the list of all animation ranges defined on this skeleton
  86207. * @returns an array
  86208. */
  86209. Skeleton.prototype.getAnimationRanges = function () {
  86210. var animationRanges = [];
  86211. var name;
  86212. var i = 0;
  86213. for (name in this._ranges) {
  86214. animationRanges[i] = this._ranges[name];
  86215. i++;
  86216. }
  86217. return animationRanges;
  86218. };
  86219. /**
  86220. * Copy animation range from a source skeleton.
  86221. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  86222. * @param source defines the source skeleton
  86223. * @param name defines the name of the range to copy
  86224. * @param rescaleAsRequired defines if rescaling must be applied if required
  86225. * @returns true if operation was successful
  86226. */
  86227. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  86228. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  86229. if (this._ranges[name] || !source.getAnimationRange(name)) {
  86230. return false;
  86231. }
  86232. var ret = true;
  86233. var frameOffset = this._getHighestAnimationFrame() + 1;
  86234. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  86235. var boneDict = {};
  86236. var sourceBones = source.bones;
  86237. var nBones;
  86238. var i;
  86239. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  86240. boneDict[sourceBones[i].name] = sourceBones[i];
  86241. }
  86242. if (this.bones.length !== sourceBones.length) {
  86243. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  86244. ret = false;
  86245. }
  86246. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  86247. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  86248. var boneName = this.bones[i].name;
  86249. var sourceBone = boneDict[boneName];
  86250. if (sourceBone) {
  86251. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  86252. }
  86253. else {
  86254. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  86255. ret = false;
  86256. }
  86257. }
  86258. // do not call createAnimationRange(), since it also is done to bones, which was already done
  86259. var range = source.getAnimationRange(name);
  86260. if (range) {
  86261. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  86262. }
  86263. return ret;
  86264. };
  86265. /**
  86266. * Forces the skeleton to go to rest pose
  86267. */
  86268. Skeleton.prototype.returnToRest = function () {
  86269. for (var index = 0; index < this.bones.length; index++) {
  86270. this.bones[index].returnToRest();
  86271. }
  86272. };
  86273. Skeleton.prototype._getHighestAnimationFrame = function () {
  86274. var ret = 0;
  86275. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86276. if (this.bones[i].animations[0]) {
  86277. var highest = this.bones[i].animations[0].getHighestFrame();
  86278. if (ret < highest) {
  86279. ret = highest;
  86280. }
  86281. }
  86282. }
  86283. return ret;
  86284. };
  86285. /**
  86286. * Begin a specific animation range
  86287. * @param name defines the name of the range to start
  86288. * @param loop defines if looping must be turned on (false by default)
  86289. * @param speedRatio defines the speed ratio to apply (1 by default)
  86290. * @param onAnimationEnd defines a callback which will be called when animation will end
  86291. * @returns a new animatable
  86292. */
  86293. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  86294. var range = this.getAnimationRange(name);
  86295. if (!range) {
  86296. return null;
  86297. }
  86298. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  86299. };
  86300. /** @hidden */
  86301. Skeleton.prototype._markAsDirty = function () {
  86302. this._isDirty = true;
  86303. };
  86304. /** @hidden */
  86305. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  86306. this._meshesWithPoseMatrix.push(mesh);
  86307. };
  86308. /** @hidden */
  86309. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  86310. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  86311. if (index > -1) {
  86312. this._meshesWithPoseMatrix.splice(index, 1);
  86313. }
  86314. };
  86315. /** @hidden */
  86316. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  86317. this.onBeforeComputeObservable.notifyObservers(this);
  86318. for (var index = 0; index < this.bones.length; index++) {
  86319. var bone = this.bones[index];
  86320. var parentBone = bone.getParent();
  86321. if (parentBone) {
  86322. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  86323. }
  86324. else {
  86325. if (initialSkinMatrix) {
  86326. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  86327. }
  86328. else {
  86329. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  86330. }
  86331. }
  86332. if (bone._index !== -1) {
  86333. var mappedIndex = bone._index === null ? index : bone._index;
  86334. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  86335. }
  86336. }
  86337. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  86338. };
  86339. /**
  86340. * Build all resources required to render a skeleton
  86341. */
  86342. Skeleton.prototype.prepare = function () {
  86343. if (!this._isDirty) {
  86344. return;
  86345. }
  86346. if (this.needInitialSkinMatrix) {
  86347. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  86348. var mesh = this._meshesWithPoseMatrix[index];
  86349. var poseMatrix = mesh.getPoseMatrix();
  86350. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  86351. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86352. }
  86353. if (this._synchronizedWithMesh !== mesh) {
  86354. this._synchronizedWithMesh = mesh;
  86355. // Prepare bones
  86356. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  86357. var bone = this.bones[boneIndex];
  86358. if (!bone.getParent()) {
  86359. var matrix = bone.getBaseMatrix();
  86360. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  86361. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  86362. }
  86363. }
  86364. }
  86365. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  86366. }
  86367. }
  86368. else {
  86369. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  86370. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86371. }
  86372. this._computeTransformMatrices(this._transformMatrices, null);
  86373. }
  86374. this._isDirty = false;
  86375. this._scene._activeBones.addCount(this.bones.length, false);
  86376. };
  86377. /**
  86378. * Gets the list of animatables currently running for this skeleton
  86379. * @returns an array of animatables
  86380. */
  86381. Skeleton.prototype.getAnimatables = function () {
  86382. if (!this._animatables || this._animatables.length !== this.bones.length) {
  86383. this._animatables = [];
  86384. for (var index = 0; index < this.bones.length; index++) {
  86385. this._animatables.push(this.bones[index]);
  86386. }
  86387. }
  86388. return this._animatables;
  86389. };
  86390. /**
  86391. * Clone the current skeleton
  86392. * @param name defines the name of the new skeleton
  86393. * @param id defines the id of the enw skeleton
  86394. * @returns the new skeleton
  86395. */
  86396. Skeleton.prototype.clone = function (name, id) {
  86397. var result = new Skeleton(name, id || name, this._scene);
  86398. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86399. for (var index = 0; index < this.bones.length; index++) {
  86400. var source = this.bones[index];
  86401. var parentBone = null;
  86402. var parent_1 = source.getParent();
  86403. if (parent_1) {
  86404. var parentIndex = this.bones.indexOf(parent_1);
  86405. parentBone = result.bones[parentIndex];
  86406. }
  86407. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  86408. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  86409. }
  86410. if (this._ranges) {
  86411. result._ranges = {};
  86412. for (var rangeName in this._ranges) {
  86413. var range = this._ranges[rangeName];
  86414. if (range) {
  86415. result._ranges[rangeName] = range.clone();
  86416. }
  86417. }
  86418. }
  86419. this._isDirty = true;
  86420. return result;
  86421. };
  86422. /**
  86423. * Enable animation blending for this skeleton
  86424. * @param blendingSpeed defines the blending speed to apply
  86425. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  86426. */
  86427. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  86428. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  86429. this.bones.forEach(function (bone) {
  86430. bone.animations.forEach(function (animation) {
  86431. animation.enableBlending = true;
  86432. animation.blendingSpeed = blendingSpeed;
  86433. });
  86434. });
  86435. };
  86436. /**
  86437. * Releases all resources associated with the current skeleton
  86438. */
  86439. Skeleton.prototype.dispose = function () {
  86440. this._meshesWithPoseMatrix = [];
  86441. // Animations
  86442. this.getScene().stopAnimation(this);
  86443. // Remove from scene
  86444. this.getScene().removeSkeleton(this);
  86445. };
  86446. /**
  86447. * Serialize the skeleton in a JSON object
  86448. * @returns a JSON object
  86449. */
  86450. Skeleton.prototype.serialize = function () {
  86451. var serializationObject = {};
  86452. serializationObject.name = this.name;
  86453. serializationObject.id = this.id;
  86454. if (this.dimensionsAtRest) {
  86455. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  86456. }
  86457. serializationObject.bones = [];
  86458. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86459. for (var index = 0; index < this.bones.length; index++) {
  86460. var bone = this.bones[index];
  86461. var parent_2 = bone.getParent();
  86462. var serializedBone = {
  86463. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  86464. name: bone.name,
  86465. matrix: bone.getBaseMatrix().toArray(),
  86466. rest: bone.getRestPose().toArray()
  86467. };
  86468. serializationObject.bones.push(serializedBone);
  86469. if (bone.length) {
  86470. serializedBone.length = bone.length;
  86471. }
  86472. if (bone.metadata) {
  86473. serializedBone.metadata = bone.metadata;
  86474. }
  86475. if (bone.animations && bone.animations.length > 0) {
  86476. serializedBone.animation = bone.animations[0].serialize();
  86477. }
  86478. serializationObject.ranges = [];
  86479. for (var name in this._ranges) {
  86480. var source = this._ranges[name];
  86481. if (!source) {
  86482. continue;
  86483. }
  86484. var range = {};
  86485. range.name = name;
  86486. range.from = source.from;
  86487. range.to = source.to;
  86488. serializationObject.ranges.push(range);
  86489. }
  86490. }
  86491. return serializationObject;
  86492. };
  86493. /**
  86494. * Creates a new skeleton from serialized data
  86495. * @param parsedSkeleton defines the serialized data
  86496. * @param scene defines the hosting scene
  86497. * @returns a new skeleton
  86498. */
  86499. Skeleton.Parse = function (parsedSkeleton, scene) {
  86500. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  86501. if (parsedSkeleton.dimensionsAtRest) {
  86502. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  86503. }
  86504. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  86505. var index;
  86506. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  86507. var parsedBone = parsedSkeleton.bones[index];
  86508. var parentBone = null;
  86509. if (parsedBone.parentBoneIndex > -1) {
  86510. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  86511. }
  86512. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  86513. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  86514. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  86515. bone.id = parsedBone.id;
  86516. }
  86517. if (parsedBone.length) {
  86518. bone.length = parsedBone.length;
  86519. }
  86520. if (parsedBone.metadata) {
  86521. bone.metadata = parsedBone.metadata;
  86522. }
  86523. if (parsedBone.animation) {
  86524. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  86525. }
  86526. }
  86527. // placed after bones, so createAnimationRange can cascade down
  86528. if (parsedSkeleton.ranges) {
  86529. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  86530. var data = parsedSkeleton.ranges[index];
  86531. skeleton.createAnimationRange(data.name, data.from, data.to);
  86532. }
  86533. }
  86534. return skeleton;
  86535. };
  86536. /**
  86537. * Compute all node absolute transforms
  86538. * @param forceUpdate defines if computation must be done even if cache is up to date
  86539. */
  86540. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  86541. if (forceUpdate === void 0) { forceUpdate = false; }
  86542. var renderId = this._scene.getRenderId();
  86543. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  86544. this.bones[0].computeAbsoluteTransforms();
  86545. this._lastAbsoluteTransformsUpdateId = renderId;
  86546. }
  86547. };
  86548. /**
  86549. * Gets the root pose matrix
  86550. * @returns a matrix
  86551. */
  86552. Skeleton.prototype.getPoseMatrix = function () {
  86553. var poseMatrix = null;
  86554. if (this._meshesWithPoseMatrix.length > 0) {
  86555. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  86556. }
  86557. return poseMatrix;
  86558. };
  86559. /**
  86560. * Sorts bones per internal index
  86561. */
  86562. Skeleton.prototype.sortBones = function () {
  86563. var bones = new Array();
  86564. var visited = new Array(this.bones.length);
  86565. for (var index = 0; index < this.bones.length; index++) {
  86566. this._sortBones(index, bones, visited);
  86567. }
  86568. this.bones = bones;
  86569. };
  86570. Skeleton.prototype._sortBones = function (index, bones, visited) {
  86571. if (visited[index]) {
  86572. return;
  86573. }
  86574. visited[index] = true;
  86575. var bone = this.bones[index];
  86576. if (bone._index === undefined) {
  86577. bone._index = index;
  86578. }
  86579. var parentBone = bone.getParent();
  86580. if (parentBone) {
  86581. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  86582. }
  86583. bones.push(bone);
  86584. };
  86585. return Skeleton;
  86586. }());
  86587. BABYLON.Skeleton = Skeleton;
  86588. })(BABYLON || (BABYLON = {}));
  86589. //# sourceMappingURL=babylon.skeleton.js.map
  86590. var BABYLON;
  86591. (function (BABYLON) {
  86592. ;
  86593. /**
  86594. * This groups tools to convert HDR texture to native colors array.
  86595. */
  86596. var HDRTools = /** @class */ (function () {
  86597. function HDRTools() {
  86598. }
  86599. HDRTools.Ldexp = function (mantissa, exponent) {
  86600. if (exponent > 1023) {
  86601. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  86602. }
  86603. if (exponent < -1074) {
  86604. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  86605. }
  86606. return mantissa * Math.pow(2, exponent);
  86607. };
  86608. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  86609. if (exponent > 0) { /*nonzero pixel*/
  86610. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  86611. float32array[index + 0] = red * exponent;
  86612. float32array[index + 1] = green * exponent;
  86613. float32array[index + 2] = blue * exponent;
  86614. }
  86615. else {
  86616. float32array[index + 0] = 0;
  86617. float32array[index + 1] = 0;
  86618. float32array[index + 2] = 0;
  86619. }
  86620. };
  86621. HDRTools.readStringLine = function (uint8array, startIndex) {
  86622. var line = "";
  86623. var character = "";
  86624. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  86625. character = String.fromCharCode(uint8array[i]);
  86626. if (character == "\n") {
  86627. break;
  86628. }
  86629. line += character;
  86630. }
  86631. return line;
  86632. };
  86633. /**
  86634. * Reads header information from an RGBE texture stored in a native array.
  86635. * More information on this format are available here:
  86636. * https://en.wikipedia.org/wiki/RGBE_image_format
  86637. *
  86638. * @param uint8array The binary file stored in native array.
  86639. * @return The header information.
  86640. */
  86641. HDRTools.RGBE_ReadHeader = function (uint8array) {
  86642. var height = 0;
  86643. var width = 0;
  86644. var line = this.readStringLine(uint8array, 0);
  86645. if (line[0] != '#' || line[1] != '?') {
  86646. throw "Bad HDR Format.";
  86647. }
  86648. var endOfHeader = false;
  86649. var findFormat = false;
  86650. var lineIndex = 0;
  86651. do {
  86652. lineIndex += (line.length + 1);
  86653. line = this.readStringLine(uint8array, lineIndex);
  86654. if (line == "FORMAT=32-bit_rle_rgbe") {
  86655. findFormat = true;
  86656. }
  86657. else if (line.length == 0) {
  86658. endOfHeader = true;
  86659. }
  86660. } while (!endOfHeader);
  86661. if (!findFormat) {
  86662. throw "HDR Bad header format, unsupported FORMAT";
  86663. }
  86664. lineIndex += (line.length + 1);
  86665. line = this.readStringLine(uint8array, lineIndex);
  86666. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  86667. var match = sizeRegexp.exec(line);
  86668. // TODO. Support +Y and -X if needed.
  86669. if (!match || match.length < 3) {
  86670. throw "HDR Bad header format, no size";
  86671. }
  86672. width = parseInt(match[2]);
  86673. height = parseInt(match[1]);
  86674. if (width < 8 || width > 0x7fff) {
  86675. throw "HDR Bad header format, unsupported size";
  86676. }
  86677. lineIndex += (line.length + 1);
  86678. return {
  86679. height: height,
  86680. width: width,
  86681. dataPosition: lineIndex
  86682. };
  86683. };
  86684. /**
  86685. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  86686. * This RGBE texture needs to store the information as a panorama.
  86687. *
  86688. * More information on this format are available here:
  86689. * https://en.wikipedia.org/wiki/RGBE_image_format
  86690. *
  86691. * @param buffer The binary file stored in an array buffer.
  86692. * @param size The expected size of the extracted cubemap.
  86693. * @return The Cube Map information.
  86694. */
  86695. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  86696. var uint8array = new Uint8Array(buffer);
  86697. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  86698. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86699. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  86700. return cubeMapData;
  86701. };
  86702. /**
  86703. * Returns the pixels data extracted from an RGBE texture.
  86704. * This pixels will be stored left to right up to down in the R G B order in one array.
  86705. *
  86706. * More information on this format are available here:
  86707. * https://en.wikipedia.org/wiki/RGBE_image_format
  86708. *
  86709. * @param uint8array The binary file stored in an array buffer.
  86710. * @param hdrInfo The header information of the file.
  86711. * @return The pixels data in RGB right to left up to down order.
  86712. */
  86713. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  86714. // Keep for multi format supports.
  86715. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86716. };
  86717. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  86718. var num_scanlines = hdrInfo.height;
  86719. var scanline_width = hdrInfo.width;
  86720. var a, b, c, d, count;
  86721. var dataIndex = hdrInfo.dataPosition;
  86722. var index = 0, endIndex = 0, i = 0;
  86723. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  86724. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  86725. // 3 channels of 4 bytes per pixel in float.
  86726. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  86727. var resultArray = new Float32Array(resultBuffer);
  86728. // read in each successive scanline
  86729. while (num_scanlines > 0) {
  86730. a = uint8array[dataIndex++];
  86731. b = uint8array[dataIndex++];
  86732. c = uint8array[dataIndex++];
  86733. d = uint8array[dataIndex++];
  86734. if (a != 2 || b != 2 || (c & 0x80)) {
  86735. // this file is not run length encoded
  86736. throw "HDR Bad header format, not RLE";
  86737. }
  86738. if (((c << 8) | d) != scanline_width) {
  86739. throw "HDR Bad header format, wrong scan line width";
  86740. }
  86741. index = 0;
  86742. // read each of the four channels for the scanline into the buffer
  86743. for (i = 0; i < 4; i++) {
  86744. endIndex = (i + 1) * scanline_width;
  86745. while (index < endIndex) {
  86746. a = uint8array[dataIndex++];
  86747. b = uint8array[dataIndex++];
  86748. if (a > 128) {
  86749. // a run of the same value
  86750. count = a - 128;
  86751. if ((count == 0) || (count > endIndex - index)) {
  86752. throw "HDR Bad Format, bad scanline data (run)";
  86753. }
  86754. while (count-- > 0) {
  86755. scanLineArray[index++] = b;
  86756. }
  86757. }
  86758. else {
  86759. // a non-run
  86760. count = a;
  86761. if ((count == 0) || (count > endIndex - index)) {
  86762. throw "HDR Bad Format, bad scanline data (non-run)";
  86763. }
  86764. scanLineArray[index++] = b;
  86765. if (--count > 0) {
  86766. for (var j = 0; j < count; j++) {
  86767. scanLineArray[index++] = uint8array[dataIndex++];
  86768. }
  86769. }
  86770. }
  86771. }
  86772. }
  86773. // now convert data from buffer into floats
  86774. for (i = 0; i < scanline_width; i++) {
  86775. a = scanLineArray[i];
  86776. b = scanLineArray[i + scanline_width];
  86777. c = scanLineArray[i + 2 * scanline_width];
  86778. d = scanLineArray[i + 3 * scanline_width];
  86779. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  86780. }
  86781. num_scanlines--;
  86782. }
  86783. return resultArray;
  86784. };
  86785. return HDRTools;
  86786. }());
  86787. BABYLON.HDRTools = HDRTools;
  86788. })(BABYLON || (BABYLON = {}));
  86789. //# sourceMappingURL=babylon.hdr.js.map
  86790. var BABYLON;
  86791. (function (BABYLON) {
  86792. /**
  86793. * This represents a texture coming from an HDR input.
  86794. *
  86795. * The only supported format is currently panorama picture stored in RGBE format.
  86796. * Example of such files can be found on HDRLib: http://hdrlib.com/
  86797. */
  86798. var HDRCubeTexture = /** @class */ (function (_super) {
  86799. __extends(HDRCubeTexture, _super);
  86800. /**
  86801. * Instantiates an HDRTexture from the following parameters.
  86802. *
  86803. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  86804. * @param scene The scene the texture will be used in
  86805. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  86806. * @param noMipmap Forces to not generate the mipmap if true
  86807. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  86808. * @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)
  86809. * @param reserved Reserved flag for internal use.
  86810. */
  86811. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  86812. if (noMipmap === void 0) { noMipmap = false; }
  86813. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86814. if (gammaSpace === void 0) { gammaSpace = false; }
  86815. if (reserved === void 0) { reserved = false; }
  86816. if (onLoad === void 0) { onLoad = null; }
  86817. if (onError === void 0) { onError = null; }
  86818. var _this = _super.call(this, scene) || this;
  86819. _this._generateHarmonics = true;
  86820. _this._onLoad = null;
  86821. _this._onError = null;
  86822. /**
  86823. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  86824. */
  86825. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  86826. _this._isBlocking = true;
  86827. _this._rotationY = 0;
  86828. /**
  86829. * Gets or sets the center of the bounding box associated with the cube texture
  86830. * It must define where the camera used to render the texture was set
  86831. */
  86832. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  86833. if (!url) {
  86834. return _this;
  86835. }
  86836. _this.name = url;
  86837. _this.url = url;
  86838. _this.hasAlpha = false;
  86839. _this.isCube = true;
  86840. _this._textureMatrix = BABYLON.Matrix.Identity();
  86841. _this._onLoad = onLoad;
  86842. _this._onError = onError;
  86843. _this.gammaSpace = gammaSpace;
  86844. _this._noMipmap = noMipmap;
  86845. _this._size = size;
  86846. _this._texture = _this._getFromCache(url, _this._noMipmap);
  86847. if (!_this._texture) {
  86848. if (!scene.useDelayedTextureLoading) {
  86849. _this.loadTexture();
  86850. }
  86851. else {
  86852. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86853. }
  86854. }
  86855. return _this;
  86856. }
  86857. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  86858. /**
  86859. * Gets wether or not the texture is blocking during loading.
  86860. */
  86861. get: function () {
  86862. return this._isBlocking;
  86863. },
  86864. /**
  86865. * Sets wether or not the texture is blocking during loading.
  86866. */
  86867. set: function (value) {
  86868. this._isBlocking = value;
  86869. },
  86870. enumerable: true,
  86871. configurable: true
  86872. });
  86873. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  86874. /**
  86875. * Gets texture matrix rotation angle around Y axis radians.
  86876. */
  86877. get: function () {
  86878. return this._rotationY;
  86879. },
  86880. /**
  86881. * Sets texture matrix rotation angle around Y axis in radians.
  86882. */
  86883. set: function (value) {
  86884. this._rotationY = value;
  86885. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  86886. },
  86887. enumerable: true,
  86888. configurable: true
  86889. });
  86890. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  86891. get: function () {
  86892. return this._boundingBoxSize;
  86893. },
  86894. /**
  86895. * Gets or sets the size of the bounding box associated with the cube texture
  86896. * When defined, the cubemap will switch to local mode
  86897. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  86898. * @example https://www.babylonjs-playground.com/#RNASML
  86899. */
  86900. set: function (value) {
  86901. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  86902. return;
  86903. }
  86904. this._boundingBoxSize = value;
  86905. var scene = this.getScene();
  86906. if (scene) {
  86907. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  86908. }
  86909. },
  86910. enumerable: true,
  86911. configurable: true
  86912. });
  86913. /**
  86914. * Occurs when the file is raw .hdr file.
  86915. */
  86916. HDRCubeTexture.prototype.loadTexture = function () {
  86917. var _this = this;
  86918. var callback = function (buffer) {
  86919. _this.lodGenerationOffset = 0.0;
  86920. _this.lodGenerationScale = 0.8;
  86921. var scene = _this.getScene();
  86922. if (!scene) {
  86923. return null;
  86924. }
  86925. // Extract the raw linear data.
  86926. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  86927. // Generate harmonics if needed.
  86928. if (_this._generateHarmonics) {
  86929. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  86930. _this.sphericalPolynomial = sphericalPolynomial;
  86931. }
  86932. var results = [];
  86933. var byteArray = null;
  86934. // Push each faces.
  86935. for (var j = 0; j < 6; j++) {
  86936. // Create uintarray fallback.
  86937. if (!scene.getEngine().getCaps().textureFloat) {
  86938. // 3 channels of 1 bytes per pixel in bytes.
  86939. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  86940. byteArray = new Uint8Array(byteBuffer);
  86941. }
  86942. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  86943. // If special cases.
  86944. if (_this.gammaSpace || byteArray) {
  86945. for (var i = 0; i < _this._size * _this._size; i++) {
  86946. // Put in gamma space if requested.
  86947. if (_this.gammaSpace) {
  86948. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  86949. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  86950. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  86951. }
  86952. // Convert to int texture for fallback.
  86953. if (byteArray) {
  86954. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  86955. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  86956. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  86957. // May use luminance instead if the result is not accurate.
  86958. var max = Math.max(Math.max(r, g), b);
  86959. if (max > 255) {
  86960. var scale = 255 / max;
  86961. r *= scale;
  86962. g *= scale;
  86963. b *= scale;
  86964. }
  86965. byteArray[(i * 3) + 0] = r;
  86966. byteArray[(i * 3) + 1] = g;
  86967. byteArray[(i * 3) + 2] = b;
  86968. }
  86969. }
  86970. }
  86971. if (byteArray) {
  86972. results.push(byteArray);
  86973. }
  86974. else {
  86975. results.push(dataFace);
  86976. }
  86977. }
  86978. return results;
  86979. };
  86980. var scene = this.getScene();
  86981. if (scene) {
  86982. 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);
  86983. }
  86984. };
  86985. HDRCubeTexture.prototype.clone = function () {
  86986. var scene = this.getScene();
  86987. if (!scene) {
  86988. return this;
  86989. }
  86990. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  86991. // Base texture
  86992. newTexture.level = this.level;
  86993. newTexture.wrapU = this.wrapU;
  86994. newTexture.wrapV = this.wrapV;
  86995. newTexture.coordinatesIndex = this.coordinatesIndex;
  86996. newTexture.coordinatesMode = this.coordinatesMode;
  86997. return newTexture;
  86998. };
  86999. // Methods
  87000. HDRCubeTexture.prototype.delayLoad = function () {
  87001. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  87002. return;
  87003. }
  87004. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  87005. this._texture = this._getFromCache(this.url, this._noMipmap);
  87006. if (!this._texture) {
  87007. this.loadTexture();
  87008. }
  87009. };
  87010. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  87011. return this._textureMatrix;
  87012. };
  87013. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  87014. this._textureMatrix = value;
  87015. };
  87016. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  87017. var texture = null;
  87018. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  87019. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  87020. texture.name = parsedTexture.name;
  87021. texture.hasAlpha = parsedTexture.hasAlpha;
  87022. texture.level = parsedTexture.level;
  87023. texture.coordinatesMode = parsedTexture.coordinatesMode;
  87024. texture.isBlocking = parsedTexture.isBlocking;
  87025. }
  87026. if (texture) {
  87027. if (parsedTexture.boundingBoxPosition) {
  87028. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  87029. }
  87030. if (parsedTexture.boundingBoxSize) {
  87031. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  87032. }
  87033. if (parsedTexture.rotationY) {
  87034. texture.rotationY = parsedTexture.rotationY;
  87035. }
  87036. }
  87037. return texture;
  87038. };
  87039. HDRCubeTexture.prototype.serialize = function () {
  87040. if (!this.name) {
  87041. return null;
  87042. }
  87043. var serializationObject = {};
  87044. serializationObject.name = this.name;
  87045. serializationObject.hasAlpha = this.hasAlpha;
  87046. serializationObject.isCube = true;
  87047. serializationObject.level = this.level;
  87048. serializationObject.size = this._size;
  87049. serializationObject.coordinatesMode = this.coordinatesMode;
  87050. serializationObject.useInGammaSpace = this.gammaSpace;
  87051. serializationObject.generateHarmonics = this._generateHarmonics;
  87052. serializationObject.customType = "BABYLON.HDRCubeTexture";
  87053. serializationObject.noMipmap = this._noMipmap;
  87054. serializationObject.isBlocking = this._isBlocking;
  87055. serializationObject.rotationY = this._rotationY;
  87056. return serializationObject;
  87057. };
  87058. HDRCubeTexture._facesMapping = [
  87059. "right",
  87060. "left",
  87061. "up",
  87062. "down",
  87063. "front",
  87064. "back"
  87065. ];
  87066. return HDRCubeTexture;
  87067. }(BABYLON.BaseTexture));
  87068. BABYLON.HDRCubeTexture = HDRCubeTexture;
  87069. })(BABYLON || (BABYLON = {}));
  87070. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  87071. var BABYLON;
  87072. (function (BABYLON) {
  87073. /**
  87074. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  87075. */
  87076. var PanoramaToCubeMapTools = /** @class */ (function () {
  87077. function PanoramaToCubeMapTools() {
  87078. }
  87079. /**
  87080. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  87081. *
  87082. * @param float32Array The source data.
  87083. * @param inputWidth The width of the input panorama.
  87084. * @param inputhHeight The height of the input panorama.
  87085. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  87086. * @return The cubemap data
  87087. */
  87088. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  87089. if (!float32Array) {
  87090. throw "ConvertPanoramaToCubemap: input cannot be null";
  87091. }
  87092. if (float32Array.length != inputWidth * inputHeight * 3) {
  87093. throw "ConvertPanoramaToCubemap: input size is wrong";
  87094. }
  87095. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  87096. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  87097. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  87098. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  87099. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  87100. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  87101. return {
  87102. front: textureFront,
  87103. back: textureBack,
  87104. left: textureLeft,
  87105. right: textureRight,
  87106. up: textureUp,
  87107. down: textureDown,
  87108. size: size,
  87109. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87110. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  87111. gammaSpace: false,
  87112. };
  87113. };
  87114. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  87115. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  87116. var textureArray = new Float32Array(buffer);
  87117. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  87118. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  87119. var dy = 1 / texSize;
  87120. var fy = 0;
  87121. for (var y = 0; y < texSize; y++) {
  87122. var xv1 = faceData[0];
  87123. var xv2 = faceData[2];
  87124. for (var x = 0; x < texSize; x++) {
  87125. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  87126. v.normalize();
  87127. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  87128. // 3 channels per pixels
  87129. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  87130. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  87131. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  87132. xv1 = xv1.add(rotDX1);
  87133. xv2 = xv2.add(rotDX2);
  87134. }
  87135. fy += dy;
  87136. }
  87137. return textureArray;
  87138. };
  87139. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  87140. var theta = Math.atan2(vDir.z, vDir.x);
  87141. var phi = Math.acos(vDir.y);
  87142. while (theta < -Math.PI)
  87143. theta += 2 * Math.PI;
  87144. while (theta > Math.PI)
  87145. theta -= 2 * Math.PI;
  87146. var dx = theta / Math.PI;
  87147. var dy = phi / Math.PI;
  87148. // recenter.
  87149. dx = dx * 0.5 + 0.5;
  87150. var px = Math.round(dx * inputWidth);
  87151. if (px < 0)
  87152. px = 0;
  87153. else if (px >= inputWidth)
  87154. px = inputWidth - 1;
  87155. var py = Math.round(dy * inputHeight);
  87156. if (py < 0)
  87157. py = 0;
  87158. else if (py >= inputHeight)
  87159. py = inputHeight - 1;
  87160. var inputY = (inputHeight - py - 1);
  87161. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  87162. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  87163. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  87164. return {
  87165. r: r,
  87166. g: g,
  87167. b: b
  87168. };
  87169. };
  87170. PanoramaToCubeMapTools.FACE_FRONT = [
  87171. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87172. new BABYLON.Vector3(1.0, -1.0, -1.0),
  87173. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  87174. new BABYLON.Vector3(1.0, 1.0, -1.0)
  87175. ];
  87176. PanoramaToCubeMapTools.FACE_BACK = [
  87177. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87178. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87179. new BABYLON.Vector3(1.0, 1.0, 1.0),
  87180. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  87181. ];
  87182. PanoramaToCubeMapTools.FACE_RIGHT = [
  87183. new BABYLON.Vector3(1.0, -1.0, -1.0),
  87184. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87185. new BABYLON.Vector3(1.0, 1.0, -1.0),
  87186. new BABYLON.Vector3(1.0, 1.0, 1.0)
  87187. ];
  87188. PanoramaToCubeMapTools.FACE_LEFT = [
  87189. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87190. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87191. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  87192. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  87193. ];
  87194. PanoramaToCubeMapTools.FACE_DOWN = [
  87195. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  87196. new BABYLON.Vector3(1.0, 1.0, -1.0),
  87197. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  87198. new BABYLON.Vector3(1.0, 1.0, 1.0)
  87199. ];
  87200. PanoramaToCubeMapTools.FACE_UP = [
  87201. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87202. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87203. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87204. new BABYLON.Vector3(1.0, -1.0, -1.0)
  87205. ];
  87206. return PanoramaToCubeMapTools;
  87207. }());
  87208. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  87209. })(BABYLON || (BABYLON = {}));
  87210. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  87211. var BABYLON;
  87212. (function (BABYLON) {
  87213. var IndexedVector2 = /** @class */ (function (_super) {
  87214. __extends(IndexedVector2, _super);
  87215. function IndexedVector2(original, index) {
  87216. var _this = _super.call(this, original.x, original.y) || this;
  87217. _this.index = index;
  87218. return _this;
  87219. }
  87220. return IndexedVector2;
  87221. }(BABYLON.Vector2));
  87222. var PolygonPoints = /** @class */ (function () {
  87223. function PolygonPoints() {
  87224. this.elements = new Array();
  87225. }
  87226. PolygonPoints.prototype.add = function (originalPoints) {
  87227. var _this = this;
  87228. var result = new Array();
  87229. originalPoints.forEach(function (point) {
  87230. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  87231. var newPoint = new IndexedVector2(point, _this.elements.length);
  87232. result.push(newPoint);
  87233. _this.elements.push(newPoint);
  87234. }
  87235. });
  87236. return result;
  87237. };
  87238. PolygonPoints.prototype.computeBounds = function () {
  87239. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  87240. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  87241. this.elements.forEach(function (point) {
  87242. // x
  87243. if (point.x < lmin.x) {
  87244. lmin.x = point.x;
  87245. }
  87246. else if (point.x > lmax.x) {
  87247. lmax.x = point.x;
  87248. }
  87249. // y
  87250. if (point.y < lmin.y) {
  87251. lmin.y = point.y;
  87252. }
  87253. else if (point.y > lmax.y) {
  87254. lmax.y = point.y;
  87255. }
  87256. });
  87257. return {
  87258. min: lmin,
  87259. max: lmax,
  87260. width: lmax.x - lmin.x,
  87261. height: lmax.y - lmin.y
  87262. };
  87263. };
  87264. return PolygonPoints;
  87265. }());
  87266. var Polygon = /** @class */ (function () {
  87267. function Polygon() {
  87268. }
  87269. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  87270. return [
  87271. new BABYLON.Vector2(xmin, ymin),
  87272. new BABYLON.Vector2(xmax, ymin),
  87273. new BABYLON.Vector2(xmax, ymax),
  87274. new BABYLON.Vector2(xmin, ymax)
  87275. ];
  87276. };
  87277. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  87278. if (cx === void 0) { cx = 0; }
  87279. if (cy === void 0) { cy = 0; }
  87280. if (numberOfSides === void 0) { numberOfSides = 32; }
  87281. var result = new Array();
  87282. var angle = 0;
  87283. var increment = (Math.PI * 2) / numberOfSides;
  87284. for (var i = 0; i < numberOfSides; i++) {
  87285. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  87286. angle -= increment;
  87287. }
  87288. return result;
  87289. };
  87290. Polygon.Parse = function (input) {
  87291. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  87292. var i, result = [];
  87293. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  87294. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  87295. }
  87296. return result;
  87297. };
  87298. Polygon.StartingAt = function (x, y) {
  87299. return BABYLON.Path2.StartingAt(x, y);
  87300. };
  87301. return Polygon;
  87302. }());
  87303. BABYLON.Polygon = Polygon;
  87304. var PolygonMeshBuilder = /** @class */ (function () {
  87305. function PolygonMeshBuilder(name, contours, scene) {
  87306. this._points = new PolygonPoints();
  87307. this._outlinepoints = new PolygonPoints();
  87308. this._holes = new Array();
  87309. this._epoints = new Array();
  87310. this._eholes = new Array();
  87311. this._name = name;
  87312. this._scene = scene;
  87313. var points;
  87314. if (contours instanceof BABYLON.Path2) {
  87315. points = contours.getPoints();
  87316. }
  87317. else {
  87318. points = contours;
  87319. }
  87320. this._addToepoint(points);
  87321. this._points.add(points);
  87322. this._outlinepoints.add(points);
  87323. if (typeof earcut === 'undefined') {
  87324. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  87325. }
  87326. }
  87327. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  87328. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  87329. var p = points_1[_i];
  87330. this._epoints.push(p.x, p.y);
  87331. }
  87332. };
  87333. PolygonMeshBuilder.prototype.addHole = function (hole) {
  87334. this._points.add(hole);
  87335. var holepoints = new PolygonPoints();
  87336. holepoints.add(hole);
  87337. this._holes.push(holepoints);
  87338. this._eholes.push(this._epoints.length / 2);
  87339. this._addToepoint(hole);
  87340. return this;
  87341. };
  87342. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  87343. var _this = this;
  87344. if (updatable === void 0) { updatable = false; }
  87345. if (depth === void 0) { depth = 0; }
  87346. var result = new BABYLON.Mesh(this._name, this._scene);
  87347. var normals = new Array();
  87348. var positions = new Array();
  87349. var uvs = new Array();
  87350. var bounds = this._points.computeBounds();
  87351. this._points.elements.forEach(function (p) {
  87352. normals.push(0, 1.0, 0);
  87353. positions.push(p.x, 0, p.y);
  87354. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  87355. });
  87356. var indices = new Array();
  87357. var res = earcut(this._epoints, this._eholes, 2);
  87358. for (var i = 0; i < res.length; i++) {
  87359. indices.push(res[i]);
  87360. }
  87361. if (depth > 0) {
  87362. var positionscount = (positions.length / 3); //get the current pointcount
  87363. this._points.elements.forEach(function (p) {
  87364. normals.push(0, -1.0, 0);
  87365. positions.push(p.x, -depth, p.y);
  87366. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  87367. });
  87368. var totalCount = indices.length;
  87369. for (var i = 0; i < totalCount; i += 3) {
  87370. var i0 = indices[i + 0];
  87371. var i1 = indices[i + 1];
  87372. var i2 = indices[i + 2];
  87373. indices.push(i2 + positionscount);
  87374. indices.push(i1 + positionscount);
  87375. indices.push(i0 + positionscount);
  87376. }
  87377. //Add the sides
  87378. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  87379. this._holes.forEach(function (hole) {
  87380. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  87381. });
  87382. }
  87383. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  87384. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  87385. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  87386. result.setIndices(indices);
  87387. return result;
  87388. };
  87389. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  87390. var StartIndex = positions.length / 3;
  87391. var ulength = 0;
  87392. for (var i = 0; i < points.elements.length; i++) {
  87393. var p = points.elements[i];
  87394. var p1;
  87395. if ((i + 1) > points.elements.length - 1) {
  87396. p1 = points.elements[0];
  87397. }
  87398. else {
  87399. p1 = points.elements[i + 1];
  87400. }
  87401. positions.push(p.x, 0, p.y);
  87402. positions.push(p.x, -depth, p.y);
  87403. positions.push(p1.x, 0, p1.y);
  87404. positions.push(p1.x, -depth, p1.y);
  87405. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  87406. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  87407. var v3 = v2.subtract(v1);
  87408. var v4 = new BABYLON.Vector3(0, 1, 0);
  87409. var vn = BABYLON.Vector3.Cross(v3, v4);
  87410. vn = vn.normalize();
  87411. uvs.push(ulength / bounds.width, 0);
  87412. uvs.push(ulength / bounds.width, 1);
  87413. ulength += v3.length();
  87414. uvs.push((ulength / bounds.width), 0);
  87415. uvs.push((ulength / bounds.width), 1);
  87416. if (!flip) {
  87417. normals.push(-vn.x, -vn.y, -vn.z);
  87418. normals.push(-vn.x, -vn.y, -vn.z);
  87419. normals.push(-vn.x, -vn.y, -vn.z);
  87420. normals.push(-vn.x, -vn.y, -vn.z);
  87421. indices.push(StartIndex);
  87422. indices.push(StartIndex + 1);
  87423. indices.push(StartIndex + 2);
  87424. indices.push(StartIndex + 1);
  87425. indices.push(StartIndex + 3);
  87426. indices.push(StartIndex + 2);
  87427. }
  87428. else {
  87429. normals.push(vn.x, vn.y, vn.z);
  87430. normals.push(vn.x, vn.y, vn.z);
  87431. normals.push(vn.x, vn.y, vn.z);
  87432. normals.push(vn.x, vn.y, vn.z);
  87433. indices.push(StartIndex);
  87434. indices.push(StartIndex + 2);
  87435. indices.push(StartIndex + 1);
  87436. indices.push(StartIndex + 1);
  87437. indices.push(StartIndex + 2);
  87438. indices.push(StartIndex + 3);
  87439. }
  87440. StartIndex += 4;
  87441. }
  87442. ;
  87443. };
  87444. return PolygonMeshBuilder;
  87445. }());
  87446. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  87447. })(BABYLON || (BABYLON = {}));
  87448. //# sourceMappingURL=babylon.polygonMesh.js.map
  87449. var BABYLON;
  87450. (function (BABYLON) {
  87451. // Unique ID when we import meshes from Babylon to CSG
  87452. var currentCSGMeshId = 0;
  87453. // # class Vertex
  87454. // Represents a vertex of a polygon. Use your own vertex class instead of this
  87455. // one to provide additional features like texture coordinates and vertex
  87456. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  87457. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  87458. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  87459. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  87460. // is not used anywhere else.
  87461. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  87462. var Vertex = /** @class */ (function () {
  87463. function Vertex(pos, normal, uv) {
  87464. this.pos = pos;
  87465. this.normal = normal;
  87466. this.uv = uv;
  87467. }
  87468. Vertex.prototype.clone = function () {
  87469. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  87470. };
  87471. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  87472. // orientation of a polygon is flipped.
  87473. Vertex.prototype.flip = function () {
  87474. this.normal = this.normal.scale(-1);
  87475. };
  87476. // Create a new vertex between this vertex and `other` by linearly
  87477. // interpolating all properties using a parameter of `t`. Subclasses should
  87478. // override this to interpolate additional properties.
  87479. Vertex.prototype.interpolate = function (other, t) {
  87480. 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));
  87481. };
  87482. return Vertex;
  87483. }());
  87484. // # class Plane
  87485. // Represents a plane in 3D space.
  87486. var Plane = /** @class */ (function () {
  87487. function Plane(normal, w) {
  87488. this.normal = normal;
  87489. this.w = w;
  87490. }
  87491. Plane.FromPoints = function (a, b, c) {
  87492. var v0 = c.subtract(a);
  87493. var v1 = b.subtract(a);
  87494. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  87495. return null;
  87496. }
  87497. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  87498. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  87499. };
  87500. Plane.prototype.clone = function () {
  87501. return new Plane(this.normal.clone(), this.w);
  87502. };
  87503. Plane.prototype.flip = function () {
  87504. this.normal.scaleInPlace(-1);
  87505. this.w = -this.w;
  87506. };
  87507. // Split `polygon` by this plane if needed, then put the polygon or polygon
  87508. // fragments in the appropriate lists. Coplanar polygons go into either
  87509. // `coplanarFront` or `coplanarBack` depending on their orientation with
  87510. // respect to this plane. Polygons in front or in back of this plane go into
  87511. // either `front` or `back`.
  87512. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  87513. var COPLANAR = 0;
  87514. var FRONT = 1;
  87515. var BACK = 2;
  87516. var SPANNING = 3;
  87517. // Classify each point as well as the entire polygon into one of the above
  87518. // four classes.
  87519. var polygonType = 0;
  87520. var types = [];
  87521. var i;
  87522. var t;
  87523. for (i = 0; i < polygon.vertices.length; i++) {
  87524. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  87525. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  87526. polygonType |= type;
  87527. types.push(type);
  87528. }
  87529. // Put the polygon in the correct list, splitting it when necessary.
  87530. switch (polygonType) {
  87531. case COPLANAR:
  87532. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  87533. break;
  87534. case FRONT:
  87535. front.push(polygon);
  87536. break;
  87537. case BACK:
  87538. back.push(polygon);
  87539. break;
  87540. case SPANNING:
  87541. var f = [], b = [];
  87542. for (i = 0; i < polygon.vertices.length; i++) {
  87543. var j = (i + 1) % polygon.vertices.length;
  87544. var ti = types[i], tj = types[j];
  87545. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  87546. if (ti !== BACK)
  87547. f.push(vi);
  87548. if (ti !== FRONT)
  87549. b.push(ti !== BACK ? vi.clone() : vi);
  87550. if ((ti | tj) === SPANNING) {
  87551. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  87552. var v = vi.interpolate(vj, t);
  87553. f.push(v);
  87554. b.push(v.clone());
  87555. }
  87556. }
  87557. var poly;
  87558. if (f.length >= 3) {
  87559. poly = new Polygon(f, polygon.shared);
  87560. if (poly.plane)
  87561. front.push(poly);
  87562. }
  87563. if (b.length >= 3) {
  87564. poly = new Polygon(b, polygon.shared);
  87565. if (poly.plane)
  87566. back.push(poly);
  87567. }
  87568. break;
  87569. }
  87570. };
  87571. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  87572. // point is on the plane.
  87573. Plane.EPSILON = 1e-5;
  87574. return Plane;
  87575. }());
  87576. // # class Polygon
  87577. // Represents a convex polygon. The vertices used to initialize a polygon must
  87578. // be coplanar and form a convex loop.
  87579. //
  87580. // Each convex polygon has a `shared` property, which is shared between all
  87581. // polygons that are clones of each other or were split from the same polygon.
  87582. // This can be used to define per-polygon properties (such as surface color).
  87583. var Polygon = /** @class */ (function () {
  87584. function Polygon(vertices, shared) {
  87585. this.vertices = vertices;
  87586. this.shared = shared;
  87587. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  87588. }
  87589. Polygon.prototype.clone = function () {
  87590. var vertices = this.vertices.map(function (v) { return v.clone(); });
  87591. return new Polygon(vertices, this.shared);
  87592. };
  87593. Polygon.prototype.flip = function () {
  87594. this.vertices.reverse().map(function (v) { v.flip(); });
  87595. this.plane.flip();
  87596. };
  87597. return Polygon;
  87598. }());
  87599. // # class Node
  87600. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  87601. // by picking a polygon to split along. That polygon (and all other coplanar
  87602. // polygons) are added directly to that node and the other polygons are added to
  87603. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  87604. // no distinction between internal and leaf nodes.
  87605. var Node = /** @class */ (function () {
  87606. function Node(polygons) {
  87607. this.plane = null;
  87608. this.front = null;
  87609. this.back = null;
  87610. this.polygons = new Array();
  87611. if (polygons) {
  87612. this.build(polygons);
  87613. }
  87614. }
  87615. Node.prototype.clone = function () {
  87616. var node = new Node();
  87617. node.plane = this.plane && this.plane.clone();
  87618. node.front = this.front && this.front.clone();
  87619. node.back = this.back && this.back.clone();
  87620. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  87621. return node;
  87622. };
  87623. // Convert solid space to empty space and empty space to solid space.
  87624. Node.prototype.invert = function () {
  87625. for (var i = 0; i < this.polygons.length; i++) {
  87626. this.polygons[i].flip();
  87627. }
  87628. if (this.plane) {
  87629. this.plane.flip();
  87630. }
  87631. if (this.front) {
  87632. this.front.invert();
  87633. }
  87634. if (this.back) {
  87635. this.back.invert();
  87636. }
  87637. var temp = this.front;
  87638. this.front = this.back;
  87639. this.back = temp;
  87640. };
  87641. // Recursively remove all polygons in `polygons` that are inside this BSP
  87642. // tree.
  87643. Node.prototype.clipPolygons = function (polygons) {
  87644. if (!this.plane)
  87645. return polygons.slice();
  87646. var front = new Array(), back = new Array();
  87647. for (var i = 0; i < polygons.length; i++) {
  87648. this.plane.splitPolygon(polygons[i], front, back, front, back);
  87649. }
  87650. if (this.front) {
  87651. front = this.front.clipPolygons(front);
  87652. }
  87653. if (this.back) {
  87654. back = this.back.clipPolygons(back);
  87655. }
  87656. else {
  87657. back = [];
  87658. }
  87659. return front.concat(back);
  87660. };
  87661. // Remove all polygons in this BSP tree that are inside the other BSP tree
  87662. // `bsp`.
  87663. Node.prototype.clipTo = function (bsp) {
  87664. this.polygons = bsp.clipPolygons(this.polygons);
  87665. if (this.front)
  87666. this.front.clipTo(bsp);
  87667. if (this.back)
  87668. this.back.clipTo(bsp);
  87669. };
  87670. // Return a list of all polygons in this BSP tree.
  87671. Node.prototype.allPolygons = function () {
  87672. var polygons = this.polygons.slice();
  87673. if (this.front)
  87674. polygons = polygons.concat(this.front.allPolygons());
  87675. if (this.back)
  87676. polygons = polygons.concat(this.back.allPolygons());
  87677. return polygons;
  87678. };
  87679. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  87680. // new polygons are filtered down to the bottom of the tree and become new
  87681. // nodes there. Each set of polygons is partitioned using the first polygon
  87682. // (no heuristic is used to pick a good split).
  87683. Node.prototype.build = function (polygons) {
  87684. if (!polygons.length)
  87685. return;
  87686. if (!this.plane)
  87687. this.plane = polygons[0].plane.clone();
  87688. var front = new Array(), back = new Array();
  87689. for (var i = 0; i < polygons.length; i++) {
  87690. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  87691. }
  87692. if (front.length) {
  87693. if (!this.front)
  87694. this.front = new Node();
  87695. this.front.build(front);
  87696. }
  87697. if (back.length) {
  87698. if (!this.back)
  87699. this.back = new Node();
  87700. this.back.build(back);
  87701. }
  87702. };
  87703. return Node;
  87704. }());
  87705. var CSG = /** @class */ (function () {
  87706. function CSG() {
  87707. this.polygons = new Array();
  87708. }
  87709. // Convert BABYLON.Mesh to BABYLON.CSG
  87710. CSG.FromMesh = function (mesh) {
  87711. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  87712. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  87713. if (mesh instanceof BABYLON.Mesh) {
  87714. mesh.computeWorldMatrix(true);
  87715. matrix = mesh.getWorldMatrix();
  87716. meshPosition = mesh.position.clone();
  87717. meshRotation = mesh.rotation.clone();
  87718. if (mesh.rotationQuaternion) {
  87719. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  87720. }
  87721. meshScaling = mesh.scaling.clone();
  87722. }
  87723. else {
  87724. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  87725. }
  87726. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87727. var subMeshes = mesh.subMeshes;
  87728. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  87729. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  87730. vertices = [];
  87731. for (var j = 0; j < 3; j++) {
  87732. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  87733. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  87734. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  87735. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  87736. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  87737. vertex = new Vertex(position, normal, uv);
  87738. vertices.push(vertex);
  87739. }
  87740. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  87741. // To handle the case of degenerated triangle
  87742. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  87743. if (polygon.plane)
  87744. polygons.push(polygon);
  87745. }
  87746. }
  87747. var csg = CSG.FromPolygons(polygons);
  87748. csg.matrix = matrix;
  87749. csg.position = meshPosition;
  87750. csg.rotation = meshRotation;
  87751. csg.scaling = meshScaling;
  87752. csg.rotationQuaternion = meshRotationQuaternion;
  87753. currentCSGMeshId++;
  87754. return csg;
  87755. };
  87756. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  87757. CSG.FromPolygons = function (polygons) {
  87758. var csg = new CSG();
  87759. csg.polygons = polygons;
  87760. return csg;
  87761. };
  87762. CSG.prototype.clone = function () {
  87763. var csg = new CSG();
  87764. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  87765. csg.copyTransformAttributes(this);
  87766. return csg;
  87767. };
  87768. CSG.prototype.union = function (csg) {
  87769. var a = new Node(this.clone().polygons);
  87770. var b = new Node(csg.clone().polygons);
  87771. a.clipTo(b);
  87772. b.clipTo(a);
  87773. b.invert();
  87774. b.clipTo(a);
  87775. b.invert();
  87776. a.build(b.allPolygons());
  87777. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87778. };
  87779. CSG.prototype.unionInPlace = function (csg) {
  87780. var a = new Node(this.polygons);
  87781. var b = new Node(csg.polygons);
  87782. a.clipTo(b);
  87783. b.clipTo(a);
  87784. b.invert();
  87785. b.clipTo(a);
  87786. b.invert();
  87787. a.build(b.allPolygons());
  87788. this.polygons = a.allPolygons();
  87789. };
  87790. CSG.prototype.subtract = function (csg) {
  87791. var a = new Node(this.clone().polygons);
  87792. var b = new Node(csg.clone().polygons);
  87793. a.invert();
  87794. a.clipTo(b);
  87795. b.clipTo(a);
  87796. b.invert();
  87797. b.clipTo(a);
  87798. b.invert();
  87799. a.build(b.allPolygons());
  87800. a.invert();
  87801. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87802. };
  87803. CSG.prototype.subtractInPlace = function (csg) {
  87804. var a = new Node(this.polygons);
  87805. var b = new Node(csg.polygons);
  87806. a.invert();
  87807. a.clipTo(b);
  87808. b.clipTo(a);
  87809. b.invert();
  87810. b.clipTo(a);
  87811. b.invert();
  87812. a.build(b.allPolygons());
  87813. a.invert();
  87814. this.polygons = a.allPolygons();
  87815. };
  87816. CSG.prototype.intersect = function (csg) {
  87817. var a = new Node(this.clone().polygons);
  87818. var b = new Node(csg.clone().polygons);
  87819. a.invert();
  87820. b.clipTo(a);
  87821. b.invert();
  87822. a.clipTo(b);
  87823. b.clipTo(a);
  87824. a.build(b.allPolygons());
  87825. a.invert();
  87826. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87827. };
  87828. CSG.prototype.intersectInPlace = function (csg) {
  87829. var a = new Node(this.polygons);
  87830. var b = new Node(csg.polygons);
  87831. a.invert();
  87832. b.clipTo(a);
  87833. b.invert();
  87834. a.clipTo(b);
  87835. b.clipTo(a);
  87836. a.build(b.allPolygons());
  87837. a.invert();
  87838. this.polygons = a.allPolygons();
  87839. };
  87840. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  87841. // not modified.
  87842. CSG.prototype.inverse = function () {
  87843. var csg = this.clone();
  87844. csg.inverseInPlace();
  87845. return csg;
  87846. };
  87847. CSG.prototype.inverseInPlace = function () {
  87848. this.polygons.map(function (p) { p.flip(); });
  87849. };
  87850. // This is used to keep meshes transformations so they can be restored
  87851. // when we build back a Babylon Mesh
  87852. // NB : All CSG operations are performed in world coordinates
  87853. CSG.prototype.copyTransformAttributes = function (csg) {
  87854. this.matrix = csg.matrix;
  87855. this.position = csg.position;
  87856. this.rotation = csg.rotation;
  87857. this.scaling = csg.scaling;
  87858. this.rotationQuaternion = csg.rotationQuaternion;
  87859. return this;
  87860. };
  87861. // Build Raw mesh from CSG
  87862. // Coordinates here are in world space
  87863. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  87864. var matrix = this.matrix.clone();
  87865. matrix.invert();
  87866. 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;
  87867. if (keepSubMeshes) {
  87868. // Sort Polygons, since subMeshes are indices range
  87869. polygons.sort(function (a, b) {
  87870. if (a.shared.meshId === b.shared.meshId) {
  87871. return a.shared.subMeshId - b.shared.subMeshId;
  87872. }
  87873. else {
  87874. return a.shared.meshId - b.shared.meshId;
  87875. }
  87876. });
  87877. }
  87878. for (var i = 0, il = polygons.length; i < il; i++) {
  87879. polygon = polygons[i];
  87880. // Building SubMeshes
  87881. if (!subMesh_dict[polygon.shared.meshId]) {
  87882. subMesh_dict[polygon.shared.meshId] = {};
  87883. }
  87884. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  87885. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  87886. indexStart: +Infinity,
  87887. indexEnd: -Infinity,
  87888. materialIndex: polygon.shared.materialIndex
  87889. };
  87890. }
  87891. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  87892. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  87893. polygonIndices[0] = 0;
  87894. polygonIndices[1] = j - 1;
  87895. polygonIndices[2] = j;
  87896. for (var k = 0; k < 3; k++) {
  87897. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  87898. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  87899. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  87900. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  87901. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  87902. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  87903. // Check if 2 points can be merged
  87904. if (!(typeof vertex_idx !== 'undefined' &&
  87905. normals[vertex_idx * 3] === localNormal.x &&
  87906. normals[vertex_idx * 3 + 1] === localNormal.y &&
  87907. normals[vertex_idx * 3 + 2] === localNormal.z &&
  87908. uvs[vertex_idx * 2] === uv.x &&
  87909. uvs[vertex_idx * 2 + 1] === uv.y)) {
  87910. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  87911. uvs.push(uv.x, uv.y);
  87912. normals.push(normal.x, normal.y, normal.z);
  87913. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  87914. }
  87915. indices.push(vertex_idx);
  87916. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  87917. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  87918. currentIndex++;
  87919. }
  87920. }
  87921. }
  87922. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  87923. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  87924. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  87925. mesh.setIndices(indices, null);
  87926. if (keepSubMeshes) {
  87927. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  87928. var materialIndexOffset = 0, materialMaxIndex;
  87929. mesh.subMeshes = new Array();
  87930. for (var m in subMesh_dict) {
  87931. materialMaxIndex = -1;
  87932. for (var sm in subMesh_dict[m]) {
  87933. subMesh_obj = subMesh_dict[m][sm];
  87934. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  87935. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  87936. }
  87937. materialIndexOffset += ++materialMaxIndex;
  87938. }
  87939. }
  87940. return mesh;
  87941. };
  87942. // Build Mesh from CSG taking material and transforms into account
  87943. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  87944. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  87945. mesh.material = material;
  87946. mesh.position.copyFrom(this.position);
  87947. mesh.rotation.copyFrom(this.rotation);
  87948. if (this.rotationQuaternion) {
  87949. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  87950. }
  87951. mesh.scaling.copyFrom(this.scaling);
  87952. mesh.computeWorldMatrix(true);
  87953. return mesh;
  87954. };
  87955. return CSG;
  87956. }());
  87957. BABYLON.CSG = CSG;
  87958. })(BABYLON || (BABYLON = {}));
  87959. //# sourceMappingURL=babylon.csg.js.map
  87960. var BABYLON;
  87961. (function (BABYLON) {
  87962. var LensFlare = /** @class */ (function () {
  87963. function LensFlare(size, position, color, imgUrl, system) {
  87964. this.size = size;
  87965. this.position = position;
  87966. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87967. this.color = color || new BABYLON.Color3(1, 1, 1);
  87968. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  87969. this._system = system;
  87970. system.lensFlares.push(this);
  87971. }
  87972. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  87973. return new LensFlare(size, position, color, imgUrl, system);
  87974. };
  87975. LensFlare.prototype.dispose = function () {
  87976. if (this.texture) {
  87977. this.texture.dispose();
  87978. }
  87979. // Remove from scene
  87980. var index = this._system.lensFlares.indexOf(this);
  87981. this._system.lensFlares.splice(index, 1);
  87982. };
  87983. ;
  87984. return LensFlare;
  87985. }());
  87986. BABYLON.LensFlare = LensFlare;
  87987. })(BABYLON || (BABYLON = {}));
  87988. //# sourceMappingURL=babylon.lensFlare.js.map
  87989. var BABYLON;
  87990. (function (BABYLON) {
  87991. // Adds the parser to the scene parsers.
  87992. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  87993. // Lens flares
  87994. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  87995. if (!container.lensFlareSystems) {
  87996. container.lensFlareSystems = new Array();
  87997. }
  87998. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  87999. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  88000. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  88001. container.lensFlareSystems.push(lf);
  88002. }
  88003. }
  88004. });
  88005. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  88006. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  88007. if (this.lensFlareSystems[index].name === name) {
  88008. return this.lensFlareSystems[index];
  88009. }
  88010. }
  88011. return null;
  88012. };
  88013. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  88014. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  88015. if (this.lensFlareSystems[index].id === id) {
  88016. return this.lensFlareSystems[index];
  88017. }
  88018. }
  88019. return null;
  88020. };
  88021. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  88022. var index = this.lensFlareSystems.indexOf(toRemove);
  88023. if (index !== -1) {
  88024. this.lensFlareSystems.splice(index, 1);
  88025. }
  88026. return index;
  88027. };
  88028. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  88029. this.lensFlareSystems.push(newLensFlareSystem);
  88030. };
  88031. /**
  88032. * Defines the lens flare scene component responsible to manage any lens flares
  88033. * in a given scene.
  88034. */
  88035. var LensFlareSystemSceneComponent = /** @class */ (function () {
  88036. /**
  88037. * Creates a new instance of the component for the given scene
  88038. * @param scene Defines the scene to register the component in
  88039. */
  88040. function LensFlareSystemSceneComponent(scene) {
  88041. /**
  88042. * The component name helpfull to identify the component in the list of scene components.
  88043. */
  88044. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  88045. this.scene = scene;
  88046. scene.lensFlareSystems = new Array();
  88047. }
  88048. /**
  88049. * Registers the component in a given scene
  88050. */
  88051. LensFlareSystemSceneComponent.prototype.register = function () {
  88052. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  88053. };
  88054. /**
  88055. * Rebuilds the elements related to this component in case of
  88056. * context lost for instance.
  88057. */
  88058. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  88059. // Nothing to do for lens flare
  88060. };
  88061. /**
  88062. * Adds all the element from the container to the scene
  88063. * @param container the container holding the elements
  88064. */
  88065. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  88066. var _this = this;
  88067. if (!container.lensFlareSystems) {
  88068. return;
  88069. }
  88070. container.lensFlareSystems.forEach(function (o) {
  88071. _this.scene.addLensFlareSystem(o);
  88072. });
  88073. };
  88074. /**
  88075. * Removes all the elements in the container from the scene
  88076. * @param container contains the elements to remove
  88077. */
  88078. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  88079. var _this = this;
  88080. if (!container.lensFlareSystems) {
  88081. return;
  88082. }
  88083. container.lensFlareSystems.forEach(function (o) {
  88084. _this.scene.removeLensFlareSystem(o);
  88085. });
  88086. };
  88087. /**
  88088. * Serializes the component data to the specified json object
  88089. * @param serializationObject The object to serialize to
  88090. */
  88091. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  88092. // Lens flares
  88093. serializationObject.lensFlareSystems = [];
  88094. var lensFlareSystems = this.scene.lensFlareSystems;
  88095. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  88096. var lensFlareSystem = lensFlareSystems_1[_i];
  88097. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  88098. }
  88099. };
  88100. /**
  88101. * Disposes the component and the associated ressources.
  88102. */
  88103. LensFlareSystemSceneComponent.prototype.dispose = function () {
  88104. var lensFlareSystems = this.scene.lensFlareSystems;
  88105. while (lensFlareSystems.length) {
  88106. lensFlareSystems[0].dispose();
  88107. }
  88108. };
  88109. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  88110. // Lens flares
  88111. if (this.scene.lensFlaresEnabled) {
  88112. var lensFlareSystems = this.scene.lensFlareSystems;
  88113. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  88114. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  88115. var lensFlareSystem = lensFlareSystems_2[_i];
  88116. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  88117. lensFlareSystem.render();
  88118. }
  88119. }
  88120. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  88121. }
  88122. };
  88123. return LensFlareSystemSceneComponent;
  88124. }());
  88125. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  88126. })(BABYLON || (BABYLON = {}));
  88127. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  88128. var BABYLON;
  88129. (function (BABYLON) {
  88130. var LensFlareSystem = /** @class */ (function () {
  88131. function LensFlareSystem(name, emitter, scene) {
  88132. this.name = name;
  88133. this.lensFlares = new Array();
  88134. this.borderLimit = 300;
  88135. this.viewportBorder = 0;
  88136. this.layerMask = 0x0FFFFFFF;
  88137. this._vertexBuffers = {};
  88138. this._isEnabled = true;
  88139. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88140. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  88141. if (!component) {
  88142. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  88143. scene._addComponent(component);
  88144. }
  88145. this._emitter = emitter;
  88146. this.id = name;
  88147. scene.lensFlareSystems.push(this);
  88148. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  88149. var engine = scene.getEngine();
  88150. // VBO
  88151. var vertices = [];
  88152. vertices.push(1, 1);
  88153. vertices.push(-1, 1);
  88154. vertices.push(-1, -1);
  88155. vertices.push(1, -1);
  88156. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88157. // Indices
  88158. var indices = [];
  88159. indices.push(0);
  88160. indices.push(1);
  88161. indices.push(2);
  88162. indices.push(0);
  88163. indices.push(2);
  88164. indices.push(3);
  88165. this._indexBuffer = engine.createIndexBuffer(indices);
  88166. // Effects
  88167. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  88168. }
  88169. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  88170. get: function () {
  88171. return this._isEnabled;
  88172. },
  88173. set: function (value) {
  88174. this._isEnabled = value;
  88175. },
  88176. enumerable: true,
  88177. configurable: true
  88178. });
  88179. LensFlareSystem.prototype.getScene = function () {
  88180. return this._scene;
  88181. };
  88182. LensFlareSystem.prototype.getEmitter = function () {
  88183. return this._emitter;
  88184. };
  88185. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  88186. this._emitter = newEmitter;
  88187. };
  88188. LensFlareSystem.prototype.getEmitterPosition = function () {
  88189. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  88190. };
  88191. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  88192. var position = this.getEmitterPosition();
  88193. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  88194. this._positionX = position.x;
  88195. this._positionY = position.y;
  88196. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  88197. if (this.viewportBorder > 0) {
  88198. globalViewport.x -= this.viewportBorder;
  88199. globalViewport.y -= this.viewportBorder;
  88200. globalViewport.width += this.viewportBorder * 2;
  88201. globalViewport.height += this.viewportBorder * 2;
  88202. position.x += this.viewportBorder;
  88203. position.y += this.viewportBorder;
  88204. this._positionX += this.viewportBorder;
  88205. this._positionY += this.viewportBorder;
  88206. }
  88207. if (position.z > 0) {
  88208. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  88209. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  88210. return true;
  88211. }
  88212. return true;
  88213. }
  88214. return false;
  88215. };
  88216. /** @hidden */
  88217. LensFlareSystem.prototype._isVisible = function () {
  88218. if (!this._isEnabled || !this._scene.activeCamera) {
  88219. return false;
  88220. }
  88221. var emitterPosition = this.getEmitterPosition();
  88222. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  88223. var distance = direction.length();
  88224. direction.normalize();
  88225. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  88226. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  88227. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  88228. };
  88229. LensFlareSystem.prototype.render = function () {
  88230. if (!this._effect.isReady() || !this._scene.activeCamera)
  88231. return false;
  88232. var engine = this._scene.getEngine();
  88233. var viewport = this._scene.activeCamera.viewport;
  88234. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  88235. // Position
  88236. if (!this.computeEffectivePosition(globalViewport)) {
  88237. return false;
  88238. }
  88239. // Visibility
  88240. if (!this._isVisible()) {
  88241. return false;
  88242. }
  88243. // Intensity
  88244. var awayX;
  88245. var awayY;
  88246. if (this._positionX < this.borderLimit + globalViewport.x) {
  88247. awayX = this.borderLimit + globalViewport.x - this._positionX;
  88248. }
  88249. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  88250. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  88251. }
  88252. else {
  88253. awayX = 0;
  88254. }
  88255. if (this._positionY < this.borderLimit + globalViewport.y) {
  88256. awayY = this.borderLimit + globalViewport.y - this._positionY;
  88257. }
  88258. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  88259. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  88260. }
  88261. else {
  88262. awayY = 0;
  88263. }
  88264. var away = (awayX > awayY) ? awayX : awayY;
  88265. away -= this.viewportBorder;
  88266. if (away > this.borderLimit) {
  88267. away = this.borderLimit;
  88268. }
  88269. var intensity = 1.0 - (away / this.borderLimit);
  88270. if (intensity < 0) {
  88271. return false;
  88272. }
  88273. if (intensity > 1.0) {
  88274. intensity = 1.0;
  88275. }
  88276. if (this.viewportBorder > 0) {
  88277. globalViewport.x += this.viewportBorder;
  88278. globalViewport.y += this.viewportBorder;
  88279. globalViewport.width -= this.viewportBorder * 2;
  88280. globalViewport.height -= this.viewportBorder * 2;
  88281. this._positionX -= this.viewportBorder;
  88282. this._positionY -= this.viewportBorder;
  88283. }
  88284. // Position
  88285. var centerX = globalViewport.x + globalViewport.width / 2;
  88286. var centerY = globalViewport.y + globalViewport.height / 2;
  88287. var distX = centerX - this._positionX;
  88288. var distY = centerY - this._positionY;
  88289. // Effects
  88290. engine.enableEffect(this._effect);
  88291. engine.setState(false);
  88292. engine.setDepthBuffer(false);
  88293. // VBOs
  88294. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  88295. // Flares
  88296. for (var index = 0; index < this.lensFlares.length; index++) {
  88297. var flare = this.lensFlares[index];
  88298. engine.setAlphaMode(flare.alphaMode);
  88299. var x = centerX - (distX * flare.position);
  88300. var y = centerY - (distY * flare.position);
  88301. var cw = flare.size;
  88302. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  88303. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  88304. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  88305. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  88306. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  88307. // Texture
  88308. this._effect.setTexture("textureSampler", flare.texture);
  88309. // Color
  88310. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  88311. // Draw order
  88312. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88313. }
  88314. engine.setDepthBuffer(true);
  88315. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88316. return true;
  88317. };
  88318. LensFlareSystem.prototype.dispose = function () {
  88319. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88320. if (vertexBuffer) {
  88321. vertexBuffer.dispose();
  88322. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88323. }
  88324. if (this._indexBuffer) {
  88325. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88326. this._indexBuffer = null;
  88327. }
  88328. while (this.lensFlares.length) {
  88329. this.lensFlares[0].dispose();
  88330. }
  88331. // Remove from scene
  88332. var index = this._scene.lensFlareSystems.indexOf(this);
  88333. this._scene.lensFlareSystems.splice(index, 1);
  88334. };
  88335. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  88336. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  88337. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  88338. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  88339. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  88340. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  88341. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  88342. var parsedFlare = parsedLensFlareSystem.flares[index];
  88343. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  88344. }
  88345. return lensFlareSystem;
  88346. };
  88347. LensFlareSystem.prototype.serialize = function () {
  88348. var serializationObject = {};
  88349. serializationObject.id = this.id;
  88350. serializationObject.name = this.name;
  88351. serializationObject.emitterId = this.getEmitter().id;
  88352. serializationObject.borderLimit = this.borderLimit;
  88353. serializationObject.flares = [];
  88354. for (var index = 0; index < this.lensFlares.length; index++) {
  88355. var flare = this.lensFlares[index];
  88356. serializationObject.flares.push({
  88357. size: flare.size,
  88358. position: flare.position,
  88359. color: flare.color.asArray(),
  88360. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  88361. });
  88362. }
  88363. return serializationObject;
  88364. };
  88365. return LensFlareSystem;
  88366. }());
  88367. BABYLON.LensFlareSystem = LensFlareSystem;
  88368. })(BABYLON || (BABYLON = {}));
  88369. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  88370. var BABYLON;
  88371. (function (BABYLON) {
  88372. /**
  88373. * This is a holder class for the physics joint created by the physics plugin.
  88374. * It holds a set of functions to control the underlying joint.
  88375. */
  88376. var PhysicsJoint = /** @class */ (function () {
  88377. function PhysicsJoint(type, jointData) {
  88378. this.type = type;
  88379. this.jointData = jointData;
  88380. jointData.nativeParams = jointData.nativeParams || {};
  88381. }
  88382. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  88383. get: function () {
  88384. return this._physicsJoint;
  88385. },
  88386. set: function (newJoint) {
  88387. if (this._physicsJoint) {
  88388. //remove from the wolrd
  88389. }
  88390. this._physicsJoint = newJoint;
  88391. },
  88392. enumerable: true,
  88393. configurable: true
  88394. });
  88395. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  88396. set: function (physicsPlugin) {
  88397. this._physicsPlugin = physicsPlugin;
  88398. },
  88399. enumerable: true,
  88400. configurable: true
  88401. });
  88402. /**
  88403. * Execute a function that is physics-plugin specific.
  88404. * @param {Function} func the function that will be executed.
  88405. * It accepts two parameters: the physics world and the physics joint.
  88406. */
  88407. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  88408. func(this._physicsPlugin.world, this._physicsJoint);
  88409. };
  88410. //TODO check if the native joints are the same
  88411. //Joint Types
  88412. PhysicsJoint.DistanceJoint = 0;
  88413. PhysicsJoint.HingeJoint = 1;
  88414. PhysicsJoint.BallAndSocketJoint = 2;
  88415. PhysicsJoint.WheelJoint = 3;
  88416. PhysicsJoint.SliderJoint = 4;
  88417. //OIMO
  88418. PhysicsJoint.PrismaticJoint = 5;
  88419. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  88420. PhysicsJoint.UniversalJoint = 6;
  88421. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  88422. //Cannon
  88423. //Similar to a Ball-Joint. Different in params
  88424. PhysicsJoint.PointToPointJoint = 8;
  88425. //Cannon only at the moment
  88426. PhysicsJoint.SpringJoint = 9;
  88427. PhysicsJoint.LockJoint = 10;
  88428. return PhysicsJoint;
  88429. }());
  88430. BABYLON.PhysicsJoint = PhysicsJoint;
  88431. /**
  88432. * A class representing a physics distance joint.
  88433. */
  88434. var DistanceJoint = /** @class */ (function (_super) {
  88435. __extends(DistanceJoint, _super);
  88436. function DistanceJoint(jointData) {
  88437. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  88438. }
  88439. /**
  88440. * Update the predefined distance.
  88441. */
  88442. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  88443. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  88444. };
  88445. return DistanceJoint;
  88446. }(PhysicsJoint));
  88447. BABYLON.DistanceJoint = DistanceJoint;
  88448. var MotorEnabledJoint = /** @class */ (function (_super) {
  88449. __extends(MotorEnabledJoint, _super);
  88450. function MotorEnabledJoint(type, jointData) {
  88451. return _super.call(this, type, jointData) || this;
  88452. }
  88453. /**
  88454. * Set the motor values.
  88455. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88456. * @param {number} force the force to apply
  88457. * @param {number} maxForce max force for this motor.
  88458. */
  88459. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  88460. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88461. };
  88462. /**
  88463. * Set the motor's limits.
  88464. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88465. */
  88466. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88467. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88468. };
  88469. return MotorEnabledJoint;
  88470. }(PhysicsJoint));
  88471. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  88472. /**
  88473. * This class represents a single hinge physics joint
  88474. */
  88475. var HingeJoint = /** @class */ (function (_super) {
  88476. __extends(HingeJoint, _super);
  88477. function HingeJoint(jointData) {
  88478. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  88479. }
  88480. /**
  88481. * Set the motor values.
  88482. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88483. * @param {number} force the force to apply
  88484. * @param {number} maxForce max force for this motor.
  88485. */
  88486. HingeJoint.prototype.setMotor = function (force, maxForce) {
  88487. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88488. };
  88489. /**
  88490. * Set the motor's limits.
  88491. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88492. */
  88493. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88494. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88495. };
  88496. return HingeJoint;
  88497. }(MotorEnabledJoint));
  88498. BABYLON.HingeJoint = HingeJoint;
  88499. /**
  88500. * This class represents a dual hinge physics joint (same as wheel joint)
  88501. */
  88502. var Hinge2Joint = /** @class */ (function (_super) {
  88503. __extends(Hinge2Joint, _super);
  88504. function Hinge2Joint(jointData) {
  88505. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  88506. }
  88507. /**
  88508. * Set the motor values.
  88509. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88510. * @param {number} force the force to apply
  88511. * @param {number} maxForce max force for this motor.
  88512. * @param {motorIndex} the motor's index, 0 or 1.
  88513. */
  88514. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  88515. if (motorIndex === void 0) { motorIndex = 0; }
  88516. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  88517. };
  88518. /**
  88519. * Set the motor limits.
  88520. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88521. * @param {number} upperLimit the upper limit
  88522. * @param {number} lowerLimit lower limit
  88523. * @param {motorIndex} the motor's index, 0 or 1.
  88524. */
  88525. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  88526. if (motorIndex === void 0) { motorIndex = 0; }
  88527. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  88528. };
  88529. return Hinge2Joint;
  88530. }(MotorEnabledJoint));
  88531. BABYLON.Hinge2Joint = Hinge2Joint;
  88532. })(BABYLON || (BABYLON = {}));
  88533. //# sourceMappingURL=babylon.physicsJoint.js.map
  88534. var BABYLON;
  88535. (function (BABYLON) {
  88536. var PhysicsImpostor = /** @class */ (function () {
  88537. function PhysicsImpostor(object, type, _options, _scene) {
  88538. if (_options === void 0) { _options = { mass: 0 }; }
  88539. var _this = this;
  88540. this.object = object;
  88541. this.type = type;
  88542. this._options = _options;
  88543. this._scene = _scene;
  88544. this._bodyUpdateRequired = false;
  88545. this._onBeforePhysicsStepCallbacks = new Array();
  88546. this._onAfterPhysicsStepCallbacks = new Array();
  88547. this._onPhysicsCollideCallbacks = [];
  88548. this._deltaPosition = BABYLON.Vector3.Zero();
  88549. this._isDisposed = false;
  88550. //temp variables for parent rotation calculations
  88551. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  88552. this._tmpQuat = new BABYLON.Quaternion();
  88553. this._tmpQuat2 = new BABYLON.Quaternion();
  88554. /**
  88555. * this function is executed by the physics engine.
  88556. */
  88557. this.beforeStep = function () {
  88558. if (!_this._physicsEngine) {
  88559. return;
  88560. }
  88561. _this.object.translate(_this._deltaPosition, -1);
  88562. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  88563. _this.object.computeWorldMatrix(false);
  88564. if (_this.object.parent && _this.object.rotationQuaternion) {
  88565. _this.getParentsRotation();
  88566. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  88567. }
  88568. else {
  88569. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  88570. }
  88571. if (!_this._options.disableBidirectionalTransformation) {
  88572. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  88573. }
  88574. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  88575. func(_this);
  88576. });
  88577. };
  88578. /**
  88579. * this function is executed by the physics engine.
  88580. */
  88581. this.afterStep = function () {
  88582. if (!_this._physicsEngine) {
  88583. return;
  88584. }
  88585. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  88586. func(_this);
  88587. });
  88588. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  88589. // object has now its world rotation. needs to be converted to local.
  88590. if (_this.object.parent && _this.object.rotationQuaternion) {
  88591. _this.getParentsRotation();
  88592. _this._tmpQuat.conjugateInPlace();
  88593. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  88594. }
  88595. // take the position set and make it the absolute position of this object.
  88596. _this.object.setAbsolutePosition(_this.object.position);
  88597. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  88598. _this.object.translate(_this._deltaPosition, 1);
  88599. };
  88600. /**
  88601. * Legacy collision detection event support
  88602. */
  88603. this.onCollideEvent = null;
  88604. //event and body object due to cannon's event-based architecture.
  88605. this.onCollide = function (e) {
  88606. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  88607. return;
  88608. }
  88609. if (!_this._physicsEngine) {
  88610. return;
  88611. }
  88612. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  88613. if (otherImpostor) {
  88614. // Legacy collision detection event support
  88615. if (_this.onCollideEvent) {
  88616. _this.onCollideEvent(_this, otherImpostor);
  88617. }
  88618. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  88619. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  88620. }).forEach(function (obj) {
  88621. obj.callback(_this, otherImpostor);
  88622. });
  88623. }
  88624. };
  88625. //sanity check!
  88626. if (!this.object) {
  88627. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  88628. return;
  88629. }
  88630. //legacy support for old syntax.
  88631. if (!this._scene && object.getScene) {
  88632. this._scene = object.getScene();
  88633. }
  88634. if (!this._scene) {
  88635. return;
  88636. }
  88637. this._physicsEngine = this._scene.getPhysicsEngine();
  88638. if (!this._physicsEngine) {
  88639. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  88640. }
  88641. else {
  88642. //set the object's quaternion, if not set
  88643. if (!this.object.rotationQuaternion) {
  88644. if (this.object.rotation) {
  88645. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  88646. }
  88647. else {
  88648. this.object.rotationQuaternion = new BABYLON.Quaternion();
  88649. }
  88650. }
  88651. //default options params
  88652. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  88653. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  88654. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  88655. this._joints = [];
  88656. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  88657. if (!this.object.parent || this._options.ignoreParent) {
  88658. this._init();
  88659. }
  88660. else if (this.object.parent.physicsImpostor) {
  88661. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  88662. }
  88663. }
  88664. }
  88665. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  88666. get: function () {
  88667. return this._isDisposed;
  88668. },
  88669. enumerable: true,
  88670. configurable: true
  88671. });
  88672. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  88673. get: function () {
  88674. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  88675. },
  88676. set: function (value) {
  88677. this.setMass(value);
  88678. },
  88679. enumerable: true,
  88680. configurable: true
  88681. });
  88682. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  88683. get: function () {
  88684. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  88685. },
  88686. set: function (value) {
  88687. if (!this._physicsEngine) {
  88688. return;
  88689. }
  88690. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  88691. },
  88692. enumerable: true,
  88693. configurable: true
  88694. });
  88695. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  88696. get: function () {
  88697. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  88698. },
  88699. set: function (value) {
  88700. if (!this._physicsEngine) {
  88701. return;
  88702. }
  88703. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  88704. },
  88705. enumerable: true,
  88706. configurable: true
  88707. });
  88708. /**
  88709. * This function will completly initialize this impostor.
  88710. * It will create a new body - but only if this mesh has no parent.
  88711. * If it has, this impostor will not be used other than to define the impostor
  88712. * of the child mesh.
  88713. * @hidden
  88714. */
  88715. PhysicsImpostor.prototype._init = function () {
  88716. if (!this._physicsEngine) {
  88717. return;
  88718. }
  88719. this._physicsEngine.removeImpostor(this);
  88720. this.physicsBody = null;
  88721. this._parent = this._parent || this._getPhysicsParent();
  88722. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  88723. this._physicsEngine.addImpostor(this);
  88724. }
  88725. };
  88726. PhysicsImpostor.prototype._getPhysicsParent = function () {
  88727. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  88728. var parentMesh = this.object.parent;
  88729. return parentMesh.physicsImpostor;
  88730. }
  88731. return null;
  88732. };
  88733. /**
  88734. * Should a new body be generated.
  88735. */
  88736. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  88737. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  88738. };
  88739. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  88740. this.forceUpdate();
  88741. };
  88742. /**
  88743. * Force a regeneration of this or the parent's impostor's body.
  88744. * Use under cautious - This will remove all joints already implemented.
  88745. */
  88746. PhysicsImpostor.prototype.forceUpdate = function () {
  88747. this._init();
  88748. if (this.parent && !this._options.ignoreParent) {
  88749. this.parent.forceUpdate();
  88750. }
  88751. };
  88752. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  88753. /*public get mesh(): AbstractMesh {
  88754. return this._mesh;
  88755. }*/
  88756. /**
  88757. * Gets the body that holds this impostor. Either its own, or its parent.
  88758. */
  88759. get: function () {
  88760. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  88761. },
  88762. /**
  88763. * Set the physics body. Used mainly by the physics engine/plugin
  88764. */
  88765. set: function (physicsBody) {
  88766. if (this._physicsBody && this._physicsEngine) {
  88767. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  88768. }
  88769. this._physicsBody = physicsBody;
  88770. this.resetUpdateFlags();
  88771. },
  88772. enumerable: true,
  88773. configurable: true
  88774. });
  88775. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  88776. get: function () {
  88777. return !this._options.ignoreParent && this._parent ? this._parent : null;
  88778. },
  88779. set: function (value) {
  88780. this._parent = value;
  88781. },
  88782. enumerable: true,
  88783. configurable: true
  88784. });
  88785. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  88786. this._bodyUpdateRequired = false;
  88787. };
  88788. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  88789. if (this.object.getBoundingInfo) {
  88790. var q = this.object.rotationQuaternion;
  88791. //reset rotation
  88792. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  88793. //calculate the world matrix with no rotation
  88794. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88795. var boundingInfo = this.object.getBoundingInfo();
  88796. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  88797. //bring back the rotation
  88798. this.object.rotationQuaternion = q;
  88799. //calculate the world matrix with the new rotation
  88800. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88801. return size;
  88802. }
  88803. else {
  88804. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  88805. }
  88806. };
  88807. PhysicsImpostor.prototype.getObjectCenter = function () {
  88808. if (this.object.getBoundingInfo) {
  88809. var boundingInfo = this.object.getBoundingInfo();
  88810. return boundingInfo.boundingBox.centerWorld;
  88811. }
  88812. else {
  88813. return this.object.position;
  88814. }
  88815. };
  88816. /**
  88817. * Get a specific parametes from the options parameter.
  88818. */
  88819. PhysicsImpostor.prototype.getParam = function (paramName) {
  88820. return this._options[paramName];
  88821. };
  88822. /**
  88823. * Sets a specific parameter in the options given to the physics plugin
  88824. */
  88825. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  88826. this._options[paramName] = value;
  88827. this._bodyUpdateRequired = true;
  88828. };
  88829. /**
  88830. * Specifically change the body's mass option. Won't recreate the physics body object
  88831. */
  88832. PhysicsImpostor.prototype.setMass = function (mass) {
  88833. if (this.getParam("mass") !== mass) {
  88834. this.setParam("mass", mass);
  88835. }
  88836. if (this._physicsEngine) {
  88837. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  88838. }
  88839. };
  88840. PhysicsImpostor.prototype.getLinearVelocity = function () {
  88841. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  88842. };
  88843. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  88844. if (this._physicsEngine) {
  88845. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  88846. }
  88847. };
  88848. PhysicsImpostor.prototype.getAngularVelocity = function () {
  88849. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  88850. };
  88851. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  88852. if (this._physicsEngine) {
  88853. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  88854. }
  88855. };
  88856. /**
  88857. * Execute a function with the physics plugin native code.
  88858. * Provide a function the will have two variables - the world object and the physics body object.
  88859. */
  88860. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  88861. if (this._physicsEngine) {
  88862. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  88863. }
  88864. };
  88865. /**
  88866. * Register a function that will be executed before the physics world is stepping forward.
  88867. */
  88868. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  88869. this._onBeforePhysicsStepCallbacks.push(func);
  88870. };
  88871. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  88872. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  88873. if (index > -1) {
  88874. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  88875. }
  88876. else {
  88877. BABYLON.Tools.Warn("Function to remove was not found");
  88878. }
  88879. };
  88880. /**
  88881. * Register a function that will be executed after the physics step
  88882. */
  88883. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  88884. this._onAfterPhysicsStepCallbacks.push(func);
  88885. };
  88886. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  88887. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  88888. if (index > -1) {
  88889. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  88890. }
  88891. else {
  88892. BABYLON.Tools.Warn("Function to remove was not found");
  88893. }
  88894. };
  88895. /**
  88896. * register a function that will be executed when this impostor collides against a different body.
  88897. */
  88898. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  88899. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88900. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  88901. };
  88902. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  88903. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88904. var index = -1;
  88905. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  88906. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  88907. // chcek the arrays match
  88908. var sameList = cbDef.otherImpostors.every(function (impostor) {
  88909. return collidedAgainstList.indexOf(impostor) > -1;
  88910. });
  88911. if (sameList) {
  88912. index = idx;
  88913. }
  88914. return sameList;
  88915. }
  88916. return false;
  88917. });
  88918. if (found) {
  88919. this._onPhysicsCollideCallbacks.splice(index, 1);
  88920. }
  88921. else {
  88922. BABYLON.Tools.Warn("Function to remove was not found");
  88923. }
  88924. };
  88925. PhysicsImpostor.prototype.getParentsRotation = function () {
  88926. var parent = this.object.parent;
  88927. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  88928. while (parent) {
  88929. if (parent.rotationQuaternion) {
  88930. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  88931. }
  88932. else {
  88933. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  88934. }
  88935. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  88936. parent = parent.parent;
  88937. }
  88938. return this._tmpQuat;
  88939. };
  88940. /**
  88941. * Apply a force
  88942. */
  88943. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  88944. if (this._physicsEngine) {
  88945. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  88946. }
  88947. return this;
  88948. };
  88949. /**
  88950. * Apply an impulse
  88951. */
  88952. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  88953. if (this._physicsEngine) {
  88954. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  88955. }
  88956. return this;
  88957. };
  88958. /**
  88959. * A help function to create a joint.
  88960. */
  88961. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  88962. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  88963. this.addJoint(otherImpostor, joint);
  88964. return this;
  88965. };
  88966. /**
  88967. * Add a joint to this impostor with a different impostor.
  88968. */
  88969. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  88970. this._joints.push({
  88971. otherImpostor: otherImpostor,
  88972. joint: joint
  88973. });
  88974. if (this._physicsEngine) {
  88975. this._physicsEngine.addJoint(this, otherImpostor, joint);
  88976. }
  88977. return this;
  88978. };
  88979. /**
  88980. * Will keep this body still, in a sleep mode.
  88981. */
  88982. PhysicsImpostor.prototype.sleep = function () {
  88983. if (this._physicsEngine) {
  88984. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  88985. }
  88986. return this;
  88987. };
  88988. /**
  88989. * Wake the body up.
  88990. */
  88991. PhysicsImpostor.prototype.wakeUp = function () {
  88992. if (this._physicsEngine) {
  88993. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  88994. }
  88995. return this;
  88996. };
  88997. PhysicsImpostor.prototype.clone = function (newObject) {
  88998. if (!newObject)
  88999. return null;
  89000. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  89001. };
  89002. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  89003. var _this = this;
  89004. //no dispose if no physics engine is available.
  89005. if (!this._physicsEngine) {
  89006. return;
  89007. }
  89008. this._joints.forEach(function (j) {
  89009. if (_this._physicsEngine) {
  89010. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  89011. }
  89012. });
  89013. //dispose the physics body
  89014. this._physicsEngine.removeImpostor(this);
  89015. if (this.parent) {
  89016. this.parent.forceUpdate();
  89017. }
  89018. else {
  89019. /*this._object.getChildMeshes().forEach(function(mesh) {
  89020. if (mesh.physicsImpostor) {
  89021. if (disposeChildren) {
  89022. mesh.physicsImpostor.dispose();
  89023. mesh.physicsImpostor = null;
  89024. }
  89025. }
  89026. })*/
  89027. }
  89028. this._isDisposed = true;
  89029. };
  89030. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  89031. this._deltaPosition.copyFrom(position);
  89032. };
  89033. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  89034. if (!this._deltaRotation) {
  89035. this._deltaRotation = new BABYLON.Quaternion();
  89036. }
  89037. this._deltaRotation.copyFrom(rotation);
  89038. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  89039. };
  89040. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  89041. if (this._physicsEngine) {
  89042. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  89043. }
  89044. return this;
  89045. };
  89046. PhysicsImpostor.prototype.getRadius = function () {
  89047. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  89048. };
  89049. /**
  89050. * Sync a bone with this impostor
  89051. * @param bone The bone to sync to the impostor.
  89052. * @param boneMesh The mesh that the bone is influencing.
  89053. * @param jointPivot The pivot of the joint / bone in local space.
  89054. * @param distToJoint Optional distance from the impostor to the joint.
  89055. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  89056. */
  89057. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  89058. var tempVec = PhysicsImpostor._tmpVecs[0];
  89059. var mesh = this.object;
  89060. if (mesh.rotationQuaternion) {
  89061. if (adjustRotation) {
  89062. var tempQuat = PhysicsImpostor._tmpQuat;
  89063. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  89064. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  89065. }
  89066. else {
  89067. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  89068. }
  89069. }
  89070. tempVec.x = 0;
  89071. tempVec.y = 0;
  89072. tempVec.z = 0;
  89073. if (jointPivot) {
  89074. tempVec.x = jointPivot.x;
  89075. tempVec.y = jointPivot.y;
  89076. tempVec.z = jointPivot.z;
  89077. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  89078. if (distToJoint === undefined || distToJoint === null) {
  89079. distToJoint = jointPivot.length();
  89080. }
  89081. tempVec.x *= distToJoint;
  89082. tempVec.y *= distToJoint;
  89083. tempVec.z *= distToJoint;
  89084. }
  89085. if (bone.getParent()) {
  89086. tempVec.addInPlace(mesh.getAbsolutePosition());
  89087. bone.setAbsolutePosition(tempVec, boneMesh);
  89088. }
  89089. else {
  89090. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  89091. boneMesh.position.x -= tempVec.x;
  89092. boneMesh.position.y -= tempVec.y;
  89093. boneMesh.position.z -= tempVec.z;
  89094. }
  89095. };
  89096. /**
  89097. * Sync impostor to a bone
  89098. * @param bone The bone that the impostor will be synced to.
  89099. * @param boneMesh The mesh that the bone is influencing.
  89100. * @param jointPivot The pivot of the joint / bone in local space.
  89101. * @param distToJoint Optional distance from the impostor to the joint.
  89102. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  89103. * @param boneAxis Optional vector3 axis the bone is aligned with
  89104. */
  89105. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  89106. var mesh = this.object;
  89107. if (mesh.rotationQuaternion) {
  89108. if (adjustRotation) {
  89109. var tempQuat = PhysicsImpostor._tmpQuat;
  89110. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  89111. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  89112. }
  89113. else {
  89114. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  89115. }
  89116. }
  89117. var pos = PhysicsImpostor._tmpVecs[0];
  89118. var boneDir = PhysicsImpostor._tmpVecs[1];
  89119. if (!boneAxis) {
  89120. boneAxis = PhysicsImpostor._tmpVecs[2];
  89121. boneAxis.x = 0;
  89122. boneAxis.y = 1;
  89123. boneAxis.z = 0;
  89124. }
  89125. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  89126. bone.getAbsolutePositionToRef(boneMesh, pos);
  89127. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  89128. distToJoint = jointPivot.length();
  89129. }
  89130. if (distToJoint !== undefined && distToJoint !== null) {
  89131. pos.x += boneDir.x * distToJoint;
  89132. pos.y += boneDir.y * distToJoint;
  89133. pos.z += boneDir.z * distToJoint;
  89134. }
  89135. mesh.setAbsolutePosition(pos);
  89136. };
  89137. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  89138. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  89139. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89140. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  89141. //Impostor types
  89142. PhysicsImpostor.NoImpostor = 0;
  89143. PhysicsImpostor.SphereImpostor = 1;
  89144. PhysicsImpostor.BoxImpostor = 2;
  89145. PhysicsImpostor.PlaneImpostor = 3;
  89146. PhysicsImpostor.MeshImpostor = 4;
  89147. PhysicsImpostor.CylinderImpostor = 7;
  89148. PhysicsImpostor.ParticleImpostor = 8;
  89149. PhysicsImpostor.HeightmapImpostor = 9;
  89150. return PhysicsImpostor;
  89151. }());
  89152. BABYLON.PhysicsImpostor = PhysicsImpostor;
  89153. })(BABYLON || (BABYLON = {}));
  89154. //# sourceMappingURL=babylon.physicsImpostor.js.map
  89155. var BABYLON;
  89156. (function (BABYLON) {
  89157. /**
  89158. * Class used to control physics engine
  89159. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  89160. */
  89161. var PhysicsEngine = /** @class */ (function () {
  89162. /**
  89163. * Creates a new Physics Engine
  89164. * @param gravity defines the gravity vector used by the simulation
  89165. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  89166. */
  89167. function PhysicsEngine(gravity, _physicsPlugin) {
  89168. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  89169. this._physicsPlugin = _physicsPlugin;
  89170. this._impostors = [];
  89171. this._joints = [];
  89172. if (!this._physicsPlugin.isSupported()) {
  89173. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  89174. + "Please make sure it is included.");
  89175. }
  89176. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  89177. this.setGravity(gravity);
  89178. this.setTimeStep();
  89179. }
  89180. /**
  89181. * Sets the gravity vector used by the simulation
  89182. * @param gravity defines the gravity vector to use
  89183. */
  89184. PhysicsEngine.prototype.setGravity = function (gravity) {
  89185. this.gravity = gravity;
  89186. this._physicsPlugin.setGravity(this.gravity);
  89187. };
  89188. /**
  89189. * Set the time step of the physics engine.
  89190. * Default is 1/60.
  89191. * To slow it down, enter 1/600 for example.
  89192. * To speed it up, 1/30
  89193. * @param newTimeStep defines the new timestep to apply to this world.
  89194. */
  89195. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  89196. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  89197. this._physicsPlugin.setTimeStep(newTimeStep);
  89198. };
  89199. /**
  89200. * Get the time step of the physics engine.
  89201. * @returns the current time step
  89202. */
  89203. PhysicsEngine.prototype.getTimeStep = function () {
  89204. return this._physicsPlugin.getTimeStep();
  89205. };
  89206. /**
  89207. * Release all resources
  89208. */
  89209. PhysicsEngine.prototype.dispose = function () {
  89210. this._impostors.forEach(function (impostor) {
  89211. impostor.dispose();
  89212. });
  89213. this._physicsPlugin.dispose();
  89214. };
  89215. /**
  89216. * Gets the name of the current physics plugin
  89217. * @returns the name of the plugin
  89218. */
  89219. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  89220. return this._physicsPlugin.name;
  89221. };
  89222. /**
  89223. * Adding a new impostor for the impostor tracking.
  89224. * This will be done by the impostor itself.
  89225. * @param impostor the impostor to add
  89226. */
  89227. PhysicsEngine.prototype.addImpostor = function (impostor) {
  89228. impostor.uniqueId = this._impostors.push(impostor);
  89229. //if no parent, generate the body
  89230. if (!impostor.parent) {
  89231. this._physicsPlugin.generatePhysicsBody(impostor);
  89232. }
  89233. };
  89234. /**
  89235. * Remove an impostor from the engine.
  89236. * This impostor and its mesh will not longer be updated by the physics engine.
  89237. * @param impostor the impostor to remove
  89238. */
  89239. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  89240. var index = this._impostors.indexOf(impostor);
  89241. if (index > -1) {
  89242. var removed = this._impostors.splice(index, 1);
  89243. //Is it needed?
  89244. if (removed.length) {
  89245. //this will also remove it from the world.
  89246. removed[0].physicsBody = null;
  89247. }
  89248. }
  89249. };
  89250. /**
  89251. * Add a joint to the physics engine
  89252. * @param mainImpostor defines the main impostor to which the joint is added.
  89253. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  89254. * @param joint defines the joint that will connect both impostors.
  89255. */
  89256. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  89257. var impostorJoint = {
  89258. mainImpostor: mainImpostor,
  89259. connectedImpostor: connectedImpostor,
  89260. joint: joint
  89261. };
  89262. joint.physicsPlugin = this._physicsPlugin;
  89263. this._joints.push(impostorJoint);
  89264. this._physicsPlugin.generateJoint(impostorJoint);
  89265. };
  89266. /**
  89267. * Removes a joint from the simulation
  89268. * @param mainImpostor defines the impostor used with the joint
  89269. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  89270. * @param joint defines the joint to remove
  89271. */
  89272. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  89273. var matchingJoints = this._joints.filter(function (impostorJoint) {
  89274. return (impostorJoint.connectedImpostor === connectedImpostor
  89275. && impostorJoint.joint === joint
  89276. && impostorJoint.mainImpostor === mainImpostor);
  89277. });
  89278. if (matchingJoints.length) {
  89279. this._physicsPlugin.removeJoint(matchingJoints[0]);
  89280. //TODO remove it from the list as well
  89281. }
  89282. };
  89283. /**
  89284. * Called by the scene. No need to call it.
  89285. * @param delta defines the timespam between frames
  89286. */
  89287. PhysicsEngine.prototype._step = function (delta) {
  89288. var _this = this;
  89289. //check if any mesh has no body / requires an update
  89290. this._impostors.forEach(function (impostor) {
  89291. if (impostor.isBodyInitRequired()) {
  89292. _this._physicsPlugin.generatePhysicsBody(impostor);
  89293. }
  89294. });
  89295. if (delta > 0.1) {
  89296. delta = 0.1;
  89297. }
  89298. else if (delta <= 0) {
  89299. delta = 1.0 / 60.0;
  89300. }
  89301. this._physicsPlugin.executeStep(delta, this._impostors);
  89302. };
  89303. /**
  89304. * Gets the current plugin used to run the simulation
  89305. * @returns current plugin
  89306. */
  89307. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  89308. return this._physicsPlugin;
  89309. };
  89310. /**
  89311. * Gets the list of physic impostors
  89312. * @returns an array of PhysicsImpostor
  89313. */
  89314. PhysicsEngine.prototype.getImpostors = function () {
  89315. return this._impostors;
  89316. };
  89317. /**
  89318. * Gets the impostor for a physics enabled object
  89319. * @param object defines the object impersonated by the impostor
  89320. * @returns the PhysicsImpostor or null if not found
  89321. */
  89322. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  89323. for (var i = 0; i < this._impostors.length; ++i) {
  89324. if (this._impostors[i].object === object) {
  89325. return this._impostors[i];
  89326. }
  89327. }
  89328. return null;
  89329. };
  89330. /**
  89331. * Gets the impostor for a physics body object
  89332. * @param body defines physics body used by the impostor
  89333. * @returns the PhysicsImpostor or null if not found
  89334. */
  89335. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  89336. for (var i = 0; i < this._impostors.length; ++i) {
  89337. if (this._impostors[i].physicsBody === body) {
  89338. return this._impostors[i];
  89339. }
  89340. }
  89341. return null;
  89342. };
  89343. /**
  89344. * Global value used to control the smallest number supported by the simulation
  89345. */
  89346. PhysicsEngine.Epsilon = 0.001;
  89347. return PhysicsEngine;
  89348. }());
  89349. BABYLON.PhysicsEngine = PhysicsEngine;
  89350. })(BABYLON || (BABYLON = {}));
  89351. //# sourceMappingURL=babylon.physicsEngine.js.map
  89352. var BABYLON;
  89353. (function (BABYLON) {
  89354. var PhysicsHelper = /** @class */ (function () {
  89355. function PhysicsHelper(scene) {
  89356. this._scene = scene;
  89357. this._physicsEngine = this._scene.getPhysicsEngine();
  89358. if (!this._physicsEngine) {
  89359. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  89360. }
  89361. }
  89362. /**
  89363. * @param {Vector3} origin the origin of the explosion
  89364. * @param {number} radius the explosion radius
  89365. * @param {number} strength the explosion strength
  89366. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89367. */
  89368. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  89369. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89370. if (!this._physicsEngine) {
  89371. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  89372. return null;
  89373. }
  89374. var impostors = this._physicsEngine.getImpostors();
  89375. if (impostors.length === 0) {
  89376. return null;
  89377. }
  89378. var event = new PhysicsRadialExplosionEvent(this._scene);
  89379. impostors.forEach(function (impostor) {
  89380. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89381. if (!impostorForceAndContactPoint) {
  89382. return;
  89383. }
  89384. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89385. });
  89386. event.dispose(false);
  89387. return event;
  89388. };
  89389. /**
  89390. * @param {Vector3} origin the origin of the explosion
  89391. * @param {number} radius the explosion radius
  89392. * @param {number} strength the explosion strength
  89393. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89394. */
  89395. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  89396. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89397. if (!this._physicsEngine) {
  89398. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89399. return null;
  89400. }
  89401. var impostors = this._physicsEngine.getImpostors();
  89402. if (impostors.length === 0) {
  89403. return null;
  89404. }
  89405. var event = new PhysicsRadialExplosionEvent(this._scene);
  89406. impostors.forEach(function (impostor) {
  89407. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89408. if (!impostorForceAndContactPoint) {
  89409. return;
  89410. }
  89411. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89412. });
  89413. event.dispose(false);
  89414. return event;
  89415. };
  89416. /**
  89417. * @param {Vector3} origin the origin of the explosion
  89418. * @param {number} radius the explosion radius
  89419. * @param {number} strength the explosion strength
  89420. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89421. */
  89422. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  89423. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89424. if (!this._physicsEngine) {
  89425. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89426. return null;
  89427. }
  89428. var impostors = this._physicsEngine.getImpostors();
  89429. if (impostors.length === 0) {
  89430. return null;
  89431. }
  89432. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  89433. event.dispose(false);
  89434. return event;
  89435. };
  89436. /**
  89437. * @param {Vector3} origin the origin of the updraft
  89438. * @param {number} radius the radius of the updraft
  89439. * @param {number} strength the strength of the updraft
  89440. * @param {number} height the height of the updraft
  89441. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  89442. */
  89443. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  89444. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  89445. if (!this._physicsEngine) {
  89446. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89447. return null;
  89448. }
  89449. if (this._physicsEngine.getImpostors().length === 0) {
  89450. return null;
  89451. }
  89452. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  89453. event.dispose(false);
  89454. return event;
  89455. };
  89456. /**
  89457. * @param {Vector3} origin the of the vortex
  89458. * @param {number} radius the radius of the vortex
  89459. * @param {number} strength the strength of the vortex
  89460. * @param {number} height the height of the vortex
  89461. */
  89462. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  89463. if (!this._physicsEngine) {
  89464. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89465. return null;
  89466. }
  89467. if (this._physicsEngine.getImpostors().length === 0) {
  89468. return null;
  89469. }
  89470. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  89471. event.dispose(false);
  89472. return event;
  89473. };
  89474. return PhysicsHelper;
  89475. }());
  89476. BABYLON.PhysicsHelper = PhysicsHelper;
  89477. /***** Radial explosion *****/
  89478. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  89479. function PhysicsRadialExplosionEvent(scene) {
  89480. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  89481. this._rays = [];
  89482. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  89483. this._scene = scene;
  89484. }
  89485. /**
  89486. * Returns the data related to the radial explosion event (sphere & rays).
  89487. * @returns {PhysicsRadialExplosionEventData}
  89488. */
  89489. PhysicsRadialExplosionEvent.prototype.getData = function () {
  89490. this._dataFetched = true;
  89491. return {
  89492. sphere: this._sphere,
  89493. rays: this._rays,
  89494. };
  89495. };
  89496. /**
  89497. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  89498. * @param impostor
  89499. * @param {Vector3} origin the origin of the explosion
  89500. * @param {number} radius the explosion radius
  89501. * @param {number} strength the explosion strength
  89502. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  89503. * @returns {Nullable<PhysicsForceAndContactPoint>}
  89504. */
  89505. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  89506. if (impostor.mass === 0) {
  89507. return null;
  89508. }
  89509. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  89510. return null;
  89511. }
  89512. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89513. return null;
  89514. }
  89515. var impostorObjectCenter = impostor.getObjectCenter();
  89516. var direction = impostorObjectCenter.subtract(origin);
  89517. var ray = new BABYLON.Ray(origin, direction, radius);
  89518. this._rays.push(ray);
  89519. var hit = ray.intersectsMesh(impostor.object);
  89520. var contactPoint = hit.pickedPoint;
  89521. if (!contactPoint) {
  89522. return null;
  89523. }
  89524. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  89525. if (distanceFromOrigin > radius) {
  89526. return null;
  89527. }
  89528. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  89529. ? strength
  89530. : strength * (1 - (distanceFromOrigin / radius));
  89531. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89532. return { force: force, contactPoint: contactPoint };
  89533. };
  89534. /**
  89535. * Disposes the sphere.
  89536. * @param {bolean} force
  89537. */
  89538. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  89539. var _this = this;
  89540. if (force === void 0) { force = true; }
  89541. if (force) {
  89542. this._sphere.dispose();
  89543. }
  89544. else {
  89545. setTimeout(function () {
  89546. if (!_this._dataFetched) {
  89547. _this._sphere.dispose();
  89548. }
  89549. }, 0);
  89550. }
  89551. };
  89552. /*** Helpers ***/
  89553. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  89554. if (!this._sphere) {
  89555. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  89556. this._sphere.isVisible = false;
  89557. }
  89558. };
  89559. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  89560. var impostorObject = impostor.object;
  89561. this._prepareSphere();
  89562. this._sphere.position = origin;
  89563. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  89564. this._sphere._updateBoundingInfo();
  89565. this._sphere.computeWorldMatrix(true);
  89566. return this._sphere.intersectsMesh(impostorObject, true);
  89567. };
  89568. return PhysicsRadialExplosionEvent;
  89569. }());
  89570. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  89571. /***** Gravitational Field *****/
  89572. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  89573. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  89574. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89575. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89576. this._physicsHelper = physicsHelper;
  89577. this._scene = scene;
  89578. this._origin = origin;
  89579. this._radius = radius;
  89580. this._strength = strength;
  89581. this._falloff = falloff;
  89582. this._tickCallback = this._tick.bind(this);
  89583. }
  89584. /**
  89585. * Returns the data related to the gravitational field event (sphere).
  89586. * @returns {PhysicsGravitationalFieldEventData}
  89587. */
  89588. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  89589. this._dataFetched = true;
  89590. return {
  89591. sphere: this._sphere,
  89592. };
  89593. };
  89594. /**
  89595. * Enables the gravitational field.
  89596. */
  89597. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  89598. this._tickCallback.call(this);
  89599. this._scene.registerBeforeRender(this._tickCallback);
  89600. };
  89601. /**
  89602. * Disables the gravitational field.
  89603. */
  89604. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  89605. this._scene.unregisterBeforeRender(this._tickCallback);
  89606. };
  89607. /**
  89608. * Disposes the sphere.
  89609. * @param {bolean} force
  89610. */
  89611. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  89612. var _this = this;
  89613. if (force === void 0) { force = true; }
  89614. if (force) {
  89615. this._sphere.dispose();
  89616. }
  89617. else {
  89618. setTimeout(function () {
  89619. if (!_this._dataFetched) {
  89620. _this._sphere.dispose();
  89621. }
  89622. }, 0);
  89623. }
  89624. };
  89625. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  89626. // Since the params won't change, we fetch the event only once
  89627. if (this._sphere) {
  89628. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89629. }
  89630. else {
  89631. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89632. if (radialExplosionEvent) {
  89633. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  89634. }
  89635. }
  89636. };
  89637. return PhysicsGravitationalFieldEvent;
  89638. }());
  89639. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  89640. /***** Updraft *****/
  89641. var PhysicsUpdraftEvent = /** @class */ (function () {
  89642. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  89643. this._scene = _scene;
  89644. this._origin = _origin;
  89645. this._radius = _radius;
  89646. this._strength = _strength;
  89647. this._height = _height;
  89648. this._updraftMode = _updraftMode;
  89649. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89650. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  89651. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89652. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89653. this._physicsEngine = this._scene.getPhysicsEngine();
  89654. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89655. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89656. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89657. this._originDirection = this._origin.subtract(this._originTop).normalize();
  89658. }
  89659. this._tickCallback = this._tick.bind(this);
  89660. }
  89661. /**
  89662. * Returns the data related to the updraft event (cylinder).
  89663. * @returns {PhysicsUpdraftEventData}
  89664. */
  89665. PhysicsUpdraftEvent.prototype.getData = function () {
  89666. this._dataFetched = true;
  89667. return {
  89668. cylinder: this._cylinder,
  89669. };
  89670. };
  89671. /**
  89672. * Enables the updraft.
  89673. */
  89674. PhysicsUpdraftEvent.prototype.enable = function () {
  89675. this._tickCallback.call(this);
  89676. this._scene.registerBeforeRender(this._tickCallback);
  89677. };
  89678. /**
  89679. * Disables the cortex.
  89680. */
  89681. PhysicsUpdraftEvent.prototype.disable = function () {
  89682. this._scene.unregisterBeforeRender(this._tickCallback);
  89683. };
  89684. /**
  89685. * Disposes the sphere.
  89686. * @param {bolean} force
  89687. */
  89688. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  89689. var _this = this;
  89690. if (force === void 0) { force = true; }
  89691. if (force) {
  89692. this._cylinder.dispose();
  89693. }
  89694. else {
  89695. setTimeout(function () {
  89696. if (!_this._dataFetched) {
  89697. _this._cylinder.dispose();
  89698. }
  89699. }, 0);
  89700. }
  89701. };
  89702. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89703. if (impostor.mass === 0) {
  89704. return null;
  89705. }
  89706. if (!this._intersectsWithCylinder(impostor)) {
  89707. return null;
  89708. }
  89709. var impostorObjectCenter = impostor.getObjectCenter();
  89710. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89711. var direction = this._originDirection;
  89712. }
  89713. else {
  89714. var direction = impostorObjectCenter.subtract(this._originTop);
  89715. }
  89716. var multiplier = this._strength * -1;
  89717. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89718. return { force: force, contactPoint: impostorObjectCenter };
  89719. };
  89720. PhysicsUpdraftEvent.prototype._tick = function () {
  89721. var _this = this;
  89722. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89723. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89724. if (!impostorForceAndContactPoint) {
  89725. return;
  89726. }
  89727. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89728. });
  89729. };
  89730. /*** Helpers ***/
  89731. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  89732. if (!this._cylinder) {
  89733. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  89734. height: this._height,
  89735. diameter: this._radius * 2,
  89736. }, this._scene);
  89737. this._cylinder.isVisible = false;
  89738. }
  89739. };
  89740. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  89741. var impostorObject = impostor.object;
  89742. this._prepareCylinder();
  89743. this._cylinder.position = this._cylinderPosition;
  89744. return this._cylinder.intersectsMesh(impostorObject, true);
  89745. };
  89746. return PhysicsUpdraftEvent;
  89747. }());
  89748. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  89749. /***** Vortex *****/
  89750. var PhysicsVortexEvent = /** @class */ (function () {
  89751. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  89752. this._scene = _scene;
  89753. this._origin = _origin;
  89754. this._radius = _radius;
  89755. this._strength = _strength;
  89756. this._height = _height;
  89757. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89758. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  89759. this._updraftMultiplier = 0.02;
  89760. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89761. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89762. this._physicsEngine = this._scene.getPhysicsEngine();
  89763. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89764. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89765. this._tickCallback = this._tick.bind(this);
  89766. }
  89767. /**
  89768. * Returns the data related to the vortex event (cylinder).
  89769. * @returns {PhysicsVortexEventData}
  89770. */
  89771. PhysicsVortexEvent.prototype.getData = function () {
  89772. this._dataFetched = true;
  89773. return {
  89774. cylinder: this._cylinder,
  89775. };
  89776. };
  89777. /**
  89778. * Enables the vortex.
  89779. */
  89780. PhysicsVortexEvent.prototype.enable = function () {
  89781. this._tickCallback.call(this);
  89782. this._scene.registerBeforeRender(this._tickCallback);
  89783. };
  89784. /**
  89785. * Disables the cortex.
  89786. */
  89787. PhysicsVortexEvent.prototype.disable = function () {
  89788. this._scene.unregisterBeforeRender(this._tickCallback);
  89789. };
  89790. /**
  89791. * Disposes the sphere.
  89792. * @param {bolean} force
  89793. */
  89794. PhysicsVortexEvent.prototype.dispose = function (force) {
  89795. var _this = this;
  89796. if (force === void 0) { force = true; }
  89797. if (force) {
  89798. this._cylinder.dispose();
  89799. }
  89800. else {
  89801. setTimeout(function () {
  89802. if (!_this._dataFetched) {
  89803. _this._cylinder.dispose();
  89804. }
  89805. }, 0);
  89806. }
  89807. };
  89808. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89809. if (impostor.mass === 0) {
  89810. return null;
  89811. }
  89812. if (!this._intersectsWithCylinder(impostor)) {
  89813. return null;
  89814. }
  89815. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89816. return null;
  89817. }
  89818. var impostorObjectCenter = impostor.getObjectCenter();
  89819. 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)
  89820. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  89821. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  89822. var hit = ray.intersectsMesh(impostor.object);
  89823. var contactPoint = hit.pickedPoint;
  89824. if (!contactPoint) {
  89825. return null;
  89826. }
  89827. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  89828. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  89829. var directionToOrigin = contactPoint.normalize();
  89830. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89831. directionToOrigin = directionToOrigin.negate();
  89832. }
  89833. // TODO: find a more physically based solution
  89834. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89835. var forceX = directionToOrigin.x * this._strength / 8;
  89836. var forceY = directionToOrigin.y * this._updraftMultiplier;
  89837. var forceZ = directionToOrigin.z * this._strength / 8;
  89838. }
  89839. else {
  89840. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  89841. var forceY = this._originTop.y * this._updraftMultiplier;
  89842. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  89843. }
  89844. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  89845. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  89846. return { force: force, contactPoint: impostorObjectCenter };
  89847. };
  89848. PhysicsVortexEvent.prototype._tick = function () {
  89849. var _this = this;
  89850. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89851. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89852. if (!impostorForceAndContactPoint) {
  89853. return;
  89854. }
  89855. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89856. });
  89857. };
  89858. /*** Helpers ***/
  89859. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  89860. if (!this._cylinder) {
  89861. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  89862. height: this._height,
  89863. diameter: this._radius * 2,
  89864. }, this._scene);
  89865. this._cylinder.isVisible = false;
  89866. }
  89867. };
  89868. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  89869. var impostorObject = impostor.object;
  89870. this._prepareCylinder();
  89871. this._cylinder.position = this._cylinderPosition;
  89872. return this._cylinder.intersectsMesh(impostorObject, true);
  89873. };
  89874. return PhysicsVortexEvent;
  89875. }());
  89876. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  89877. /***** Enums *****/
  89878. /**
  89879. * The strenght of the force in correspondence to the distance of the affected object
  89880. */
  89881. var PhysicsRadialImpulseFalloff;
  89882. (function (PhysicsRadialImpulseFalloff) {
  89883. /** Defines that impulse is constant in strength across it's whole radius */
  89884. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  89885. /** DEfines that impulse gets weaker if it's further from the origin */
  89886. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  89887. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  89888. /**
  89889. * The strenght of the force in correspondence to the distance of the affected object
  89890. */
  89891. var PhysicsUpdraftMode;
  89892. (function (PhysicsUpdraftMode) {
  89893. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  89894. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  89895. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  89896. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  89897. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  89898. })(BABYLON || (BABYLON = {}));
  89899. //# sourceMappingURL=babylon.physicsHelper.js.map
  89900. var BABYLON;
  89901. (function (BABYLON) {
  89902. var CannonJSPlugin = /** @class */ (function () {
  89903. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  89904. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  89905. if (iterations === void 0) { iterations = 10; }
  89906. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  89907. this.name = "CannonJSPlugin";
  89908. this._physicsMaterials = new Array();
  89909. this._fixedTimeStep = 1 / 60;
  89910. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  89911. this.BJSCANNON = CANNON;
  89912. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  89913. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  89914. this._tmpPosition = BABYLON.Vector3.Zero();
  89915. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  89916. this._tmpUnityRotation = new BABYLON.Quaternion();
  89917. if (!this.isSupported()) {
  89918. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  89919. return;
  89920. }
  89921. this._extendNamespace();
  89922. this.world = new this.BJSCANNON.World();
  89923. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  89924. this.world.solver.iterations = iterations;
  89925. }
  89926. CannonJSPlugin.prototype.setGravity = function (gravity) {
  89927. this.world.gravity.copy(gravity);
  89928. };
  89929. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  89930. this._fixedTimeStep = timeStep;
  89931. };
  89932. CannonJSPlugin.prototype.getTimeStep = function () {
  89933. return this._fixedTimeStep;
  89934. };
  89935. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  89936. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  89937. };
  89938. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  89939. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89940. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89941. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  89942. };
  89943. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  89944. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89945. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89946. impostor.physicsBody.applyForce(impulse, worldPoint);
  89947. };
  89948. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  89949. //parent-child relationship. Does this impostor has a parent impostor?
  89950. if (impostor.parent) {
  89951. if (impostor.physicsBody) {
  89952. this.removePhysicsBody(impostor);
  89953. //TODO is that needed?
  89954. impostor.forceUpdate();
  89955. }
  89956. return;
  89957. }
  89958. //should a new body be created for this impostor?
  89959. if (impostor.isBodyInitRequired()) {
  89960. var shape = this._createShape(impostor);
  89961. //unregister events, if body is being changed
  89962. var oldBody = impostor.physicsBody;
  89963. if (oldBody) {
  89964. this.removePhysicsBody(impostor);
  89965. }
  89966. //create the body and material
  89967. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  89968. var bodyCreationObject = {
  89969. mass: impostor.getParam("mass"),
  89970. material: material
  89971. };
  89972. // A simple extend, in case native options were used.
  89973. var nativeOptions = impostor.getParam("nativeOptions");
  89974. for (var key in nativeOptions) {
  89975. if (nativeOptions.hasOwnProperty(key)) {
  89976. bodyCreationObject[key] = nativeOptions[key];
  89977. }
  89978. }
  89979. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  89980. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  89981. this.world.addEventListener("preStep", impostor.beforeStep);
  89982. this.world.addEventListener("postStep", impostor.afterStep);
  89983. impostor.physicsBody.addShape(shape);
  89984. this.world.add(impostor.physicsBody);
  89985. //try to keep the body moving in the right direction by taking old properties.
  89986. //Should be tested!
  89987. if (oldBody) {
  89988. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  89989. impostor.physicsBody[param].copy(oldBody[param]);
  89990. });
  89991. }
  89992. this._processChildMeshes(impostor);
  89993. }
  89994. //now update the body's transformation
  89995. this._updatePhysicsBodyTransformation(impostor);
  89996. };
  89997. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  89998. var _this = this;
  89999. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  90000. var currentRotation = mainImpostor.object.rotationQuaternion;
  90001. if (meshChildren.length) {
  90002. var processMesh = function (localPosition, mesh) {
  90003. if (!currentRotation || !mesh.rotationQuaternion) {
  90004. return;
  90005. }
  90006. var childImpostor = mesh.getPhysicsImpostor();
  90007. if (childImpostor) {
  90008. var parent = childImpostor.parent;
  90009. if (parent !== mainImpostor) {
  90010. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  90011. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  90012. if (childImpostor.physicsBody) {
  90013. _this.removePhysicsBody(childImpostor);
  90014. childImpostor.physicsBody = null;
  90015. }
  90016. childImpostor.parent = mainImpostor;
  90017. childImpostor.resetUpdateFlags();
  90018. 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));
  90019. //Add the mass of the children.
  90020. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  90021. }
  90022. }
  90023. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  90024. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  90025. };
  90026. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  90027. }
  90028. };
  90029. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90030. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  90031. this.world.removeEventListener("preStep", impostor.beforeStep);
  90032. this.world.removeEventListener("postStep", impostor.afterStep);
  90033. this.world.remove(impostor.physicsBody);
  90034. };
  90035. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90036. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90037. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90038. if (!mainBody || !connectedBody) {
  90039. return;
  90040. }
  90041. var constraint;
  90042. var jointData = impostorJoint.joint.jointData;
  90043. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  90044. var constraintData = {
  90045. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  90046. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  90047. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  90048. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  90049. maxForce: jointData.nativeParams.maxForce,
  90050. collideConnected: !!jointData.collision
  90051. };
  90052. switch (impostorJoint.joint.type) {
  90053. case BABYLON.PhysicsJoint.HingeJoint:
  90054. case BABYLON.PhysicsJoint.Hinge2Joint:
  90055. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  90056. break;
  90057. case BABYLON.PhysicsJoint.DistanceJoint:
  90058. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  90059. break;
  90060. case BABYLON.PhysicsJoint.SpringJoint:
  90061. var springData = jointData;
  90062. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  90063. restLength: springData.length,
  90064. stiffness: springData.stiffness,
  90065. damping: springData.damping,
  90066. localAnchorA: constraintData.pivotA,
  90067. localAnchorB: constraintData.pivotB
  90068. });
  90069. break;
  90070. case BABYLON.PhysicsJoint.LockJoint:
  90071. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  90072. break;
  90073. case BABYLON.PhysicsJoint.PointToPointJoint:
  90074. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90075. default:
  90076. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  90077. break;
  90078. }
  90079. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  90080. constraint.collideConnected = !!jointData.collision;
  90081. impostorJoint.joint.physicsJoint = constraint;
  90082. //don't add spring as constraint, as it is not one.
  90083. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  90084. this.world.addConstraint(constraint);
  90085. }
  90086. else {
  90087. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  90088. constraint.applyForce();
  90089. };
  90090. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  90091. }
  90092. };
  90093. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90094. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  90095. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  90096. }
  90097. else {
  90098. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  90099. }
  90100. };
  90101. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  90102. var index;
  90103. var mat;
  90104. for (index = 0; index < this._physicsMaterials.length; index++) {
  90105. mat = this._physicsMaterials[index];
  90106. if (mat.friction === friction && mat.restitution === restitution) {
  90107. return mat;
  90108. }
  90109. }
  90110. var currentMat = new this.BJSCANNON.Material(name);
  90111. currentMat.friction = friction;
  90112. currentMat.restitution = restitution;
  90113. this._physicsMaterials.push(currentMat);
  90114. return currentMat;
  90115. };
  90116. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  90117. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  90118. };
  90119. CannonJSPlugin.prototype._createShape = function (impostor) {
  90120. var object = impostor.object;
  90121. var returnValue;
  90122. var extendSize = impostor.getObjectExtendSize();
  90123. switch (impostor.type) {
  90124. case BABYLON.PhysicsImpostor.SphereImpostor:
  90125. var radiusX = extendSize.x;
  90126. var radiusY = extendSize.y;
  90127. var radiusZ = extendSize.z;
  90128. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  90129. break;
  90130. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  90131. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90132. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  90133. break;
  90134. case BABYLON.PhysicsImpostor.BoxImpostor:
  90135. var box = extendSize.scale(0.5);
  90136. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  90137. break;
  90138. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90139. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  90140. returnValue = new this.BJSCANNON.Plane();
  90141. break;
  90142. case BABYLON.PhysicsImpostor.MeshImpostor:
  90143. // should transform the vertex data to world coordinates!!
  90144. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  90145. var rawFaces = object.getIndices ? object.getIndices() : [];
  90146. if (!rawVerts)
  90147. return;
  90148. // get only scale! so the object could transform correctly.
  90149. var oldPosition = object.position.clone();
  90150. var oldRotation = object.rotation && object.rotation.clone();
  90151. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  90152. object.position.copyFromFloats(0, 0, 0);
  90153. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  90154. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  90155. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  90156. var transform = object.computeWorldMatrix(true);
  90157. // convert rawVerts to object space
  90158. var temp = new Array();
  90159. var index;
  90160. for (index = 0; index < rawVerts.length; index += 3) {
  90161. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  90162. }
  90163. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  90164. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  90165. //now set back the transformation!
  90166. object.position.copyFrom(oldPosition);
  90167. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  90168. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  90169. break;
  90170. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  90171. var oldPosition2 = object.position.clone();
  90172. var oldRotation2 = object.rotation && object.rotation.clone();
  90173. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  90174. object.position.copyFromFloats(0, 0, 0);
  90175. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  90176. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  90177. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  90178. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  90179. returnValue = this._createHeightmap(object);
  90180. object.position.copyFrom(oldPosition2);
  90181. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  90182. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  90183. object.computeWorldMatrix(true);
  90184. break;
  90185. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90186. returnValue = new this.BJSCANNON.Particle();
  90187. break;
  90188. }
  90189. return returnValue;
  90190. };
  90191. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  90192. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90193. var transform = object.computeWorldMatrix(true);
  90194. // convert rawVerts to object space
  90195. var temp = new Array();
  90196. var index;
  90197. for (index = 0; index < pos.length; index += 3) {
  90198. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  90199. }
  90200. pos = temp;
  90201. var matrix = new Array();
  90202. //For now pointDepth will not be used and will be automatically calculated.
  90203. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  90204. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  90205. var boundingInfo = object.getBoundingInfo();
  90206. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  90207. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  90208. var elementSize = dim * 2 / arraySize;
  90209. for (var i = 0; i < pos.length; i = i + 3) {
  90210. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  90211. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  90212. var y = -pos[i + 2] + minY;
  90213. if (!matrix[x]) {
  90214. matrix[x] = [];
  90215. }
  90216. if (!matrix[x][z]) {
  90217. matrix[x][z] = y;
  90218. }
  90219. matrix[x][z] = Math.max(y, matrix[x][z]);
  90220. }
  90221. for (var x = 0; x <= arraySize; ++x) {
  90222. if (!matrix[x]) {
  90223. var loc = 1;
  90224. while (!matrix[(x + loc) % arraySize]) {
  90225. loc++;
  90226. }
  90227. matrix[x] = matrix[(x + loc) % arraySize].slice();
  90228. //console.log("missing x", x);
  90229. }
  90230. for (var z = 0; z <= arraySize; ++z) {
  90231. if (!matrix[x][z]) {
  90232. var loc = 1;
  90233. var newValue;
  90234. while (newValue === undefined) {
  90235. newValue = matrix[x][(z + loc++) % arraySize];
  90236. }
  90237. matrix[x][z] = newValue;
  90238. }
  90239. }
  90240. }
  90241. var shape = new this.BJSCANNON.Heightfield(matrix, {
  90242. elementSize: elementSize
  90243. });
  90244. //For future reference, needed for body transformation
  90245. shape.minY = minY;
  90246. return shape;
  90247. };
  90248. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  90249. var object = impostor.object;
  90250. //make sure it is updated...
  90251. object.computeWorldMatrix && object.computeWorldMatrix(true);
  90252. // The delta between the mesh position and the mesh bounding box center
  90253. var bInfo = object.getBoundingInfo();
  90254. if (!bInfo)
  90255. return;
  90256. var center = impostor.getObjectCenter();
  90257. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  90258. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  90259. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  90260. this._tmpPosition.copyFrom(center);
  90261. var quaternion = object.rotationQuaternion;
  90262. if (!quaternion) {
  90263. return;
  90264. }
  90265. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  90266. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  90267. //-90 DEG in X, precalculated
  90268. quaternion = quaternion.multiply(this._minus90X);
  90269. //Invert! (Precalculated, 90 deg in X)
  90270. //No need to clone. this will never change.
  90271. impostor.setDeltaRotation(this._plus90X);
  90272. }
  90273. //If it is a heightfield, if should be centered.
  90274. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  90275. var mesh = object;
  90276. var boundingInfo = mesh.getBoundingInfo();
  90277. //calculate the correct body position:
  90278. var rotationQuaternion = mesh.rotationQuaternion;
  90279. mesh.rotationQuaternion = this._tmpUnityRotation;
  90280. mesh.computeWorldMatrix(true);
  90281. //get original center with no rotation
  90282. var c = center.clone();
  90283. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  90284. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  90285. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  90286. mesh.setPreTransformMatrix(p);
  90287. mesh.computeWorldMatrix(true);
  90288. //calculate the translation
  90289. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  90290. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  90291. //add it inverted to the delta
  90292. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  90293. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  90294. //rotation is back
  90295. mesh.rotationQuaternion = rotationQuaternion;
  90296. mesh.setPreTransformMatrix(oldPivot);
  90297. mesh.computeWorldMatrix(true);
  90298. }
  90299. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  90300. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  90301. //this._tmpPosition.copyFrom(object.position);
  90302. }
  90303. impostor.setDeltaPosition(this._tmpDeltaPosition);
  90304. //Now update the impostor object
  90305. impostor.physicsBody.position.copy(this._tmpPosition);
  90306. impostor.physicsBody.quaternion.copy(quaternion);
  90307. };
  90308. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90309. impostor.object.position.copyFrom(impostor.physicsBody.position);
  90310. if (impostor.object.rotationQuaternion) {
  90311. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  90312. }
  90313. };
  90314. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90315. impostor.physicsBody.position.copy(newPosition);
  90316. impostor.physicsBody.quaternion.copy(newRotation);
  90317. };
  90318. CannonJSPlugin.prototype.isSupported = function () {
  90319. return this.BJSCANNON !== undefined;
  90320. };
  90321. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90322. impostor.physicsBody.velocity.copy(velocity);
  90323. };
  90324. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90325. impostor.physicsBody.angularVelocity.copy(velocity);
  90326. };
  90327. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90328. var v = impostor.physicsBody.velocity;
  90329. if (!v) {
  90330. return null;
  90331. }
  90332. return new BABYLON.Vector3(v.x, v.y, v.z);
  90333. };
  90334. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90335. var v = impostor.physicsBody.angularVelocity;
  90336. if (!v) {
  90337. return null;
  90338. }
  90339. return new BABYLON.Vector3(v.x, v.y, v.z);
  90340. };
  90341. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90342. impostor.physicsBody.mass = mass;
  90343. impostor.physicsBody.updateMassProperties();
  90344. };
  90345. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  90346. return impostor.physicsBody.mass;
  90347. };
  90348. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  90349. return impostor.physicsBody.material.friction;
  90350. };
  90351. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90352. impostor.physicsBody.material.friction = friction;
  90353. };
  90354. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90355. return impostor.physicsBody.material.restitution;
  90356. };
  90357. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90358. impostor.physicsBody.material.restitution = restitution;
  90359. };
  90360. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  90361. impostor.physicsBody.sleep();
  90362. };
  90363. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  90364. impostor.physicsBody.wakeUp();
  90365. };
  90366. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90367. joint.physicsJoint.distance = maxDistance;
  90368. };
  90369. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90370. // if (!motorIndex) {
  90371. // joint.physicsJoint.enableMotor();
  90372. // }
  90373. // }
  90374. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90375. // if (!motorIndex) {
  90376. // joint.physicsJoint.disableMotor();
  90377. // }
  90378. // }
  90379. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90380. if (!motorIndex) {
  90381. joint.physicsJoint.enableMotor();
  90382. joint.physicsJoint.setMotorSpeed(speed);
  90383. if (maxForce) {
  90384. this.setLimit(joint, maxForce);
  90385. }
  90386. }
  90387. };
  90388. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  90389. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  90390. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  90391. };
  90392. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90393. var body = impostor.physicsBody;
  90394. mesh.position.x = body.position.x;
  90395. mesh.position.y = body.position.y;
  90396. mesh.position.z = body.position.z;
  90397. if (mesh.rotationQuaternion) {
  90398. mesh.rotationQuaternion.x = body.quaternion.x;
  90399. mesh.rotationQuaternion.y = body.quaternion.y;
  90400. mesh.rotationQuaternion.z = body.quaternion.z;
  90401. mesh.rotationQuaternion.w = body.quaternion.w;
  90402. }
  90403. };
  90404. CannonJSPlugin.prototype.getRadius = function (impostor) {
  90405. var shape = impostor.physicsBody.shapes[0];
  90406. return shape.boundingSphereRadius;
  90407. };
  90408. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90409. var shape = impostor.physicsBody.shapes[0];
  90410. result.x = shape.halfExtents.x * 2;
  90411. result.y = shape.halfExtents.y * 2;
  90412. result.z = shape.halfExtents.z * 2;
  90413. };
  90414. CannonJSPlugin.prototype.dispose = function () {
  90415. };
  90416. CannonJSPlugin.prototype._extendNamespace = function () {
  90417. //this will force cannon to execute at least one step when using interpolation
  90418. var step_tmp1 = new this.BJSCANNON.Vec3();
  90419. var Engine = this.BJSCANNON;
  90420. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  90421. maxSubSteps = maxSubSteps || 10;
  90422. timeSinceLastCalled = timeSinceLastCalled || 0;
  90423. if (timeSinceLastCalled === 0) {
  90424. this.internalStep(dt);
  90425. this.time += dt;
  90426. }
  90427. else {
  90428. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  90429. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  90430. var t0 = performance.now();
  90431. for (var i = 0; i !== internalSteps; i++) {
  90432. this.internalStep(dt);
  90433. if (performance.now() - t0 > dt * 1000) {
  90434. break;
  90435. }
  90436. }
  90437. this.time += timeSinceLastCalled;
  90438. var h = this.time % dt;
  90439. var h_div_dt = h / dt;
  90440. var interpvelo = step_tmp1;
  90441. var bodies = this.bodies;
  90442. for (var j = 0; j !== bodies.length; j++) {
  90443. var b = bodies[j];
  90444. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  90445. b.position.vsub(b.previousPosition, interpvelo);
  90446. interpvelo.scale(h_div_dt, interpvelo);
  90447. b.position.vadd(interpvelo, b.interpolatedPosition);
  90448. }
  90449. else {
  90450. b.interpolatedPosition.copy(b.position);
  90451. b.interpolatedQuaternion.copy(b.quaternion);
  90452. }
  90453. }
  90454. }
  90455. };
  90456. };
  90457. return CannonJSPlugin;
  90458. }());
  90459. BABYLON.CannonJSPlugin = CannonJSPlugin;
  90460. })(BABYLON || (BABYLON = {}));
  90461. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  90462. var BABYLON;
  90463. (function (BABYLON) {
  90464. var OimoJSPlugin = /** @class */ (function () {
  90465. function OimoJSPlugin(iterations) {
  90466. this.name = "OimoJSPlugin";
  90467. this._tmpImpostorsArray = [];
  90468. this._tmpPositionVector = BABYLON.Vector3.Zero();
  90469. this.BJSOIMO = OIMO;
  90470. this.world = new this.BJSOIMO.World({
  90471. iterations: iterations
  90472. });
  90473. this.world.clear();
  90474. }
  90475. OimoJSPlugin.prototype.setGravity = function (gravity) {
  90476. this.world.gravity.copy(gravity);
  90477. };
  90478. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  90479. this.world.timeStep = timeStep;
  90480. };
  90481. OimoJSPlugin.prototype.getTimeStep = function () {
  90482. return this.world.timeStep;
  90483. };
  90484. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  90485. var _this = this;
  90486. impostors.forEach(function (impostor) {
  90487. impostor.beforeStep();
  90488. });
  90489. this.world.step();
  90490. impostors.forEach(function (impostor) {
  90491. impostor.afterStep();
  90492. //update the ordered impostors array
  90493. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  90494. });
  90495. //check for collisions
  90496. var contact = this.world.contacts;
  90497. while (contact !== null) {
  90498. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  90499. contact = contact.next;
  90500. continue;
  90501. }
  90502. //is this body colliding with any other? get the impostor
  90503. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  90504. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  90505. if (!mainImpostor || !collidingImpostor) {
  90506. contact = contact.next;
  90507. continue;
  90508. }
  90509. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  90510. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  90511. contact = contact.next;
  90512. }
  90513. };
  90514. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90515. var mass = impostor.physicsBody.mass;
  90516. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  90517. };
  90518. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90519. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  90520. this.applyImpulse(impostor, force, contactPoint);
  90521. };
  90522. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90523. var _this = this;
  90524. //parent-child relationship. Does this impostor has a parent impostor?
  90525. if (impostor.parent) {
  90526. if (impostor.physicsBody) {
  90527. this.removePhysicsBody(impostor);
  90528. //TODO is that needed?
  90529. impostor.forceUpdate();
  90530. }
  90531. return;
  90532. }
  90533. if (impostor.isBodyInitRequired()) {
  90534. var bodyConfig = {
  90535. name: impostor.uniqueId,
  90536. //Oimo must have mass, also for static objects.
  90537. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  90538. size: [],
  90539. type: [],
  90540. pos: [],
  90541. posShape: [],
  90542. rot: [],
  90543. rotShape: [],
  90544. move: impostor.getParam("mass") !== 0,
  90545. density: impostor.getParam("mass"),
  90546. friction: impostor.getParam("friction"),
  90547. restitution: impostor.getParam("restitution"),
  90548. //Supporting older versions of Oimo
  90549. world: this.world
  90550. };
  90551. var impostors = [impostor];
  90552. var addToArray = function (parent) {
  90553. if (!parent.getChildMeshes)
  90554. return;
  90555. parent.getChildMeshes().forEach(function (m) {
  90556. if (m.physicsImpostor) {
  90557. impostors.push(m.physicsImpostor);
  90558. //m.physicsImpostor._init();
  90559. }
  90560. });
  90561. };
  90562. addToArray(impostor.object);
  90563. var checkWithEpsilon_1 = function (value) {
  90564. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  90565. };
  90566. var globalQuaternion_1 = new BABYLON.Quaternion();
  90567. impostors.forEach(function (i) {
  90568. if (!i.object.rotationQuaternion) {
  90569. return;
  90570. }
  90571. //get the correct bounding box
  90572. var oldQuaternion = i.object.rotationQuaternion;
  90573. globalQuaternion_1 = oldQuaternion.clone();
  90574. var rot = oldQuaternion.toEulerAngles();
  90575. var extendSize = i.getObjectExtendSize();
  90576. var radToDeg = 57.295779513082320876;
  90577. if (i === impostor) {
  90578. var center = impostor.getObjectCenter();
  90579. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  90580. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  90581. //Can also use Array.prototype.push.apply
  90582. bodyConfig.pos.push(center.x);
  90583. bodyConfig.pos.push(center.y);
  90584. bodyConfig.pos.push(center.z);
  90585. bodyConfig.posShape.push(0, 0, 0);
  90586. //tmp solution
  90587. bodyConfig.rot.push(0);
  90588. bodyConfig.rot.push(0);
  90589. bodyConfig.rot.push(0);
  90590. bodyConfig.rotShape.push(0, 0, 0);
  90591. }
  90592. else {
  90593. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  90594. bodyConfig.posShape.push(localPosition.x);
  90595. bodyConfig.posShape.push(localPosition.y);
  90596. bodyConfig.posShape.push(localPosition.z);
  90597. bodyConfig.pos.push(0, 0, 0);
  90598. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  90599. bodyConfig.rot.push(0);
  90600. bodyConfig.rot.push(0);
  90601. bodyConfig.rot.push(0);
  90602. bodyConfig.rotShape.push(rot.x * radToDeg);
  90603. bodyConfig.rotShape.push(rot.y * radToDeg);
  90604. bodyConfig.rotShape.push(rot.z * radToDeg);
  90605. }
  90606. // register mesh
  90607. switch (i.type) {
  90608. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90609. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  90610. case BABYLON.PhysicsImpostor.SphereImpostor:
  90611. var radiusX = extendSize.x;
  90612. var radiusY = extendSize.y;
  90613. var radiusZ = extendSize.z;
  90614. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  90615. bodyConfig.type.push('sphere');
  90616. //due to the way oimo works with compounds, add 3 times
  90617. bodyConfig.size.push(size);
  90618. bodyConfig.size.push(size);
  90619. bodyConfig.size.push(size);
  90620. break;
  90621. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90622. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  90623. var sizeY = checkWithEpsilon_1(extendSize.y);
  90624. bodyConfig.type.push('cylinder');
  90625. bodyConfig.size.push(sizeX);
  90626. bodyConfig.size.push(sizeY);
  90627. //due to the way oimo works with compounds, add one more value.
  90628. bodyConfig.size.push(sizeY);
  90629. break;
  90630. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90631. case BABYLON.PhysicsImpostor.BoxImpostor:
  90632. default:
  90633. var sizeX = checkWithEpsilon_1(extendSize.x);
  90634. var sizeY = checkWithEpsilon_1(extendSize.y);
  90635. var sizeZ = checkWithEpsilon_1(extendSize.z);
  90636. bodyConfig.type.push('box');
  90637. //if (i === impostor) {
  90638. bodyConfig.size.push(sizeX);
  90639. bodyConfig.size.push(sizeY);
  90640. bodyConfig.size.push(sizeZ);
  90641. //} else {
  90642. // bodyConfig.size.push(0,0,0);
  90643. //}
  90644. break;
  90645. }
  90646. //actually not needed, but hey...
  90647. i.object.rotationQuaternion = oldQuaternion;
  90648. });
  90649. impostor.physicsBody = this.world.add(bodyConfig);
  90650. // set the quaternion, ignoring the previously defined (euler) rotation
  90651. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  90652. // update with delta 0, so the body will reveive the new rotation.
  90653. impostor.physicsBody.updatePosition(0);
  90654. }
  90655. else {
  90656. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  90657. }
  90658. impostor.setDeltaPosition(this._tmpPositionVector);
  90659. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  90660. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  90661. };
  90662. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90663. //impostor.physicsBody.dispose();
  90664. //Same as : (older oimo versions)
  90665. this.world.removeRigidBody(impostor.physicsBody);
  90666. };
  90667. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90668. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90669. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90670. if (!mainBody || !connectedBody) {
  90671. return;
  90672. }
  90673. var jointData = impostorJoint.joint.jointData;
  90674. var options = jointData.nativeParams || {};
  90675. var type;
  90676. var nativeJointData = {
  90677. body1: mainBody,
  90678. body2: connectedBody,
  90679. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  90680. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  90681. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  90682. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  90683. min: options.min,
  90684. max: options.max,
  90685. collision: options.collision || jointData.collision,
  90686. spring: options.spring,
  90687. //supporting older version of Oimo
  90688. world: this.world
  90689. };
  90690. switch (impostorJoint.joint.type) {
  90691. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90692. type = "jointBall";
  90693. break;
  90694. case BABYLON.PhysicsJoint.SpringJoint:
  90695. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  90696. var springData = jointData;
  90697. nativeJointData.min = springData.length || nativeJointData.min;
  90698. //Max should also be set, just make sure it is at least min
  90699. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  90700. case BABYLON.PhysicsJoint.DistanceJoint:
  90701. type = "jointDistance";
  90702. nativeJointData.max = jointData.maxDistance;
  90703. break;
  90704. case BABYLON.PhysicsJoint.PrismaticJoint:
  90705. type = "jointPrisme";
  90706. break;
  90707. case BABYLON.PhysicsJoint.SliderJoint:
  90708. type = "jointSlide";
  90709. break;
  90710. case BABYLON.PhysicsJoint.WheelJoint:
  90711. type = "jointWheel";
  90712. break;
  90713. case BABYLON.PhysicsJoint.HingeJoint:
  90714. default:
  90715. type = "jointHinge";
  90716. break;
  90717. }
  90718. nativeJointData.type = type;
  90719. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  90720. };
  90721. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90722. //Bug in Oimo prevents us from disposing a joint in the playground
  90723. //joint.joint.physicsJoint.dispose();
  90724. //So we will bruteforce it!
  90725. try {
  90726. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  90727. }
  90728. catch (e) {
  90729. BABYLON.Tools.Warn(e);
  90730. }
  90731. };
  90732. OimoJSPlugin.prototype.isSupported = function () {
  90733. return this.BJSOIMO !== undefined;
  90734. };
  90735. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90736. if (!impostor.physicsBody.sleeping) {
  90737. //TODO check that
  90738. /*if (impostor.physicsBody.shapes.next) {
  90739. var parentShape = this._getLastShape(impostor.physicsBody);
  90740. impostor.object.position.copyFrom(parentShape.position);
  90741. console.log(parentShape.position);
  90742. } else {*/
  90743. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  90744. //}
  90745. if (impostor.object.rotationQuaternion) {
  90746. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  90747. }
  90748. }
  90749. };
  90750. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90751. var body = impostor.physicsBody;
  90752. body.position.copy(newPosition);
  90753. body.orientation.copy(newRotation);
  90754. body.syncShapes();
  90755. body.awake();
  90756. };
  90757. /*private _getLastShape(body: any): any {
  90758. var lastShape = body.shapes;
  90759. while (lastShape.next) {
  90760. lastShape = lastShape.next;
  90761. }
  90762. return lastShape;
  90763. }*/
  90764. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90765. impostor.physicsBody.linearVelocity.copy(velocity);
  90766. };
  90767. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90768. impostor.physicsBody.angularVelocity.copy(velocity);
  90769. };
  90770. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90771. var v = impostor.physicsBody.linearVelocity;
  90772. if (!v) {
  90773. return null;
  90774. }
  90775. return new BABYLON.Vector3(v.x, v.y, v.z);
  90776. };
  90777. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90778. var v = impostor.physicsBody.angularVelocity;
  90779. if (!v) {
  90780. return null;
  90781. }
  90782. return new BABYLON.Vector3(v.x, v.y, v.z);
  90783. };
  90784. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90785. var staticBody = mass === 0;
  90786. //this will actually set the body's density and not its mass.
  90787. //But this is how oimo treats the mass variable.
  90788. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  90789. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  90790. };
  90791. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  90792. return impostor.physicsBody.shapes.density;
  90793. };
  90794. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  90795. return impostor.physicsBody.shapes.friction;
  90796. };
  90797. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90798. impostor.physicsBody.shapes.friction = friction;
  90799. };
  90800. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90801. return impostor.physicsBody.shapes.restitution;
  90802. };
  90803. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90804. impostor.physicsBody.shapes.restitution = restitution;
  90805. };
  90806. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  90807. impostor.physicsBody.sleep();
  90808. };
  90809. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  90810. impostor.physicsBody.awake();
  90811. };
  90812. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90813. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  90814. if (minDistance !== void 0) {
  90815. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  90816. }
  90817. };
  90818. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90819. //TODO separate rotational and transational motors.
  90820. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90821. if (motor) {
  90822. motor.setMotor(speed, maxForce);
  90823. }
  90824. };
  90825. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  90826. //TODO separate rotational and transational motors.
  90827. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90828. if (motor) {
  90829. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  90830. }
  90831. };
  90832. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90833. var body = impostor.physicsBody;
  90834. mesh.position.x = body.position.x;
  90835. mesh.position.y = body.position.y;
  90836. mesh.position.z = body.position.z;
  90837. if (mesh.rotationQuaternion) {
  90838. mesh.rotationQuaternion.x = body.orientation.x;
  90839. mesh.rotationQuaternion.y = body.orientation.y;
  90840. mesh.rotationQuaternion.z = body.orientation.z;
  90841. mesh.rotationQuaternion.w = body.orientation.s;
  90842. }
  90843. };
  90844. OimoJSPlugin.prototype.getRadius = function (impostor) {
  90845. return impostor.physicsBody.shapes.radius;
  90846. };
  90847. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90848. var shape = impostor.physicsBody.shapes;
  90849. result.x = shape.halfWidth * 2;
  90850. result.y = shape.halfHeight * 2;
  90851. result.z = shape.halfDepth * 2;
  90852. };
  90853. OimoJSPlugin.prototype.dispose = function () {
  90854. this.world.clear();
  90855. };
  90856. return OimoJSPlugin;
  90857. }());
  90858. BABYLON.OimoJSPlugin = OimoJSPlugin;
  90859. })(BABYLON || (BABYLON = {}));
  90860. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  90861. var BABYLON;
  90862. (function (BABYLON) {
  90863. /**
  90864. * Gets the current physics engine
  90865. * @returns a IPhysicsEngine or null if none attached
  90866. */
  90867. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  90868. return this._physicsEngine;
  90869. };
  90870. /**
  90871. * Enables physics to the current scene
  90872. * @param gravity defines the scene's gravity for the physics engine
  90873. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  90874. * @return a boolean indicating if the physics engine was initialized
  90875. */
  90876. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  90877. if (gravity === void 0) { gravity = null; }
  90878. if (this._physicsEngine) {
  90879. return true;
  90880. }
  90881. // Register the component to the scene
  90882. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  90883. if (!component) {
  90884. component = new PhysicsEngineSceneComponent(this);
  90885. this._addComponent(component);
  90886. }
  90887. try {
  90888. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  90889. return true;
  90890. }
  90891. catch (e) {
  90892. BABYLON.Tools.Error(e.message);
  90893. return false;
  90894. }
  90895. };
  90896. /**
  90897. * Disables and disposes the physics engine associated with the scene
  90898. */
  90899. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  90900. if (!this._physicsEngine) {
  90901. return;
  90902. }
  90903. this._physicsEngine.dispose();
  90904. this._physicsEngine = null;
  90905. };
  90906. /**
  90907. * Gets a boolean indicating if there is an active physics engine
  90908. * @returns a boolean indicating if there is an active physics engine
  90909. */
  90910. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  90911. return this._physicsEngine !== undefined;
  90912. };
  90913. /**
  90914. * Deletes a physics compound impostor
  90915. * @param compound defines the compound to delete
  90916. */
  90917. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  90918. var mesh = compound.parts[0].mesh;
  90919. if (mesh.physicsImpostor) {
  90920. mesh.physicsImpostor.dispose( /*true*/);
  90921. mesh.physicsImpostor = null;
  90922. }
  90923. };
  90924. /** @hidden */
  90925. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  90926. if (this._physicsEngine) {
  90927. this.onBeforePhysicsObservable.notifyObservers(this);
  90928. this._physicsEngine._step(step / 1000);
  90929. this.onAfterPhysicsObservable.notifyObservers(this);
  90930. }
  90931. };
  90932. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  90933. get: function () {
  90934. return this._physicsImpostor;
  90935. },
  90936. set: function (value) {
  90937. var _this = this;
  90938. if (this._physicsImpostor === value) {
  90939. return;
  90940. }
  90941. if (this._disposePhysicsObserver) {
  90942. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  90943. }
  90944. this._physicsImpostor = value;
  90945. if (value) {
  90946. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  90947. // Physics
  90948. if (_this.physicsImpostor) {
  90949. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  90950. _this.physicsImpostor = null;
  90951. }
  90952. });
  90953. }
  90954. },
  90955. enumerable: true,
  90956. configurable: true
  90957. });
  90958. /**
  90959. * Gets the current physics impostor
  90960. * @see http://doc.babylonjs.com/features/physics_engine
  90961. * @returns a physics impostor or null
  90962. */
  90963. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  90964. return this.physicsImpostor;
  90965. };
  90966. /**
  90967. * Apply a physic impulse to the mesh
  90968. * @param force defines the force to apply
  90969. * @param contactPoint defines where to apply the force
  90970. * @returns the current mesh
  90971. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  90972. */
  90973. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  90974. if (!this.physicsImpostor) {
  90975. return this;
  90976. }
  90977. this.physicsImpostor.applyImpulse(force, contactPoint);
  90978. return this;
  90979. };
  90980. /**
  90981. * Creates a physic joint between two meshes
  90982. * @param otherMesh defines the other mesh to use
  90983. * @param pivot1 defines the pivot to use on this mesh
  90984. * @param pivot2 defines the pivot to use on the other mesh
  90985. * @param options defines additional options (can be plugin dependent)
  90986. * @returns the current mesh
  90987. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  90988. */
  90989. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  90990. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  90991. return this;
  90992. }
  90993. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  90994. mainPivot: pivot1,
  90995. connectedPivot: pivot2,
  90996. nativeParams: options
  90997. });
  90998. return this;
  90999. };
  91000. /**
  91001. * Defines the physics engine scene component responsible to manage a physics engine
  91002. */
  91003. var PhysicsEngineSceneComponent = /** @class */ (function () {
  91004. /**
  91005. * Creates a new instance of the component for the given scene
  91006. * @param scene Defines the scene to register the component in
  91007. */
  91008. function PhysicsEngineSceneComponent(scene) {
  91009. var _this = this;
  91010. /**
  91011. * The component name helpful to identify the component in the list of scene components.
  91012. */
  91013. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  91014. this.scene = scene;
  91015. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  91016. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  91017. // Replace the function used to get the deterministic frame time
  91018. this.scene.getDeterministicFrameTime = function () {
  91019. if (_this.scene._physicsEngine) {
  91020. return _this.scene._physicsEngine.getTimeStep() * 1000;
  91021. }
  91022. return 1000.0 / 60.0;
  91023. };
  91024. }
  91025. /**
  91026. * Registers the component in a given scene
  91027. */
  91028. PhysicsEngineSceneComponent.prototype.register = function () {
  91029. };
  91030. /**
  91031. * Rebuilds the elements related to this component in case of
  91032. * context lost for instance.
  91033. */
  91034. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  91035. // Nothing to do for this component
  91036. };
  91037. /**
  91038. * Disposes the component and the associated ressources
  91039. */
  91040. PhysicsEngineSceneComponent.prototype.dispose = function () {
  91041. this.scene.onBeforePhysicsObservable.clear();
  91042. this.scene.onAfterPhysicsObservable.clear();
  91043. if (this.scene._physicsEngine) {
  91044. this.scene.disablePhysicsEngine();
  91045. }
  91046. };
  91047. return PhysicsEngineSceneComponent;
  91048. }());
  91049. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  91050. })(BABYLON || (BABYLON = {}));
  91051. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  91052. var BABYLON;
  91053. (function (BABYLON) {
  91054. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  91055. // All values and structures referenced from:
  91056. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  91057. var DDS_MAGIC = 0x20534444;
  91058. var
  91059. //DDSD_CAPS = 0x1,
  91060. //DDSD_HEIGHT = 0x2,
  91061. //DDSD_WIDTH = 0x4,
  91062. //DDSD_PITCH = 0x8,
  91063. //DDSD_PIXELFORMAT = 0x1000,
  91064. DDSD_MIPMAPCOUNT = 0x20000;
  91065. //DDSD_LINEARSIZE = 0x80000,
  91066. //DDSD_DEPTH = 0x800000;
  91067. // var DDSCAPS_COMPLEX = 0x8,
  91068. // DDSCAPS_MIPMAP = 0x400000,
  91069. // DDSCAPS_TEXTURE = 0x1000;
  91070. var DDSCAPS2_CUBEMAP = 0x200;
  91071. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  91072. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  91073. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  91074. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  91075. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  91076. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  91077. // DDSCAPS2_VOLUME = 0x200000;
  91078. var
  91079. //DDPF_ALPHAPIXELS = 0x1,
  91080. //DDPF_ALPHA = 0x2,
  91081. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  91082. //DDPF_YUV = 0x200,
  91083. DDPF_LUMINANCE = 0x20000;
  91084. function FourCCToInt32(value) {
  91085. return value.charCodeAt(0) +
  91086. (value.charCodeAt(1) << 8) +
  91087. (value.charCodeAt(2) << 16) +
  91088. (value.charCodeAt(3) << 24);
  91089. }
  91090. function Int32ToFourCC(value) {
  91091. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  91092. }
  91093. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  91094. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  91095. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  91096. var FOURCC_DX10 = FourCCToInt32("DX10");
  91097. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  91098. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  91099. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  91100. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  91101. var headerLengthInt = 31; // The header length in 32 bit ints
  91102. // Offsets into the header array
  91103. var off_magic = 0;
  91104. var off_size = 1;
  91105. var off_flags = 2;
  91106. var off_height = 3;
  91107. var off_width = 4;
  91108. var off_mipmapCount = 7;
  91109. var off_pfFlags = 20;
  91110. var off_pfFourCC = 21;
  91111. var off_RGBbpp = 22;
  91112. var off_RMask = 23;
  91113. var off_GMask = 24;
  91114. var off_BMask = 25;
  91115. var off_AMask = 26;
  91116. // var off_caps1 = 27;
  91117. var off_caps2 = 28;
  91118. // var off_caps3 = 29;
  91119. // var off_caps4 = 30;
  91120. var off_dxgiFormat = 32;
  91121. ;
  91122. var DDSTools = /** @class */ (function () {
  91123. function DDSTools() {
  91124. }
  91125. DDSTools.GetDDSInfo = function (arrayBuffer) {
  91126. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  91127. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  91128. var mipmapCount = 1;
  91129. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  91130. mipmapCount = Math.max(1, header[off_mipmapCount]);
  91131. }
  91132. var fourCC = header[off_pfFourCC];
  91133. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  91134. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91135. switch (fourCC) {
  91136. case FOURCC_D3DFMT_R16G16B16A16F:
  91137. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91138. break;
  91139. case FOURCC_D3DFMT_R32G32B32A32F:
  91140. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91141. break;
  91142. case FOURCC_DX10:
  91143. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  91144. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91145. break;
  91146. }
  91147. }
  91148. return {
  91149. width: header[off_width],
  91150. height: header[off_height],
  91151. mipmapCount: mipmapCount,
  91152. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  91153. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  91154. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  91155. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  91156. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  91157. dxgiFormat: dxgiFormat,
  91158. textureType: textureType
  91159. };
  91160. };
  91161. DDSTools._ToHalfFloat = function (value) {
  91162. if (!DDSTools._FloatView) {
  91163. DDSTools._FloatView = new Float32Array(1);
  91164. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  91165. }
  91166. DDSTools._FloatView[0] = value;
  91167. var x = DDSTools._Int32View[0];
  91168. var bits = (x >> 16) & 0x8000; /* Get the sign */
  91169. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  91170. var e = (x >> 23) & 0xff; /* Using int is faster here */
  91171. /* If zero, or denormal, or exponent underflows too much for a denormal
  91172. * half, return signed zero. */
  91173. if (e < 103) {
  91174. return bits;
  91175. }
  91176. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  91177. if (e > 142) {
  91178. bits |= 0x7c00;
  91179. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  91180. * not Inf, so make sure we set one mantissa bit too. */
  91181. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  91182. return bits;
  91183. }
  91184. /* If exponent underflows but not too much, return a denormal */
  91185. if (e < 113) {
  91186. m |= 0x0800;
  91187. /* Extra rounding may overflow and set mantissa to 0 and exponent
  91188. * to 1, which is OK. */
  91189. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  91190. return bits;
  91191. }
  91192. bits |= ((e - 112) << 10) | (m >> 1);
  91193. bits += m & 1;
  91194. return bits;
  91195. };
  91196. DDSTools._FromHalfFloat = function (value) {
  91197. var s = (value & 0x8000) >> 15;
  91198. var e = (value & 0x7C00) >> 10;
  91199. var f = value & 0x03FF;
  91200. if (e === 0) {
  91201. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  91202. }
  91203. else if (e == 0x1F) {
  91204. return f ? NaN : ((s ? -1 : 1) * Infinity);
  91205. }
  91206. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  91207. };
  91208. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91209. var destArray = new Float32Array(dataLength);
  91210. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91211. var index = 0;
  91212. for (var y = 0; y < height; y++) {
  91213. for (var x = 0; x < width; x++) {
  91214. var srcPos = (x + y * width) * 4;
  91215. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  91216. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  91217. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  91218. if (DDSTools.StoreLODInAlphaChannel) {
  91219. destArray[index + 3] = lod;
  91220. }
  91221. else {
  91222. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  91223. }
  91224. index += 4;
  91225. }
  91226. }
  91227. return destArray;
  91228. };
  91229. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91230. if (DDSTools.StoreLODInAlphaChannel) {
  91231. var destArray = new Uint16Array(dataLength);
  91232. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91233. var index = 0;
  91234. for (var y = 0; y < height; y++) {
  91235. for (var x = 0; x < width; x++) {
  91236. var srcPos = (x + y * width) * 4;
  91237. destArray[index] = srcData[srcPos];
  91238. destArray[index + 1] = srcData[srcPos + 1];
  91239. destArray[index + 2] = srcData[srcPos + 2];
  91240. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  91241. index += 4;
  91242. }
  91243. }
  91244. return destArray;
  91245. }
  91246. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  91247. };
  91248. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91249. if (DDSTools.StoreLODInAlphaChannel) {
  91250. var destArray = new Float32Array(dataLength);
  91251. var srcData = new Float32Array(arrayBuffer, dataOffset);
  91252. var index = 0;
  91253. for (var y = 0; y < height; y++) {
  91254. for (var x = 0; x < width; x++) {
  91255. var srcPos = (x + y * width) * 4;
  91256. destArray[index] = srcData[srcPos];
  91257. destArray[index + 1] = srcData[srcPos + 1];
  91258. destArray[index + 2] = srcData[srcPos + 2];
  91259. destArray[index + 3] = lod;
  91260. index += 4;
  91261. }
  91262. }
  91263. return destArray;
  91264. }
  91265. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  91266. };
  91267. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91268. var destArray = new Uint8Array(dataLength);
  91269. var srcData = new Float32Array(arrayBuffer, dataOffset);
  91270. var index = 0;
  91271. for (var y = 0; y < height; y++) {
  91272. for (var x = 0; x < width; x++) {
  91273. var srcPos = (x + y * width) * 4;
  91274. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  91275. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  91276. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  91277. if (DDSTools.StoreLODInAlphaChannel) {
  91278. destArray[index + 3] = lod;
  91279. }
  91280. else {
  91281. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  91282. }
  91283. index += 4;
  91284. }
  91285. }
  91286. return destArray;
  91287. };
  91288. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91289. var destArray = new Uint8Array(dataLength);
  91290. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91291. var index = 0;
  91292. for (var y = 0; y < height; y++) {
  91293. for (var x = 0; x < width; x++) {
  91294. var srcPos = (x + y * width) * 4;
  91295. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  91296. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  91297. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  91298. if (DDSTools.StoreLODInAlphaChannel) {
  91299. destArray[index + 3] = lod;
  91300. }
  91301. else {
  91302. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  91303. }
  91304. index += 4;
  91305. }
  91306. }
  91307. return destArray;
  91308. };
  91309. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  91310. var byteArray = new Uint8Array(dataLength);
  91311. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91312. var index = 0;
  91313. for (var y = 0; y < height; y++) {
  91314. for (var x = 0; x < width; x++) {
  91315. var srcPos = (x + y * width) * 4;
  91316. byteArray[index] = srcData[srcPos + rOffset];
  91317. byteArray[index + 1] = srcData[srcPos + gOffset];
  91318. byteArray[index + 2] = srcData[srcPos + bOffset];
  91319. byteArray[index + 3] = srcData[srcPos + aOffset];
  91320. index += 4;
  91321. }
  91322. }
  91323. return byteArray;
  91324. };
  91325. DDSTools._ExtractLongWordOrder = function (value) {
  91326. if (value === 0 || value === 255 || value === -16777216) {
  91327. return 0;
  91328. }
  91329. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  91330. };
  91331. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  91332. var byteArray = new Uint8Array(dataLength);
  91333. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91334. var index = 0;
  91335. for (var y = 0; y < height; y++) {
  91336. for (var x = 0; x < width; x++) {
  91337. var srcPos = (x + y * width) * 3;
  91338. byteArray[index] = srcData[srcPos + rOffset];
  91339. byteArray[index + 1] = srcData[srcPos + gOffset];
  91340. byteArray[index + 2] = srcData[srcPos + bOffset];
  91341. index += 3;
  91342. }
  91343. }
  91344. return byteArray;
  91345. };
  91346. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  91347. var byteArray = new Uint8Array(dataLength);
  91348. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91349. var index = 0;
  91350. for (var y = 0; y < height; y++) {
  91351. for (var x = 0; x < width; x++) {
  91352. var srcPos = (x + y * width);
  91353. byteArray[index] = srcData[srcPos];
  91354. index++;
  91355. }
  91356. }
  91357. return byteArray;
  91358. };
  91359. /**
  91360. * Uploads DDS Levels to a Babylon Texture
  91361. * @hidden
  91362. */
  91363. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  91364. if (lodIndex === void 0) { lodIndex = -1; }
  91365. var sphericalPolynomialFaces = null;
  91366. if (info.sphericalPolynomial) {
  91367. sphericalPolynomialFaces = new Array();
  91368. }
  91369. var ext = engine.getCaps().s3tc;
  91370. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  91371. var fourCC, width, height, dataLength = 0, dataOffset;
  91372. var byteArray, mipmapCount, mip;
  91373. var internalCompressedFormat = 0;
  91374. var blockBytes = 1;
  91375. if (header[off_magic] !== DDS_MAGIC) {
  91376. BABYLON.Tools.Error("Invalid magic number in DDS header");
  91377. return;
  91378. }
  91379. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  91380. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  91381. return;
  91382. }
  91383. if (info.isCompressed && !ext) {
  91384. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  91385. return;
  91386. }
  91387. var bpp = header[off_RGBbpp];
  91388. dataOffset = header[off_size] + 4;
  91389. var computeFormats = false;
  91390. if (info.isFourCC) {
  91391. fourCC = header[off_pfFourCC];
  91392. switch (fourCC) {
  91393. case FOURCC_DXT1:
  91394. blockBytes = 8;
  91395. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  91396. break;
  91397. case FOURCC_DXT3:
  91398. blockBytes = 16;
  91399. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  91400. break;
  91401. case FOURCC_DXT5:
  91402. blockBytes = 16;
  91403. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  91404. break;
  91405. case FOURCC_D3DFMT_R16G16B16A16F:
  91406. computeFormats = true;
  91407. break;
  91408. case FOURCC_D3DFMT_R32G32B32A32F:
  91409. computeFormats = true;
  91410. break;
  91411. case FOURCC_DX10:
  91412. // There is an additionnal header so dataOffset need to be changed
  91413. dataOffset += 5 * 4; // 5 uints
  91414. var supported = false;
  91415. switch (info.dxgiFormat) {
  91416. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  91417. computeFormats = true;
  91418. supported = true;
  91419. break;
  91420. case DXGI_FORMAT_B8G8R8X8_UNORM:
  91421. info.isRGB = true;
  91422. info.isFourCC = false;
  91423. bpp = 32;
  91424. supported = true;
  91425. break;
  91426. }
  91427. if (supported) {
  91428. break;
  91429. }
  91430. default:
  91431. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  91432. return;
  91433. }
  91434. }
  91435. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  91436. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  91437. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  91438. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  91439. if (computeFormats) {
  91440. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  91441. }
  91442. mipmapCount = 1;
  91443. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  91444. mipmapCount = Math.max(1, header[off_mipmapCount]);
  91445. }
  91446. for (var face = 0; face < faces; face++) {
  91447. width = header[off_width];
  91448. height = header[off_height];
  91449. for (mip = 0; mip < mipmapCount; ++mip) {
  91450. if (lodIndex === -1 || lodIndex === mip) {
  91451. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  91452. var i = (lodIndex === -1) ? mip : 0;
  91453. if (!info.isCompressed && info.isFourCC) {
  91454. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91455. dataLength = width * height * 4;
  91456. var floatArray = null;
  91457. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  91458. if (bpp === 128) {
  91459. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91460. if (sphericalPolynomialFaces && i == 0) {
  91461. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91462. }
  91463. }
  91464. else if (bpp === 64) {
  91465. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91466. if (sphericalPolynomialFaces && i == 0) {
  91467. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91468. }
  91469. }
  91470. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91471. }
  91472. else {
  91473. if (bpp === 128) {
  91474. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91475. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91476. if (sphericalPolynomialFaces && i == 0) {
  91477. sphericalPolynomialFaces.push(floatArray);
  91478. }
  91479. }
  91480. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  91481. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91482. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91483. if (sphericalPolynomialFaces && i == 0) {
  91484. sphericalPolynomialFaces.push(floatArray);
  91485. }
  91486. }
  91487. else { // 64
  91488. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91489. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91490. if (sphericalPolynomialFaces && i == 0) {
  91491. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91492. }
  91493. }
  91494. }
  91495. if (floatArray) {
  91496. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  91497. }
  91498. }
  91499. else if (info.isRGB) {
  91500. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91501. if (bpp === 24) {
  91502. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  91503. dataLength = width * height * 3;
  91504. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  91505. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91506. }
  91507. else { // 32
  91508. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91509. dataLength = width * height * 4;
  91510. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  91511. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91512. }
  91513. }
  91514. else if (info.isLuminance) {
  91515. var unpackAlignment = engine._getUnpackAlignement();
  91516. var unpaddedRowSize = width;
  91517. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  91518. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  91519. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  91520. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  91521. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91522. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91523. }
  91524. else {
  91525. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  91526. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  91527. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91528. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  91529. }
  91530. }
  91531. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  91532. width *= 0.5;
  91533. height *= 0.5;
  91534. width = Math.max(1.0, width);
  91535. height = Math.max(1.0, height);
  91536. }
  91537. if (currentFace !== undefined) {
  91538. // Loading a single face
  91539. break;
  91540. }
  91541. }
  91542. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  91543. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  91544. size: header[off_width],
  91545. right: sphericalPolynomialFaces[0],
  91546. left: sphericalPolynomialFaces[1],
  91547. up: sphericalPolynomialFaces[2],
  91548. down: sphericalPolynomialFaces[3],
  91549. front: sphericalPolynomialFaces[4],
  91550. back: sphericalPolynomialFaces[5],
  91551. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  91552. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91553. gammaSpace: false,
  91554. });
  91555. }
  91556. else {
  91557. info.sphericalPolynomial = undefined;
  91558. }
  91559. };
  91560. DDSTools.StoreLODInAlphaChannel = false;
  91561. return DDSTools;
  91562. }());
  91563. BABYLON.DDSTools = DDSTools;
  91564. })(BABYLON || (BABYLON = {}));
  91565. //# sourceMappingURL=babylon.dds.js.map
  91566. var BABYLON;
  91567. (function (BABYLON) {
  91568. /**
  91569. * Implementation of the DDS Texture Loader.
  91570. */
  91571. var DDSTextureLoader = /** @class */ (function () {
  91572. function DDSTextureLoader() {
  91573. /**
  91574. * Defines wether the loader supports cascade loading the different faces.
  91575. */
  91576. this.supportCascades = true;
  91577. }
  91578. /**
  91579. * This returns if the loader support the current file information.
  91580. * @param extension defines the file extension of the file being loaded
  91581. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91582. * @param fallback defines the fallback internal texture if any
  91583. * @param isBase64 defines whether the texture is encoded as a base64
  91584. * @param isBuffer defines whether the texture data are stored as a buffer
  91585. * @returns true if the loader can load the specified file
  91586. */
  91587. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91588. return extension.indexOf(".dds") === 0;
  91589. };
  91590. /**
  91591. * Transform the url before loading if required.
  91592. * @param rootUrl the url of the texture
  91593. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91594. * @returns the transformed texture
  91595. */
  91596. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91597. return rootUrl;
  91598. };
  91599. /**
  91600. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91601. * @param rootUrl the url of the texture
  91602. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91603. * @returns the fallback texture
  91604. */
  91605. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91606. return null;
  91607. };
  91608. /**
  91609. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91610. * @param data contains the texture data
  91611. * @param texture defines the BabylonJS internal texture
  91612. * @param createPolynomials will be true if polynomials have been requested
  91613. * @param onLoad defines the callback to trigger once the texture is ready
  91614. * @param onError defines the callback to trigger in case of error
  91615. */
  91616. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  91617. var engine = texture.getEngine();
  91618. var info;
  91619. var loadMipmap = false;
  91620. if (Array.isArray(imgs)) {
  91621. for (var index = 0; index < imgs.length; index++) {
  91622. var data_1 = imgs[index];
  91623. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  91624. texture.width = info.width;
  91625. texture.height = info.height;
  91626. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91627. engine._unpackFlipY(info.isCompressed);
  91628. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  91629. if (!info.isFourCC && info.mipmapCount === 1) {
  91630. engine.generateMipMapsForCubemap(texture);
  91631. }
  91632. }
  91633. }
  91634. else {
  91635. var data = imgs;
  91636. info = BABYLON.DDSTools.GetDDSInfo(data);
  91637. texture.width = info.width;
  91638. texture.height = info.height;
  91639. if (createPolynomials) {
  91640. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  91641. }
  91642. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91643. engine._unpackFlipY(info.isCompressed);
  91644. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  91645. if (!info.isFourCC && info.mipmapCount === 1) {
  91646. engine.generateMipMapsForCubemap(texture);
  91647. }
  91648. }
  91649. engine._setCubeMapTextureParams(loadMipmap);
  91650. texture.isReady = true;
  91651. if (onLoad) {
  91652. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  91653. }
  91654. };
  91655. /**
  91656. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91657. * @param data contains the texture data
  91658. * @param texture defines the BabylonJS internal texture
  91659. * @param callback defines the method to call once ready to upload
  91660. */
  91661. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  91662. var info = BABYLON.DDSTools.GetDDSInfo(data);
  91663. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  91664. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  91665. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  91666. });
  91667. };
  91668. return DDSTextureLoader;
  91669. }());
  91670. // Register the loader.
  91671. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  91672. })(BABYLON || (BABYLON = {}));
  91673. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  91674. var BABYLON;
  91675. (function (BABYLON) {
  91676. /*
  91677. * Based on jsTGALoader - Javascript loader for TGA file
  91678. * By Vincent Thibault
  91679. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  91680. */
  91681. var TGATools = /** @class */ (function () {
  91682. function TGATools() {
  91683. }
  91684. TGATools.GetTGAHeader = function (data) {
  91685. var offset = 0;
  91686. var header = {
  91687. id_length: data[offset++],
  91688. colormap_type: data[offset++],
  91689. image_type: data[offset++],
  91690. colormap_index: data[offset++] | data[offset++] << 8,
  91691. colormap_length: data[offset++] | data[offset++] << 8,
  91692. colormap_size: data[offset++],
  91693. origin: [
  91694. data[offset++] | data[offset++] << 8,
  91695. data[offset++] | data[offset++] << 8
  91696. ],
  91697. width: data[offset++] | data[offset++] << 8,
  91698. height: data[offset++] | data[offset++] << 8,
  91699. pixel_size: data[offset++],
  91700. flags: data[offset++]
  91701. };
  91702. return header;
  91703. };
  91704. /**
  91705. * Uploads TGA content to a Babylon Texture
  91706. * @hidden
  91707. */
  91708. TGATools.UploadContent = function (texture, data) {
  91709. // Not enough data to contain header ?
  91710. if (data.length < 19) {
  91711. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  91712. return;
  91713. }
  91714. // Read Header
  91715. var offset = 18;
  91716. var header = TGATools.GetTGAHeader(data);
  91717. // Assume it's a valid Targa file.
  91718. if (header.id_length + offset > data.length) {
  91719. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  91720. return;
  91721. }
  91722. // Skip not needed data
  91723. offset += header.id_length;
  91724. var use_rle = false;
  91725. var use_pal = false;
  91726. var use_grey = false;
  91727. // Get some informations.
  91728. switch (header.image_type) {
  91729. case TGATools._TYPE_RLE_INDEXED:
  91730. use_rle = true;
  91731. case TGATools._TYPE_INDEXED:
  91732. use_pal = true;
  91733. break;
  91734. case TGATools._TYPE_RLE_RGB:
  91735. use_rle = true;
  91736. case TGATools._TYPE_RGB:
  91737. // use_rgb = true;
  91738. break;
  91739. case TGATools._TYPE_RLE_GREY:
  91740. use_rle = true;
  91741. case TGATools._TYPE_GREY:
  91742. use_grey = true;
  91743. break;
  91744. }
  91745. var pixel_data;
  91746. // var numAlphaBits = header.flags & 0xf;
  91747. var pixel_size = header.pixel_size >> 3;
  91748. var pixel_total = header.width * header.height * pixel_size;
  91749. // Read palettes
  91750. var palettes;
  91751. if (use_pal) {
  91752. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  91753. }
  91754. // Read LRE
  91755. if (use_rle) {
  91756. pixel_data = new Uint8Array(pixel_total);
  91757. var c, count, i;
  91758. var localOffset = 0;
  91759. var pixels = new Uint8Array(pixel_size);
  91760. while (offset < pixel_total && localOffset < pixel_total) {
  91761. c = data[offset++];
  91762. count = (c & 0x7f) + 1;
  91763. // RLE pixels
  91764. if (c & 0x80) {
  91765. // Bind pixel tmp array
  91766. for (i = 0; i < pixel_size; ++i) {
  91767. pixels[i] = data[offset++];
  91768. }
  91769. // Copy pixel array
  91770. for (i = 0; i < count; ++i) {
  91771. pixel_data.set(pixels, localOffset + i * pixel_size);
  91772. }
  91773. localOffset += pixel_size * count;
  91774. }
  91775. // Raw pixels
  91776. else {
  91777. count *= pixel_size;
  91778. for (i = 0; i < count; ++i) {
  91779. pixel_data[localOffset + i] = data[offset++];
  91780. }
  91781. localOffset += count;
  91782. }
  91783. }
  91784. }
  91785. // RAW Pixels
  91786. else {
  91787. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  91788. }
  91789. // Load to texture
  91790. var x_start, y_start, x_step, y_step, y_end, x_end;
  91791. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  91792. default:
  91793. case TGATools._ORIGIN_UL:
  91794. x_start = 0;
  91795. x_step = 1;
  91796. x_end = header.width;
  91797. y_start = 0;
  91798. y_step = 1;
  91799. y_end = header.height;
  91800. break;
  91801. case TGATools._ORIGIN_BL:
  91802. x_start = 0;
  91803. x_step = 1;
  91804. x_end = header.width;
  91805. y_start = header.height - 1;
  91806. y_step = -1;
  91807. y_end = -1;
  91808. break;
  91809. case TGATools._ORIGIN_UR:
  91810. x_start = header.width - 1;
  91811. x_step = -1;
  91812. x_end = -1;
  91813. y_start = 0;
  91814. y_step = 1;
  91815. y_end = header.height;
  91816. break;
  91817. case TGATools._ORIGIN_BR:
  91818. x_start = header.width - 1;
  91819. x_step = -1;
  91820. x_end = -1;
  91821. y_start = header.height - 1;
  91822. y_step = -1;
  91823. y_end = -1;
  91824. break;
  91825. }
  91826. // Load the specify method
  91827. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  91828. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  91829. var engine = texture.getEngine();
  91830. engine._uploadDataToTextureDirectly(texture, imageData);
  91831. };
  91832. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91833. var image = pixel_data, colormap = palettes;
  91834. var width = header.width, height = header.height;
  91835. var color, i = 0, x, y;
  91836. var imageData = new Uint8Array(width * height * 4);
  91837. for (y = y_start; y !== y_end; y += y_step) {
  91838. for (x = x_start; x !== x_end; x += x_step, i++) {
  91839. color = image[i];
  91840. imageData[(x + width * y) * 4 + 3] = 255;
  91841. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  91842. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  91843. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  91844. }
  91845. }
  91846. return imageData;
  91847. };
  91848. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91849. var image = pixel_data;
  91850. var width = header.width, height = header.height;
  91851. var color, i = 0, x, y;
  91852. var imageData = new Uint8Array(width * height * 4);
  91853. for (y = y_start; y !== y_end; y += y_step) {
  91854. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91855. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  91856. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  91857. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  91858. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  91859. imageData[(x + width * y) * 4 + 0] = r;
  91860. imageData[(x + width * y) * 4 + 1] = g;
  91861. imageData[(x + width * y) * 4 + 2] = b;
  91862. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  91863. }
  91864. }
  91865. return imageData;
  91866. };
  91867. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91868. var image = pixel_data;
  91869. var width = header.width, height = header.height;
  91870. var i = 0, x, y;
  91871. var imageData = new Uint8Array(width * height * 4);
  91872. for (y = y_start; y !== y_end; y += y_step) {
  91873. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  91874. imageData[(x + width * y) * 4 + 3] = 255;
  91875. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91876. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91877. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91878. }
  91879. }
  91880. return imageData;
  91881. };
  91882. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91883. var image = pixel_data;
  91884. var width = header.width, height = header.height;
  91885. var i = 0, x, y;
  91886. var imageData = new Uint8Array(width * height * 4);
  91887. for (y = y_start; y !== y_end; y += y_step) {
  91888. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  91889. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91890. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91891. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91892. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  91893. }
  91894. }
  91895. return imageData;
  91896. };
  91897. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91898. var image = pixel_data;
  91899. var width = header.width, height = header.height;
  91900. var color, i = 0, x, y;
  91901. var imageData = new Uint8Array(width * height * 4);
  91902. for (y = y_start; y !== y_end; y += y_step) {
  91903. for (x = x_start; x !== x_end; x += x_step, i++) {
  91904. color = image[i];
  91905. imageData[(x + width * y) * 4 + 0] = color;
  91906. imageData[(x + width * y) * 4 + 1] = color;
  91907. imageData[(x + width * y) * 4 + 2] = color;
  91908. imageData[(x + width * y) * 4 + 3] = 255;
  91909. }
  91910. }
  91911. return imageData;
  91912. };
  91913. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91914. var image = pixel_data;
  91915. var width = header.width, height = header.height;
  91916. var i = 0, x, y;
  91917. var imageData = new Uint8Array(width * height * 4);
  91918. for (y = y_start; y !== y_end; y += y_step) {
  91919. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91920. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  91921. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  91922. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91923. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  91924. }
  91925. }
  91926. return imageData;
  91927. };
  91928. //private static _TYPE_NO_DATA = 0;
  91929. TGATools._TYPE_INDEXED = 1;
  91930. TGATools._TYPE_RGB = 2;
  91931. TGATools._TYPE_GREY = 3;
  91932. TGATools._TYPE_RLE_INDEXED = 9;
  91933. TGATools._TYPE_RLE_RGB = 10;
  91934. TGATools._TYPE_RLE_GREY = 11;
  91935. TGATools._ORIGIN_MASK = 0x30;
  91936. TGATools._ORIGIN_SHIFT = 0x04;
  91937. TGATools._ORIGIN_BL = 0x00;
  91938. TGATools._ORIGIN_BR = 0x01;
  91939. TGATools._ORIGIN_UL = 0x02;
  91940. TGATools._ORIGIN_UR = 0x03;
  91941. return TGATools;
  91942. }());
  91943. BABYLON.TGATools = TGATools;
  91944. })(BABYLON || (BABYLON = {}));
  91945. //# sourceMappingURL=babylon.tga.js.map
  91946. var BABYLON;
  91947. (function (BABYLON) {
  91948. /**
  91949. * Implementation of the TGA Texture Loader.
  91950. */
  91951. var TGATextureLoader = /** @class */ (function () {
  91952. function TGATextureLoader() {
  91953. /**
  91954. * Defines wether the loader supports cascade loading the different faces.
  91955. */
  91956. this.supportCascades = false;
  91957. }
  91958. /**
  91959. * This returns if the loader support the current file information.
  91960. * @param extension defines the file extension of the file being loaded
  91961. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91962. * @param fallback defines the fallback internal texture if any
  91963. * @param isBase64 defines whether the texture is encoded as a base64
  91964. * @param isBuffer defines whether the texture data are stored as a buffer
  91965. * @returns true if the loader can load the specified file
  91966. */
  91967. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91968. return extension.indexOf(".tga") === 0;
  91969. };
  91970. /**
  91971. * Transform the url before loading if required.
  91972. * @param rootUrl the url of the texture
  91973. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91974. * @returns the transformed texture
  91975. */
  91976. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91977. return rootUrl;
  91978. };
  91979. /**
  91980. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91981. * @param rootUrl the url of the texture
  91982. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91983. * @returns the fallback texture
  91984. */
  91985. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91986. return null;
  91987. };
  91988. /**
  91989. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91990. * @param data contains the texture data
  91991. * @param texture defines the BabylonJS internal texture
  91992. * @param createPolynomials will be true if polynomials have been requested
  91993. * @param onLoad defines the callback to trigger once the texture is ready
  91994. * @param onError defines the callback to trigger in case of error
  91995. */
  91996. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91997. throw ".env not supported in Cube.";
  91998. };
  91999. /**
  92000. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92001. * @param data contains the texture data
  92002. * @param texture defines the BabylonJS internal texture
  92003. * @param callback defines the method to call once ready to upload
  92004. */
  92005. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  92006. var uintData = new Uint8Array(data);
  92007. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  92008. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  92009. BABYLON.TGATools.UploadContent(texture, uintData);
  92010. });
  92011. };
  92012. return TGATextureLoader;
  92013. }());
  92014. // Register the loader.
  92015. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  92016. })(BABYLON || (BABYLON = {}));
  92017. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  92018. var BABYLON;
  92019. (function (BABYLON) {
  92020. /**
  92021. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  92022. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  92023. */
  92024. var KhronosTextureContainer = /** @class */ (function () {
  92025. /**
  92026. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  92027. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  92028. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  92029. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  92030. */
  92031. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  92032. this.arrayBuffer = arrayBuffer;
  92033. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  92034. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  92035. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  92036. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  92037. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  92038. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  92039. BABYLON.Tools.Error("texture missing KTX identifier");
  92040. return;
  92041. }
  92042. // load the reset of the header in native 32 bit int
  92043. var header = new Int32Array(this.arrayBuffer, 12, 13);
  92044. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  92045. var oppositeEndianess = header[0] === 0x01020304;
  92046. // read all the header elements in order they exist in the file, without modification (sans endainness)
  92047. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  92048. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  92049. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  92050. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  92051. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  92052. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  92053. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  92054. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  92055. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  92056. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  92057. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  92058. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  92059. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  92060. if (this.glType !== 0) {
  92061. BABYLON.Tools.Error("only compressed formats currently supported");
  92062. return;
  92063. }
  92064. else {
  92065. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  92066. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  92067. }
  92068. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  92069. BABYLON.Tools.Error("only 2D textures currently supported");
  92070. return;
  92071. }
  92072. if (this.numberOfArrayElements !== 0) {
  92073. BABYLON.Tools.Error("texture arrays not currently supported");
  92074. return;
  92075. }
  92076. if (this.numberOfFaces !== facesExpected) {
  92077. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  92078. return;
  92079. }
  92080. // we now have a completely validated file, so could use existence of loadType as success
  92081. // would need to make this more elaborate & adjust checks above to support more than one load type
  92082. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  92083. }
  92084. // not as fast hardware based, but will probably never need to use
  92085. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  92086. return ((val & 0xFF) << 24)
  92087. | ((val & 0xFF00) << 8)
  92088. | ((val >> 8) & 0xFF00)
  92089. | ((val >> 24) & 0xFF);
  92090. };
  92091. /**
  92092. * Uploads KTX content to a Babylon Texture.
  92093. * It is assumed that the texture has already been created & is currently bound
  92094. * @hidden
  92095. */
  92096. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  92097. switch (this.loadType) {
  92098. case KhronosTextureContainer.COMPRESSED_2D:
  92099. this._upload2DCompressedLevels(texture, loadMipmaps);
  92100. break;
  92101. case KhronosTextureContainer.TEX_2D:
  92102. case KhronosTextureContainer.COMPRESSED_3D:
  92103. case KhronosTextureContainer.TEX_3D:
  92104. }
  92105. };
  92106. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  92107. // initialize width & height for level 1
  92108. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  92109. var width = this.pixelWidth;
  92110. var height = this.pixelHeight;
  92111. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  92112. for (var level = 0; level < mipmapCount; level++) {
  92113. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  92114. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  92115. for (var face = 0; face < this.numberOfFaces; face++) {
  92116. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  92117. var engine = texture.getEngine();
  92118. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  92119. dataOffset += imageSize; // add size of the image for the next face/mipmap
  92120. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  92121. }
  92122. width = Math.max(1.0, width * 0.5);
  92123. height = Math.max(1.0, height * 0.5);
  92124. }
  92125. };
  92126. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  92127. // load types
  92128. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  92129. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  92130. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  92131. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  92132. return KhronosTextureContainer;
  92133. }());
  92134. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  92135. })(BABYLON || (BABYLON = {}));
  92136. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  92137. var BABYLON;
  92138. (function (BABYLON) {
  92139. /**
  92140. * Implementation of the KTX Texture Loader.
  92141. */
  92142. var KTXTextureLoader = /** @class */ (function () {
  92143. function KTXTextureLoader() {
  92144. /**
  92145. * Defines wether the loader supports cascade loading the different faces.
  92146. */
  92147. this.supportCascades = false;
  92148. }
  92149. /**
  92150. * This returns if the loader support the current file information.
  92151. * @param extension defines the file extension of the file being loaded
  92152. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92153. * @param fallback defines the fallback internal texture if any
  92154. * @param isBase64 defines whether the texture is encoded as a base64
  92155. * @param isBuffer defines whether the texture data are stored as a buffer
  92156. * @returns true if the loader can load the specified file
  92157. */
  92158. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92159. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  92160. return true;
  92161. }
  92162. return false;
  92163. };
  92164. /**
  92165. * Transform the url before loading if required.
  92166. * @param rootUrl the url of the texture
  92167. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92168. * @returns the transformed texture
  92169. */
  92170. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92171. var lastDot = rootUrl.lastIndexOf('.');
  92172. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  92173. };
  92174. /**
  92175. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92176. * @param rootUrl the url of the texture
  92177. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92178. * @returns the fallback texture
  92179. */
  92180. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92181. // remove the format appended to the rootUrl in the original createCubeTexture call.
  92182. var exp = new RegExp("" + textureFormatInUse + "$");
  92183. return rootUrl.replace(exp, "");
  92184. };
  92185. /**
  92186. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92187. * @param data contains the texture data
  92188. * @param texture defines the BabylonJS internal texture
  92189. * @param createPolynomials will be true if polynomials have been requested
  92190. * @param onLoad defines the callback to trigger once the texture is ready
  92191. * @param onError defines the callback to trigger in case of error
  92192. */
  92193. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92194. if (Array.isArray(data)) {
  92195. return;
  92196. }
  92197. var engine = texture.getEngine();
  92198. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  92199. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  92200. engine._unpackFlipY(true);
  92201. ktx.uploadLevels(texture, texture.generateMipMaps);
  92202. texture.width = ktx.pixelWidth;
  92203. texture.height = ktx.pixelHeight;
  92204. engine._setCubeMapTextureParams(loadMipmap);
  92205. texture.isReady = true;
  92206. };
  92207. /**
  92208. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92209. * @param data contains the texture data
  92210. * @param texture defines the BabylonJS internal texture
  92211. * @param callback defines the method to call once ready to upload
  92212. */
  92213. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  92214. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  92215. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  92216. ktx.uploadLevels(texture, texture.generateMipMaps);
  92217. });
  92218. };
  92219. return KTXTextureLoader;
  92220. }());
  92221. // Register the loader.
  92222. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  92223. })(BABYLON || (BABYLON = {}));
  92224. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  92225. var BABYLON;
  92226. (function (BABYLON) {
  92227. /**
  92228. * Sets of helpers addressing the serialization and deserialization of environment texture
  92229. * stored in a BabylonJS env file.
  92230. * Those files are usually stored as .env files.
  92231. */
  92232. var EnvironmentTextureTools = /** @class */ (function () {
  92233. function EnvironmentTextureTools() {
  92234. }
  92235. /**
  92236. * Gets the environment info from an env file.
  92237. * @param data The array buffer containing the .env bytes.
  92238. * @returns the environment file info (the json header) if successfully parsed.
  92239. */
  92240. EnvironmentTextureTools.GetEnvInfo = function (data) {
  92241. var dataView = new DataView(data);
  92242. var pos = 0;
  92243. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  92244. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  92245. BABYLON.Tools.Error('Not a babylon environment map');
  92246. return null;
  92247. }
  92248. }
  92249. // Read json manifest - collect characters up to null terminator
  92250. var manifestString = '';
  92251. var charCode = 0x00;
  92252. while ((charCode = dataView.getUint8(pos++))) {
  92253. manifestString += String.fromCharCode(charCode);
  92254. }
  92255. var manifest = JSON.parse(manifestString);
  92256. if (manifest.specular) {
  92257. // Extend the header with the position of the payload.
  92258. manifest.specular.specularDataPosition = pos;
  92259. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  92260. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  92261. }
  92262. return manifest;
  92263. };
  92264. /**
  92265. * Creates an environment texture from a loaded cube texture.
  92266. * @param texture defines the cube texture to convert in env file
  92267. * @return a promise containing the environment data if succesfull.
  92268. */
  92269. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  92270. var _this = this;
  92271. var internalTexture = texture.getInternalTexture();
  92272. if (!internalTexture) {
  92273. return Promise.reject("The cube texture is invalid.");
  92274. }
  92275. if (!texture._prefiltered) {
  92276. return Promise.reject("The cube texture is invalid (not prefiltered).");
  92277. }
  92278. var engine = internalTexture.getEngine();
  92279. if (engine && engine.premultipliedAlpha) {
  92280. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  92281. }
  92282. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  92283. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  92284. }
  92285. var canvas = engine.getRenderingCanvas();
  92286. if (!canvas) {
  92287. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  92288. }
  92289. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92290. if (!engine.getCaps().textureFloatRender) {
  92291. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92292. if (!engine.getCaps().textureHalfFloatRender) {
  92293. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  92294. }
  92295. }
  92296. var cubeWidth = internalTexture.width;
  92297. var hostingScene = new BABYLON.Scene(engine);
  92298. var specularTextures = {};
  92299. var promises = [];
  92300. // Read and collect all mipmaps data from the cube.
  92301. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  92302. mipmapsCount = Math.round(mipmapsCount);
  92303. var _loop_1 = function (i) {
  92304. var faceWidth = Math.pow(2, mipmapsCount - i);
  92305. var _loop_2 = function (face) {
  92306. var data = texture.readPixels(face, i);
  92307. // Creates a temp texture with the face data.
  92308. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  92309. // And rgbdEncode them.
  92310. var promise = new Promise(function (resolve, reject) {
  92311. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  92312. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92313. rgbdPostProcess.onApply = function (effect) {
  92314. effect._bindTexture("textureSampler", tempTexture);
  92315. };
  92316. // As the process needs to happen on the main canvas, keep track of the current size
  92317. var currentW = engine.getRenderWidth();
  92318. var currentH = engine.getRenderHeight();
  92319. // Set the desired size for the texture
  92320. engine.setSize(faceWidth, faceWidth);
  92321. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  92322. // Reading datas from WebGL
  92323. BABYLON.Tools.ToBlob(canvas, function (blob) {
  92324. var fileReader = new FileReader();
  92325. fileReader.onload = function (event) {
  92326. var arrayBuffer = event.target.result;
  92327. specularTextures[i * 6 + face] = arrayBuffer;
  92328. resolve();
  92329. };
  92330. fileReader.readAsArrayBuffer(blob);
  92331. });
  92332. // Reapply the previous canvas size
  92333. engine.setSize(currentW, currentH);
  92334. });
  92335. });
  92336. promises.push(promise);
  92337. };
  92338. // All faces of the cube.
  92339. for (var face = 0; face < 6; face++) {
  92340. _loop_2(face);
  92341. }
  92342. };
  92343. for (var i = 0; i <= mipmapsCount; i++) {
  92344. _loop_1(i);
  92345. }
  92346. // Once all the textures haves been collected as RGBD stored in PNGs
  92347. return Promise.all(promises).then(function () {
  92348. // We can delete the hosting scene keeping track of all the creation objects
  92349. hostingScene.dispose();
  92350. // Creates the json header for the env texture
  92351. var info = {
  92352. version: 1,
  92353. width: cubeWidth,
  92354. irradiance: _this._CreateEnvTextureIrradiance(texture),
  92355. specular: {
  92356. mipmaps: [],
  92357. lodGenerationScale: texture.lodGenerationScale
  92358. }
  92359. };
  92360. // Sets the specular image data information
  92361. var position = 0;
  92362. for (var i = 0; i <= mipmapsCount; i++) {
  92363. for (var face = 0; face < 6; face++) {
  92364. var byteLength = specularTextures[i * 6 + face].byteLength;
  92365. info.specular.mipmaps.push({
  92366. length: byteLength,
  92367. position: position
  92368. });
  92369. position += byteLength;
  92370. }
  92371. }
  92372. // Encode the JSON as an array buffer
  92373. var infoString = JSON.stringify(info);
  92374. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  92375. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  92376. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  92377. infoView[i] = infoString.charCodeAt(i);
  92378. }
  92379. // Ends up with a null terminator for easier parsing
  92380. infoView[infoString.length] = 0x00;
  92381. // Computes the final required size and creates the storage
  92382. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  92383. var finalBuffer = new ArrayBuffer(totalSize);
  92384. var finalBufferView = new Uint8Array(finalBuffer);
  92385. var dataView = new DataView(finalBuffer);
  92386. // Copy the magic bytes identifying the file in
  92387. var pos = 0;
  92388. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  92389. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  92390. }
  92391. // Add the json info
  92392. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  92393. pos += infoBuffer.byteLength;
  92394. // Finally inserts the texture data
  92395. for (var i = 0; i <= mipmapsCount; i++) {
  92396. for (var face = 0; face < 6; face++) {
  92397. var dataBuffer = specularTextures[i * 6 + face];
  92398. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  92399. pos += dataBuffer.byteLength;
  92400. }
  92401. }
  92402. // Voila
  92403. return finalBuffer;
  92404. });
  92405. };
  92406. /**
  92407. * Creates a JSON representation of the spherical data.
  92408. * @param texture defines the texture containing the polynomials
  92409. * @return the JSON representation of the spherical info
  92410. */
  92411. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  92412. var polynmials = texture.sphericalPolynomial;
  92413. if (polynmials == null) {
  92414. return null;
  92415. }
  92416. return {
  92417. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  92418. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  92419. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  92420. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  92421. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  92422. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  92423. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  92424. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  92425. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  92426. };
  92427. };
  92428. /**
  92429. * Uploads the texture info contained in the env file to the GPU.
  92430. * @param texture defines the internal texture to upload to
  92431. * @param arrayBuffer defines the buffer cotaining the data to load
  92432. * @param info defines the texture info retrieved through the GetEnvInfo method
  92433. * @returns a promise
  92434. */
  92435. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  92436. if (info.version !== 1) {
  92437. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  92438. }
  92439. var specularInfo = info.specular;
  92440. if (!specularInfo) {
  92441. // Nothing else parsed so far
  92442. return Promise.resolve();
  92443. }
  92444. // Double checks the enclosed info
  92445. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  92446. mipmapsCount = Math.round(mipmapsCount) + 1;
  92447. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  92448. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  92449. }
  92450. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  92451. var imageData = new Array(mipmapsCount);
  92452. for (var i = 0; i < mipmapsCount; i++) {
  92453. imageData[i] = new Array(6);
  92454. for (var face = 0; face < 6; face++) {
  92455. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  92456. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  92457. }
  92458. }
  92459. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  92460. };
  92461. /**
  92462. * Uploads the levels of image data to the GPU.
  92463. * @param texture defines the internal texture to upload to
  92464. * @param imageData defines the array buffer views of image data [mipmap][face]
  92465. * @returns a promise
  92466. */
  92467. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  92468. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  92469. throw new Error("Texture size must be a power of two");
  92470. }
  92471. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  92472. // Gets everything ready.
  92473. var engine = texture.getEngine();
  92474. var expandTexture = false;
  92475. var generateNonLODTextures = false;
  92476. var rgbdPostProcess = null;
  92477. var cubeRtt = null;
  92478. var lodTextures = null;
  92479. var caps = engine.getCaps();
  92480. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  92481. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92482. texture.generateMipMaps = true;
  92483. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  92484. // Add extra process if texture lod is not supported
  92485. if (!caps.textureLOD) {
  92486. expandTexture = false;
  92487. generateNonLODTextures = true;
  92488. lodTextures = {};
  92489. }
  92490. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  92491. else if (engine.webGLVersion < 2) {
  92492. expandTexture = false;
  92493. }
  92494. // If half float available we can uncompress the texture
  92495. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  92496. expandTexture = true;
  92497. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92498. }
  92499. // If full float available we can uncompress the texture
  92500. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  92501. expandTexture = true;
  92502. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92503. }
  92504. // Expand the texture if possible
  92505. if (expandTexture) {
  92506. // Simply run through the decode PP
  92507. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  92508. texture._isRGBD = false;
  92509. texture.invertY = false;
  92510. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  92511. generateDepthBuffer: false,
  92512. generateMipMaps: true,
  92513. generateStencilBuffer: false,
  92514. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  92515. type: texture.type,
  92516. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  92517. });
  92518. }
  92519. else {
  92520. texture._isRGBD = true;
  92521. texture.invertY = true;
  92522. // In case of missing support, applies the same patch than DDS files.
  92523. if (generateNonLODTextures) {
  92524. var mipSlices = 3;
  92525. var scale = texture._lodGenerationScale;
  92526. var offset = texture._lodGenerationOffset;
  92527. for (var i = 0; i < mipSlices; i++) {
  92528. //compute LOD from even spacing in smoothness (matching shader calculation)
  92529. var smoothness = i / (mipSlices - 1);
  92530. var roughness = 1 - smoothness;
  92531. var minLODIndex = offset; // roughness = 0
  92532. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  92533. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  92534. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  92535. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  92536. glTextureFromLod.isCube = true;
  92537. glTextureFromLod.invertY = true;
  92538. glTextureFromLod.generateMipMaps = false;
  92539. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  92540. // Wrap in a base texture for easy binding.
  92541. var lodTexture = new BABYLON.BaseTexture(null);
  92542. lodTexture.isCube = true;
  92543. lodTexture._texture = glTextureFromLod;
  92544. lodTextures[mipmapIndex] = lodTexture;
  92545. switch (i) {
  92546. case 0:
  92547. texture._lodTextureLow = lodTexture;
  92548. break;
  92549. case 1:
  92550. texture._lodTextureMid = lodTexture;
  92551. break;
  92552. case 2:
  92553. texture._lodTextureHigh = lodTexture;
  92554. break;
  92555. }
  92556. }
  92557. }
  92558. }
  92559. var promises = [];
  92560. var _loop_3 = function (i) {
  92561. var _loop_4 = function (face) {
  92562. // Constructs an image element from image data
  92563. var bytes = imageData[i][face];
  92564. var blob = new Blob([bytes], { type: 'image/png' });
  92565. var url = URL.createObjectURL(blob);
  92566. var image = new Image();
  92567. image.src = url;
  92568. // Enqueue promise to upload to the texture.
  92569. var promise = new Promise(function (resolve, reject) {
  92570. image.onload = function () {
  92571. if (expandTexture) {
  92572. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  92573. reject(message);
  92574. }, image);
  92575. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92576. // Uncompress the data to a RTT
  92577. rgbdPostProcess.onApply = function (effect) {
  92578. effect._bindTexture("textureSampler", tempTexture_1);
  92579. effect.setFloat2("scale", 1, 1);
  92580. };
  92581. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  92582. // Cleanup
  92583. engine.restoreDefaultFramebuffer();
  92584. tempTexture_1.dispose();
  92585. window.URL.revokeObjectURL(url);
  92586. resolve();
  92587. });
  92588. }
  92589. else {
  92590. engine._uploadImageToTexture(texture, image, face, i);
  92591. // Upload the face to the non lod texture support
  92592. if (generateNonLODTextures) {
  92593. var lodTexture = lodTextures[i];
  92594. if (lodTexture) {
  92595. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  92596. }
  92597. }
  92598. resolve();
  92599. }
  92600. };
  92601. image.onerror = function (error) {
  92602. reject(error);
  92603. };
  92604. });
  92605. promises.push(promise);
  92606. };
  92607. // All faces
  92608. for (var face = 0; face < 6; face++) {
  92609. _loop_4(face);
  92610. }
  92611. };
  92612. // All mipmaps up to provided number of images
  92613. for (var i = 0; i < imageData.length; i++) {
  92614. _loop_3(i);
  92615. }
  92616. // Fill remaining mipmaps with black textures.
  92617. if (imageData.length < mipmapsCount) {
  92618. var data = void 0;
  92619. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  92620. var dataLength = size * size * 4;
  92621. switch (texture.type) {
  92622. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  92623. data = new Uint8Array(dataLength);
  92624. break;
  92625. }
  92626. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  92627. data = new Uint16Array(dataLength);
  92628. break;
  92629. }
  92630. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  92631. data = new Float32Array(dataLength);
  92632. break;
  92633. }
  92634. }
  92635. for (var i = imageData.length; i < mipmapsCount; i++) {
  92636. for (var face = 0; face < 6; face++) {
  92637. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  92638. }
  92639. }
  92640. }
  92641. // Once all done, finishes the cleanup and return
  92642. return Promise.all(promises).then(function () {
  92643. // Release temp RTT.
  92644. if (cubeRtt) {
  92645. engine._releaseFramebufferObjects(cubeRtt);
  92646. cubeRtt._swapAndDie(texture);
  92647. }
  92648. // Release temp Post Process.
  92649. if (rgbdPostProcess) {
  92650. rgbdPostProcess.dispose();
  92651. }
  92652. // Flag internal texture as ready in case they are in use.
  92653. if (generateNonLODTextures) {
  92654. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  92655. texture._lodTextureHigh._texture.isReady = true;
  92656. }
  92657. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  92658. texture._lodTextureMid._texture.isReady = true;
  92659. }
  92660. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  92661. texture._lodTextureLow._texture.isReady = true;
  92662. }
  92663. }
  92664. });
  92665. };
  92666. /**
  92667. * Uploads spherical polynomials information to the texture.
  92668. * @param texture defines the texture we are trying to upload the information to
  92669. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  92670. */
  92671. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  92672. if (info.version !== 1) {
  92673. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  92674. }
  92675. var irradianceInfo = info.irradiance;
  92676. if (!irradianceInfo) {
  92677. return;
  92678. }
  92679. var sp = new BABYLON.SphericalPolynomial();
  92680. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  92681. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  92682. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  92683. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  92684. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  92685. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  92686. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  92687. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  92688. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  92689. texture._sphericalPolynomial = sp;
  92690. };
  92691. /**
  92692. * Magic number identifying the env file.
  92693. */
  92694. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  92695. return EnvironmentTextureTools;
  92696. }());
  92697. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  92698. })(BABYLON || (BABYLON = {}));
  92699. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  92700. var BABYLON;
  92701. (function (BABYLON) {
  92702. /**
  92703. * Implementation of the ENV Texture Loader.
  92704. */
  92705. var ENVTextureLoader = /** @class */ (function () {
  92706. function ENVTextureLoader() {
  92707. /**
  92708. * Defines wether the loader supports cascade loading the different faces.
  92709. */
  92710. this.supportCascades = false;
  92711. }
  92712. /**
  92713. * This returns if the loader support the current file information.
  92714. * @param extension defines the file extension of the file being loaded
  92715. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92716. * @param fallback defines the fallback internal texture if any
  92717. * @param isBase64 defines whether the texture is encoded as a base64
  92718. * @param isBuffer defines whether the texture data are stored as a buffer
  92719. * @returns true if the loader can load the specified file
  92720. */
  92721. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92722. return extension.indexOf(".env") === 0;
  92723. };
  92724. /**
  92725. * Transform the url before loading if required.
  92726. * @param rootUrl the url of the texture
  92727. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92728. * @returns the transformed texture
  92729. */
  92730. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92731. return rootUrl;
  92732. };
  92733. /**
  92734. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92735. * @param rootUrl the url of the texture
  92736. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92737. * @returns the fallback texture
  92738. */
  92739. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92740. return null;
  92741. };
  92742. /**
  92743. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92744. * @param data contains the texture data
  92745. * @param texture defines the BabylonJS internal texture
  92746. * @param createPolynomials will be true if polynomials have been requested
  92747. * @param onLoad defines the callback to trigger once the texture is ready
  92748. * @param onError defines the callback to trigger in case of error
  92749. */
  92750. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92751. if (Array.isArray(data)) {
  92752. return;
  92753. }
  92754. data = data;
  92755. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  92756. if (info) {
  92757. texture.width = info.width;
  92758. texture.height = info.width;
  92759. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  92760. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  92761. texture.isReady = true;
  92762. if (onLoad) {
  92763. onLoad();
  92764. }
  92765. });
  92766. }
  92767. else if (onError) {
  92768. onError("Can not parse the environment file", null);
  92769. }
  92770. };
  92771. /**
  92772. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92773. * @param data contains the texture data
  92774. * @param texture defines the BabylonJS internal texture
  92775. * @param callback defines the method to call once ready to upload
  92776. */
  92777. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  92778. throw ".env not supported in 2d.";
  92779. };
  92780. return ENVTextureLoader;
  92781. }());
  92782. // Register the loader.
  92783. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  92784. })(BABYLON || (BABYLON = {}));
  92785. //# sourceMappingURL=babylon.envTextureLoader.js.map
  92786. var BABYLON;
  92787. (function (BABYLON) {
  92788. /**
  92789. * Renders a layer on top of an existing scene
  92790. */
  92791. var UtilityLayerRenderer = /** @class */ (function () {
  92792. /**
  92793. * Instantiates a UtilityLayerRenderer
  92794. * @param originalScene the original scene that will be rendered on top of
  92795. */
  92796. function UtilityLayerRenderer(
  92797. /** the original scene that will be rendered on top of */
  92798. originalScene) {
  92799. var _this = this;
  92800. this.originalScene = originalScene;
  92801. this._pointerCaptures = {};
  92802. this._lastPointerEvents = {};
  92803. /**
  92804. * If the utility layer should automatically be rendered on top of existing scene
  92805. */
  92806. this.shouldRender = true;
  92807. /**
  92808. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  92809. */
  92810. this.onlyCheckPointerDownEvents = true;
  92811. /**
  92812. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  92813. */
  92814. this.processAllEvents = false;
  92815. /**
  92816. * Observable raised when the pointer move from the utility layer scene to the main scene
  92817. */
  92818. this.onPointerOutObservable = new BABYLON.Observable();
  92819. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  92820. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  92821. this.utilityLayerScene._allowPostProcessClearColor = false;
  92822. originalScene.getEngine().scenes.pop();
  92823. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  92824. this.utilityLayerScene.detachControl();
  92825. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  92826. if (!_this.processAllEvents) {
  92827. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  92828. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  92829. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  92830. return;
  92831. }
  92832. }
  92833. var pointerEvent = (prePointerInfo.event);
  92834. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  92835. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92836. return;
  92837. }
  92838. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  92839. if (!prePointerInfo.ray && utilityScenePick) {
  92840. prePointerInfo.ray = utilityScenePick.ray;
  92841. }
  92842. // always fire the prepointer oversvable
  92843. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  92844. // allow every non pointer down event to flow to the utility layer
  92845. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  92846. if (!prePointerInfo.skipOnPointerObservable) {
  92847. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92848. }
  92849. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  92850. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92851. }
  92852. return;
  92853. }
  92854. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  92855. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  92856. if (utilityScenePick && utilityScenePick.hit) {
  92857. if (!prePointerInfo.skipOnPointerObservable) {
  92858. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92859. }
  92860. prePointerInfo.skipOnPointerObservable = true;
  92861. }
  92862. }
  92863. else {
  92864. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  92865. var pointerEvent_1 = (prePointerInfo.event);
  92866. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  92867. if (originalScenePick && utilityScenePick) {
  92868. // No pick in utility scene
  92869. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  92870. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92871. // We touched an utility mesh present in the main scene
  92872. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92873. prePointerInfo.skipOnPointerObservable = true;
  92874. }
  92875. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92876. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  92877. }
  92878. }
  92879. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  92880. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  92881. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  92882. // If a previous utility layer set this, do not unset this
  92883. if (!prePointerInfo.skipOnPointerObservable) {
  92884. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  92885. }
  92886. }
  92887. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  92888. // We have a pick in both scenes but main is closer than utility
  92889. // We touched an utility mesh present in the main scene
  92890. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92891. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92892. prePointerInfo.skipOnPointerObservable = true;
  92893. }
  92894. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  92895. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  92896. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  92897. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  92898. }
  92899. }
  92900. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  92901. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  92902. }
  92903. }
  92904. }
  92905. });
  92906. // Render directly on top of existing scene without clearing
  92907. this.utilityLayerScene.autoClear = false;
  92908. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  92909. if (_this.shouldRender) {
  92910. _this.render();
  92911. }
  92912. });
  92913. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  92914. _this.dispose();
  92915. });
  92916. this._updateCamera();
  92917. }
  92918. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  92919. /**
  92920. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  92921. */
  92922. get: function () {
  92923. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  92924. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92925. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92926. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92927. });
  92928. }
  92929. return UtilityLayerRenderer._DefaultUtilityLayer;
  92930. },
  92931. enumerable: true,
  92932. configurable: true
  92933. });
  92934. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  92935. /**
  92936. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  92937. */
  92938. get: function () {
  92939. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  92940. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92941. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  92942. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92943. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92944. });
  92945. }
  92946. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  92947. },
  92948. enumerable: true,
  92949. configurable: true
  92950. });
  92951. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  92952. if (!prePointerInfo.skipOnPointerObservable) {
  92953. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  92954. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  92955. }
  92956. };
  92957. /**
  92958. * Renders the utility layers scene on top of the original scene
  92959. */
  92960. UtilityLayerRenderer.prototype.render = function () {
  92961. this._updateCamera();
  92962. if (this.utilityLayerScene.activeCamera) {
  92963. // Set the camera's scene to utility layers scene
  92964. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  92965. var camera = this.utilityLayerScene.activeCamera;
  92966. camera._scene = this.utilityLayerScene;
  92967. if (camera.leftCamera) {
  92968. camera.leftCamera._scene = this.utilityLayerScene;
  92969. }
  92970. if (camera.rightCamera) {
  92971. camera.rightCamera._scene = this.utilityLayerScene;
  92972. }
  92973. this.utilityLayerScene.render(false);
  92974. // Reset camera's scene back to original
  92975. camera._scene = oldScene;
  92976. if (camera.leftCamera) {
  92977. camera.leftCamera._scene = oldScene;
  92978. }
  92979. if (camera.rightCamera) {
  92980. camera.rightCamera._scene = oldScene;
  92981. }
  92982. }
  92983. };
  92984. /**
  92985. * Disposes of the renderer
  92986. */
  92987. UtilityLayerRenderer.prototype.dispose = function () {
  92988. this.onPointerOutObservable.clear();
  92989. if (this._afterRenderObserver) {
  92990. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  92991. }
  92992. if (this._sceneDisposeObserver) {
  92993. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  92994. }
  92995. if (this._originalPointerObserver) {
  92996. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  92997. }
  92998. this.utilityLayerScene.dispose();
  92999. };
  93000. UtilityLayerRenderer.prototype._updateCamera = function () {
  93001. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  93002. };
  93003. UtilityLayerRenderer._DefaultUtilityLayer = null;
  93004. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  93005. return UtilityLayerRenderer;
  93006. }());
  93007. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  93008. })(BABYLON || (BABYLON = {}));
  93009. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  93010. //# sourceMappingURL=babylon.behavior.js.map
  93011. var BABYLON;
  93012. (function (BABYLON) {
  93013. /**
  93014. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  93015. */
  93016. var PointerDragBehavior = /** @class */ (function () {
  93017. /**
  93018. * Creates a pointer drag behavior that can be attached to a mesh
  93019. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  93020. */
  93021. function PointerDragBehavior(options) {
  93022. /**
  93023. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  93024. */
  93025. this.maxDragAngle = 0;
  93026. /**
  93027. * @hidden
  93028. */
  93029. this._useAlternatePickedPointAboveMaxDragAngle = false;
  93030. /**
  93031. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93032. */
  93033. this.currentDraggingPointerID = -1;
  93034. /**
  93035. * If the behavior is currently in a dragging state
  93036. */
  93037. this.dragging = false;
  93038. /**
  93039. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  93040. */
  93041. this.dragDeltaRatio = 0.2;
  93042. /**
  93043. * If the drag plane orientation should be updated during the dragging (Default: true)
  93044. */
  93045. this.updateDragPlane = true;
  93046. // Debug mode will display drag planes to help visualize behavior
  93047. this._debugMode = false;
  93048. this._moving = false;
  93049. /**
  93050. * Fires each time the attached mesh is dragged with the pointer
  93051. * * delta between last drag position and current drag position in world space
  93052. * * dragDistance along the drag axis
  93053. * * dragPlaneNormal normal of the current drag plane used during the drag
  93054. * * dragPlanePoint in world space where the drag intersects the drag plane
  93055. */
  93056. this.onDragObservable = new BABYLON.Observable();
  93057. /**
  93058. * Fires each time a drag begins (eg. mouse down on mesh)
  93059. */
  93060. this.onDragStartObservable = new BABYLON.Observable();
  93061. /**
  93062. * Fires each time a drag ends (eg. mouse release after drag)
  93063. */
  93064. this.onDragEndObservable = new BABYLON.Observable();
  93065. /**
  93066. * If the attached mesh should be moved when dragged
  93067. */
  93068. this.moveAttached = true;
  93069. /**
  93070. * If the drag behavior will react to drag events (Default: true)
  93071. */
  93072. this.enabled = true;
  93073. /**
  93074. * If camera controls should be detached during the drag
  93075. */
  93076. this.detachCameraControls = true;
  93077. /**
  93078. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  93079. */
  93080. this.useObjectOrienationForDragging = true;
  93081. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  93082. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  93083. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  93084. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  93085. this._attachedElement = null;
  93086. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  93087. this._lastPointerRay = {};
  93088. this._dragDelta = new BABYLON.Vector3();
  93089. // Variables to avoid instantiation in the below method
  93090. this._pointA = new BABYLON.Vector3(0, 0, 0);
  93091. this._pointB = new BABYLON.Vector3(0, 0, 0);
  93092. this._pointC = new BABYLON.Vector3(0, 0, 0);
  93093. this._lineA = new BABYLON.Vector3(0, 0, 0);
  93094. this._lineB = new BABYLON.Vector3(0, 0, 0);
  93095. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  93096. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  93097. this._options = options ? options : {};
  93098. var optionCount = 0;
  93099. if (this._options.dragAxis) {
  93100. optionCount++;
  93101. }
  93102. if (this._options.dragPlaneNormal) {
  93103. optionCount++;
  93104. }
  93105. if (optionCount > 1) {
  93106. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  93107. }
  93108. }
  93109. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  93110. /**
  93111. * The name of the behavior
  93112. */
  93113. get: function () {
  93114. return "PointerDrag";
  93115. },
  93116. enumerable: true,
  93117. configurable: true
  93118. });
  93119. /**
  93120. * Initializes the behavior
  93121. */
  93122. PointerDragBehavior.prototype.init = function () { };
  93123. /**
  93124. * Attaches the drag behavior the passed in mesh
  93125. * @param ownerNode The mesh that will be dragged around once attached
  93126. */
  93127. PointerDragBehavior.prototype.attach = function (ownerNode) {
  93128. var _this = this;
  93129. this._scene = ownerNode.getScene();
  93130. this._attachedNode = ownerNode;
  93131. // Initialize drag plane to not interfere with existing scene
  93132. if (!PointerDragBehavior._planeScene) {
  93133. if (this._debugMode) {
  93134. PointerDragBehavior._planeScene = this._scene;
  93135. }
  93136. else {
  93137. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  93138. PointerDragBehavior._planeScene.detachControl();
  93139. this._scene.getEngine().scenes.pop();
  93140. this._scene.onDisposeObservable.addOnce(function () {
  93141. PointerDragBehavior._planeScene.dispose();
  93142. PointerDragBehavior._planeScene = null;
  93143. });
  93144. }
  93145. }
  93146. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  93147. // State of the drag
  93148. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  93149. var pickPredicate = function (m) {
  93150. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  93151. };
  93152. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93153. if (!_this.enabled) {
  93154. return;
  93155. }
  93156. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93157. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93158. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  93159. }
  93160. }
  93161. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93162. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93163. _this.releaseDrag();
  93164. }
  93165. }
  93166. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93167. var pointerId = pointerInfo.event.pointerId;
  93168. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  93169. if (!_this._lastPointerRay[pointerId]) {
  93170. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  93171. }
  93172. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  93173. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  93174. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  93175. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  93176. _this._moveDrag(pointerInfo.pickInfo.ray);
  93177. }
  93178. }
  93179. }
  93180. });
  93181. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93182. if (_this._moving && _this.moveAttached) {
  93183. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  93184. // Slowly move mesh to avoid jitter
  93185. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  93186. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  93187. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  93188. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  93189. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  93190. }
  93191. });
  93192. };
  93193. PointerDragBehavior.prototype.releaseDrag = function () {
  93194. this.dragging = false;
  93195. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  93196. this.currentDraggingPointerID = -1;
  93197. this._moving = false;
  93198. // Reattach camera controls
  93199. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  93200. this._scene.activeCamera.attachControl(this._attachedElement, true);
  93201. }
  93202. };
  93203. /**
  93204. * Simulates the start of a pointer drag event on the behavior
  93205. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  93206. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  93207. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  93208. */
  93209. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  93210. if (pointerId === void 0) { pointerId = 1; }
  93211. this._startDrag(pointerId, fromRay, startPickedPoint);
  93212. if (this._lastPointerRay[pointerId]) {
  93213. // if there was a last pointer ray drag the object there
  93214. this._moveDrag(this._lastPointerRay[pointerId]);
  93215. }
  93216. };
  93217. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  93218. if (pointerId === void 0) { pointerId = 1; }
  93219. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  93220. return;
  93221. }
  93222. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  93223. // Create start ray from the camera to the object
  93224. if (fromRay) {
  93225. this._startDragRay.direction.copyFrom(fromRay.direction);
  93226. this._startDragRay.origin.copyFrom(fromRay.origin);
  93227. }
  93228. else {
  93229. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  93230. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  93231. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  93232. }
  93233. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  93234. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  93235. if (pickedPoint) {
  93236. this.dragging = true;
  93237. this.currentDraggingPointerID = pointerId;
  93238. this.lastDragPosition.copyFrom(pickedPoint);
  93239. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  93240. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  93241. // Detatch camera controls
  93242. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  93243. if (this._scene.activeCamera.inputs.attachedElement) {
  93244. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  93245. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  93246. }
  93247. else {
  93248. this._attachedElement = null;
  93249. }
  93250. }
  93251. }
  93252. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  93253. };
  93254. PointerDragBehavior.prototype._moveDrag = function (ray) {
  93255. this._moving = true;
  93256. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  93257. if (pickedPoint) {
  93258. if (this.updateDragPlane) {
  93259. this._updateDragPlanePosition(ray, pickedPoint);
  93260. }
  93261. var dragLength = 0;
  93262. // depending on the drag mode option drag accordingly
  93263. if (this._options.dragAxis) {
  93264. // Convert local drag axis to world
  93265. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  93266. // Project delta drag from the drag plane onto the drag axis
  93267. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  93268. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  93269. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  93270. }
  93271. else {
  93272. dragLength = this._dragDelta.length();
  93273. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  93274. }
  93275. this._targetPosition.addInPlace(this._dragDelta);
  93276. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  93277. this.lastDragPosition.copyFrom(pickedPoint);
  93278. }
  93279. };
  93280. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  93281. var _this = this;
  93282. if (!ray) {
  93283. return null;
  93284. }
  93285. // Calculate angle between plane normal and ray
  93286. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  93287. // Correct if ray is casted from oposite side
  93288. if (angle > Math.PI / 2) {
  93289. angle = Math.PI - angle;
  93290. }
  93291. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  93292. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  93293. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  93294. // Invert ray direction along the towards object axis
  93295. this._tmpVector.copyFrom(ray.direction);
  93296. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  93297. this._alternatePickedPoint.normalize();
  93298. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  93299. this._tmpVector.addInPlace(this._alternatePickedPoint);
  93300. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  93301. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  93302. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  93303. this._alternatePickedPoint.addInPlace(this._tmpVector);
  93304. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  93305. return this._alternatePickedPoint;
  93306. }
  93307. else {
  93308. return null;
  93309. }
  93310. }
  93311. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  93312. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  93313. return pickResult.pickedPoint;
  93314. }
  93315. else {
  93316. return null;
  93317. }
  93318. };
  93319. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  93320. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  93321. this._pointA.copyFrom(dragPlanePosition);
  93322. if (this._options.dragAxis) {
  93323. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  93324. // Calculate plane normal in direction of camera but perpendicular to drag axis
  93325. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  93326. ray.origin.subtractToRef(this._pointA, this._pointC);
  93327. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  93328. // Get perpendicular line from direction to camera and drag axis
  93329. this._pointB.subtractToRef(this._pointA, this._lineA);
  93330. this._pointC.subtractToRef(this._pointA, this._lineB);
  93331. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  93332. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  93333. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  93334. this._lookAt.normalize();
  93335. this._dragPlane.position.copyFrom(this._pointA);
  93336. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  93337. this._dragPlane.lookAt(this._lookAt);
  93338. }
  93339. else if (this._options.dragPlaneNormal) {
  93340. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  93341. this._dragPlane.position.copyFrom(this._pointA);
  93342. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  93343. this._dragPlane.lookAt(this._lookAt);
  93344. }
  93345. else {
  93346. this._dragPlane.position.copyFrom(this._pointA);
  93347. this._dragPlane.lookAt(ray.origin);
  93348. }
  93349. this._dragPlane.computeWorldMatrix(true);
  93350. };
  93351. /**
  93352. * Detaches the behavior from the mesh
  93353. */
  93354. PointerDragBehavior.prototype.detach = function () {
  93355. if (this._pointerObserver) {
  93356. this._scene.onPointerObservable.remove(this._pointerObserver);
  93357. }
  93358. if (this._beforeRenderObserver) {
  93359. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  93360. }
  93361. };
  93362. return PointerDragBehavior;
  93363. }());
  93364. BABYLON.PointerDragBehavior = PointerDragBehavior;
  93365. })(BABYLON || (BABYLON = {}));
  93366. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  93367. var BABYLON;
  93368. (function (BABYLON) {
  93369. /**
  93370. * A behavior that when attached to a mesh will allow the mesh to be scaled
  93371. */
  93372. var MultiPointerScaleBehavior = /** @class */ (function () {
  93373. function MultiPointerScaleBehavior() {
  93374. this._startDistance = 0;
  93375. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  93376. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  93377. this._sceneRenderObserver = null;
  93378. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  93379. this._dragBehaviorA.moveAttached = false;
  93380. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  93381. this._dragBehaviorB.moveAttached = false;
  93382. }
  93383. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  93384. /**
  93385. * The name of the behavior
  93386. */
  93387. get: function () {
  93388. return "MultiPointerScale";
  93389. },
  93390. enumerable: true,
  93391. configurable: true
  93392. });
  93393. /**
  93394. * Initializes the behavior
  93395. */
  93396. MultiPointerScaleBehavior.prototype.init = function () { };
  93397. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  93398. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  93399. };
  93400. /**
  93401. * Attaches the scale behavior the passed in mesh
  93402. * @param ownerNode The mesh that will be scaled around once attached
  93403. */
  93404. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  93405. var _this = this;
  93406. this._ownerNode = ownerNode;
  93407. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  93408. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  93409. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93410. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  93411. _this._dragBehaviorA.releaseDrag();
  93412. }
  93413. else {
  93414. _this._initialScale.copyFrom(ownerNode.scaling);
  93415. _this._startDistance = _this._getCurrentDistance();
  93416. }
  93417. }
  93418. });
  93419. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  93420. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93421. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  93422. _this._dragBehaviorB.releaseDrag();
  93423. }
  93424. else {
  93425. _this._initialScale.copyFrom(ownerNode.scaling);
  93426. _this._startDistance = _this._getCurrentDistance();
  93427. }
  93428. }
  93429. });
  93430. // Once both drag behaviors are active scale based on the distance between the two pointers
  93431. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  93432. behavior.onDragObservable.add(function () {
  93433. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93434. var ratio = _this._getCurrentDistance() / _this._startDistance;
  93435. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  93436. }
  93437. });
  93438. });
  93439. ownerNode.addBehavior(this._dragBehaviorA);
  93440. ownerNode.addBehavior(this._dragBehaviorB);
  93441. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93442. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93443. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93444. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  93445. if (change.length() > 0.01) {
  93446. ownerNode.scaling.addInPlace(change);
  93447. }
  93448. }
  93449. });
  93450. };
  93451. /**
  93452. * Detaches the behavior from the mesh
  93453. */
  93454. MultiPointerScaleBehavior.prototype.detach = function () {
  93455. var _this = this;
  93456. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93457. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  93458. behavior.onDragStartObservable.clear();
  93459. behavior.onDragObservable.clear();
  93460. _this._ownerNode.removeBehavior(behavior);
  93461. });
  93462. };
  93463. return MultiPointerScaleBehavior;
  93464. }());
  93465. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  93466. })(BABYLON || (BABYLON = {}));
  93467. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  93468. var BABYLON;
  93469. (function (BABYLON) {
  93470. /**
  93471. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  93472. */
  93473. var SixDofDragBehavior = /** @class */ (function () {
  93474. function SixDofDragBehavior() {
  93475. this._sceneRenderObserver = null;
  93476. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  93477. this._moving = false;
  93478. this._startingOrientation = new BABYLON.Quaternion();
  93479. /**
  93480. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  93481. */
  93482. this.zDragFactor = 3;
  93483. /**
  93484. * If the behavior is currently in a dragging state
  93485. */
  93486. this.dragging = false;
  93487. /**
  93488. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  93489. */
  93490. this.dragDeltaRatio = 0.2;
  93491. /**
  93492. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93493. */
  93494. this.currentDraggingPointerID = -1;
  93495. /**
  93496. * If camera controls should be detached during the drag
  93497. */
  93498. this.detachCameraControls = true;
  93499. }
  93500. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  93501. /**
  93502. * The name of the behavior
  93503. */
  93504. get: function () {
  93505. return "SixDofDrag";
  93506. },
  93507. enumerable: true,
  93508. configurable: true
  93509. });
  93510. /**
  93511. * Initializes the behavior
  93512. */
  93513. SixDofDragBehavior.prototype.init = function () { };
  93514. /**
  93515. * Attaches the scale behavior the passed in mesh
  93516. * @param ownerNode The mesh that will be scaled around once attached
  93517. */
  93518. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  93519. var _this = this;
  93520. this._ownerNode = ownerNode;
  93521. this._scene = this._ownerNode.getScene();
  93522. if (!SixDofDragBehavior._virtualScene) {
  93523. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  93524. this._scene.getEngine().scenes.pop();
  93525. }
  93526. var pickedMesh = null;
  93527. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  93528. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  93529. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93530. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  93531. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93532. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  93533. var pickPredicate = function (m) {
  93534. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  93535. };
  93536. var attachedElement = null;
  93537. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93538. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93539. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93540. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93541. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93542. }
  93543. pickedMesh = _this._ownerNode;
  93544. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93545. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93546. // Set position and orientation of the controller
  93547. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93548. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93549. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  93550. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93551. pickedMesh.computeWorldMatrix();
  93552. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  93553. if (!pickedMesh.rotationQuaternion) {
  93554. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  93555. }
  93556. var oldParent = pickedMesh.parent;
  93557. pickedMesh.setParent(null);
  93558. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  93559. pickedMesh.setParent(oldParent);
  93560. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93561. // Update state
  93562. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93563. _this.dragging = true;
  93564. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  93565. // Detatch camera controls
  93566. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93567. if (_this._scene.activeCamera.inputs.attachedElement) {
  93568. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  93569. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  93570. }
  93571. else {
  93572. attachedElement = null;
  93573. }
  93574. }
  93575. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93576. }
  93577. }
  93578. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93579. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93580. _this.dragging = false;
  93581. _this._moving = false;
  93582. _this.currentDraggingPointerID = -1;
  93583. pickedMesh = null;
  93584. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93585. // Reattach camera controls
  93586. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93587. _this._scene.activeCamera.attachControl(attachedElement, true);
  93588. }
  93589. }
  93590. }
  93591. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93592. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  93593. var zDragFactor = _this.zDragFactor;
  93594. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93595. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93596. zDragFactor = 0;
  93597. }
  93598. // Calculate controller drag distance in controller space
  93599. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  93600. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93601. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  93602. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93603. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  93604. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  93605. if (_this._virtualDragMesh.position.z < 0) {
  93606. _this._virtualDragMesh.position.z = 0;
  93607. }
  93608. // Update the controller position
  93609. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93610. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93611. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93612. // Move the virtualObjectsPosition into the picked mesh's space if needed
  93613. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93614. if (pickedMesh.parent) {
  93615. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  93616. }
  93617. if (!_this._moving) {
  93618. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  93619. }
  93620. _this._moving = true;
  93621. }
  93622. }
  93623. });
  93624. var tmpQuaternion = new BABYLON.Quaternion();
  93625. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93626. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93627. if (_this.dragging && _this._moving && pickedMesh) {
  93628. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93629. // Slowly move mesh to avoid jitter
  93630. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  93631. // Get change in rotation
  93632. tmpQuaternion.copyFrom(_this._startingOrientation);
  93633. tmpQuaternion.x = -tmpQuaternion.x;
  93634. tmpQuaternion.y = -tmpQuaternion.y;
  93635. tmpQuaternion.z = -tmpQuaternion.z;
  93636. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  93637. // Convert change in rotation to only y axis rotation
  93638. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  93639. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  93640. // Slowly move mesh to avoid jitter
  93641. var oldParent = pickedMesh.parent;
  93642. pickedMesh.setParent(null);
  93643. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  93644. pickedMesh.setParent(oldParent);
  93645. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93646. }
  93647. });
  93648. };
  93649. /**
  93650. * Detaches the behavior from the mesh
  93651. */
  93652. SixDofDragBehavior.prototype.detach = function () {
  93653. if (this._scene) {
  93654. this._scene.onPointerObservable.remove(this._pointerObserver);
  93655. }
  93656. if (this._ownerNode) {
  93657. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93658. }
  93659. if (this._virtualOriginMesh) {
  93660. this._virtualOriginMesh.dispose();
  93661. }
  93662. if (this._virtualDragMesh) {
  93663. this._virtualDragMesh.dispose();
  93664. }
  93665. };
  93666. return SixDofDragBehavior;
  93667. }());
  93668. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  93669. })(BABYLON || (BABYLON = {}));
  93670. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  93671. var BABYLON;
  93672. (function (BABYLON) {
  93673. /**
  93674. * @hidden
  93675. */
  93676. var FaceDirectionInfo = /** @class */ (function () {
  93677. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  93678. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  93679. if (diff === void 0) { diff = 0; }
  93680. if (ignore === void 0) { ignore = false; }
  93681. this.direction = direction;
  93682. this.rotatedDirection = rotatedDirection;
  93683. this.diff = diff;
  93684. this.ignore = ignore;
  93685. }
  93686. return FaceDirectionInfo;
  93687. }());
  93688. /**
  93689. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  93690. */
  93691. var AttachToBoxBehavior = /** @class */ (function () {
  93692. /**
  93693. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  93694. * @param ui The transform node that should be attched to the mesh
  93695. */
  93696. function AttachToBoxBehavior(ui) {
  93697. this.ui = ui;
  93698. /**
  93699. * The name of the behavior
  93700. */
  93701. this.name = "AttachToBoxBehavior";
  93702. /**
  93703. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  93704. */
  93705. this.distanceAwayFromFace = 0.15;
  93706. /**
  93707. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  93708. */
  93709. this.distanceAwayFromBottomOfFace = 0.15;
  93710. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  93711. this._tmpMatrix = new BABYLON.Matrix();
  93712. this._tmpVector = new BABYLON.Vector3();
  93713. this._zeroVector = BABYLON.Vector3.Zero();
  93714. this._lookAtTmpMatrix = new BABYLON.Matrix();
  93715. /* Does nothing */
  93716. }
  93717. /**
  93718. * Initializes the behavior
  93719. */
  93720. AttachToBoxBehavior.prototype.init = function () {
  93721. /* Does nothing */
  93722. };
  93723. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  93724. var _this = this;
  93725. // Go over each face and calculate the angle between the face's normal and targetDirection
  93726. this._faceVectors.forEach(function (v) {
  93727. if (!_this._target.rotationQuaternion) {
  93728. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  93729. }
  93730. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  93731. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  93732. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  93733. });
  93734. // Return the face information of the one with the normal closeset to target direction
  93735. return this._faceVectors.reduce(function (min, p) {
  93736. if (min.ignore) {
  93737. return p;
  93738. }
  93739. else if (p.ignore) {
  93740. return min;
  93741. }
  93742. else {
  93743. return min.diff < p.diff ? min : p;
  93744. }
  93745. }, this._faceVectors[0]);
  93746. };
  93747. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  93748. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  93749. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  93750. this._lookAtTmpMatrix.invert();
  93751. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  93752. };
  93753. /**
  93754. * Attaches the AttachToBoxBehavior to the passed in mesh
  93755. * @param target The mesh that the specified node will be attached to
  93756. */
  93757. AttachToBoxBehavior.prototype.attach = function (target) {
  93758. var _this = this;
  93759. this._target = target;
  93760. this._scene = this._target.getScene();
  93761. // Every frame, update the app bars position
  93762. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93763. if (!_this._scene.activeCamera) {
  93764. return;
  93765. }
  93766. // Find the face closest to the cameras position
  93767. var cameraPos = _this._scene.activeCamera.position;
  93768. if (_this._scene.activeCamera.devicePosition) {
  93769. cameraPos = _this._scene.activeCamera.devicePosition;
  93770. }
  93771. var facing = _this._closestFace(cameraPos.subtract(target.position));
  93772. if (_this._scene.activeCamera.leftCamera) {
  93773. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93774. }
  93775. else {
  93776. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93777. }
  93778. // Get camera up direction
  93779. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  93780. // Ignore faces to not select a parrelel face for the up vector of the UI
  93781. _this._faceVectors.forEach(function (v) {
  93782. if (facing.direction.x && v.direction.x) {
  93783. v.ignore = true;
  93784. }
  93785. if (facing.direction.y && v.direction.y) {
  93786. v.ignore = true;
  93787. }
  93788. if (facing.direction.z && v.direction.z) {
  93789. v.ignore = true;
  93790. }
  93791. });
  93792. var facingUp = _this._closestFace(_this._tmpVector);
  93793. // Unignore faces
  93794. _this._faceVectors.forEach(function (v) {
  93795. v.ignore = false;
  93796. });
  93797. // Position the app bar on that face
  93798. _this.ui.position.copyFrom(target.position);
  93799. if (facing.direction.x) {
  93800. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93801. _this.ui.position.addInPlace(_this._tmpVector);
  93802. }
  93803. if (facing.direction.y) {
  93804. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93805. _this.ui.position.addInPlace(_this._tmpVector);
  93806. }
  93807. if (facing.direction.z) {
  93808. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93809. _this.ui.position.addInPlace(_this._tmpVector);
  93810. }
  93811. // Rotate to be oriented properly to the camera
  93812. if (!_this.ui.rotationQuaternion) {
  93813. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  93814. }
  93815. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  93816. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  93817. // Place ui the correct distance from the bottom of the mesh
  93818. if (facingUp.direction.x) {
  93819. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  93820. }
  93821. if (facingUp.direction.y) {
  93822. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  93823. }
  93824. if (facingUp.direction.z) {
  93825. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  93826. }
  93827. _this.ui.position.addInPlace(_this._tmpVector);
  93828. });
  93829. };
  93830. /**
  93831. * Detaches the behavior from the mesh
  93832. */
  93833. AttachToBoxBehavior.prototype.detach = function () {
  93834. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  93835. };
  93836. return AttachToBoxBehavior;
  93837. }());
  93838. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  93839. })(BABYLON || (BABYLON = {}));
  93840. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  93841. var BABYLON;
  93842. (function (BABYLON) {
  93843. /**
  93844. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  93845. */
  93846. var FadeInOutBehavior = /** @class */ (function () {
  93847. /**
  93848. * Instatiates the FadeInOutBehavior
  93849. */
  93850. function FadeInOutBehavior() {
  93851. var _this = this;
  93852. /**
  93853. * Time in milliseconds to delay before fading in (Default: 0)
  93854. */
  93855. this.delay = 0;
  93856. /**
  93857. * Time in milliseconds for the mesh to fade in (Default: 300)
  93858. */
  93859. this.fadeInTime = 300;
  93860. this._millisecondsPerFrame = 1000 / 60;
  93861. this._hovered = false;
  93862. this._hoverValue = 0;
  93863. this._ownerNode = null;
  93864. this._update = function () {
  93865. if (_this._ownerNode) {
  93866. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  93867. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  93868. if (_this._ownerNode.visibility > 1) {
  93869. _this._setAllVisibility(_this._ownerNode, 1);
  93870. _this._hoverValue = _this.fadeInTime + _this.delay;
  93871. return;
  93872. }
  93873. else if (_this._ownerNode.visibility < 0) {
  93874. _this._setAllVisibility(_this._ownerNode, 0);
  93875. if (_this._hoverValue < 0) {
  93876. _this._hoverValue = 0;
  93877. return;
  93878. }
  93879. }
  93880. setTimeout(_this._update, _this._millisecondsPerFrame);
  93881. }
  93882. };
  93883. }
  93884. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  93885. /**
  93886. * The name of the behavior
  93887. */
  93888. get: function () {
  93889. return "FadeInOut";
  93890. },
  93891. enumerable: true,
  93892. configurable: true
  93893. });
  93894. /**
  93895. * Initializes the behavior
  93896. */
  93897. FadeInOutBehavior.prototype.init = function () {
  93898. };
  93899. /**
  93900. * Attaches the fade behavior on the passed in mesh
  93901. * @param ownerNode The mesh that will be faded in/out once attached
  93902. */
  93903. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  93904. this._ownerNode = ownerNode;
  93905. this._setAllVisibility(this._ownerNode, 0);
  93906. };
  93907. /**
  93908. * Detaches the behavior from the mesh
  93909. */
  93910. FadeInOutBehavior.prototype.detach = function () {
  93911. this._ownerNode = null;
  93912. };
  93913. /**
  93914. * Triggers the mesh to begin fading in or out
  93915. * @param value if the object should fade in or out (true to fade in)
  93916. */
  93917. FadeInOutBehavior.prototype.fadeIn = function (value) {
  93918. this._hovered = value;
  93919. this._update();
  93920. };
  93921. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  93922. var _this = this;
  93923. mesh.visibility = value;
  93924. mesh.getChildMeshes().forEach(function (c) {
  93925. _this._setAllVisibility(c, value);
  93926. });
  93927. };
  93928. return FadeInOutBehavior;
  93929. }());
  93930. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  93931. })(BABYLON || (BABYLON = {}));
  93932. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  93933. var BABYLON;
  93934. (function (BABYLON) {
  93935. /**
  93936. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  93937. */
  93938. var Gizmo = /** @class */ (function () {
  93939. /**
  93940. * Creates a gizmo
  93941. * @param gizmoLayer The utility layer the gizmo will be added to
  93942. */
  93943. function Gizmo(
  93944. /** The utility layer the gizmo will be added to */
  93945. gizmoLayer) {
  93946. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93947. var _this = this;
  93948. this.gizmoLayer = gizmoLayer;
  93949. /**
  93950. * Ratio for the scale of the gizmo (Default: 1)
  93951. */
  93952. this.scaleRatio = 1;
  93953. this._tmpMatrix = new BABYLON.Matrix();
  93954. /**
  93955. * If a custom mesh has been set (Default: false)
  93956. */
  93957. this._customMeshSet = false;
  93958. /**
  93959. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  93960. */
  93961. this.updateGizmoRotationToMatchAttachedMesh = true;
  93962. /**
  93963. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  93964. */
  93965. this.updateGizmoPositionToMatchAttachedMesh = true;
  93966. /**
  93967. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  93968. */
  93969. this._updateScale = true;
  93970. this._interactionsEnabled = true;
  93971. this._tempVector = new BABYLON.Vector3();
  93972. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  93973. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  93974. _this._update();
  93975. });
  93976. this.attachedMesh = null;
  93977. }
  93978. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  93979. /**
  93980. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  93981. * * When set, interactions will be enabled
  93982. */
  93983. get: function () {
  93984. return this._attachedMesh;
  93985. },
  93986. set: function (value) {
  93987. this._attachedMesh = value;
  93988. this._rootMesh.setEnabled(value ? true : false);
  93989. this._attachedMeshChanged(value);
  93990. },
  93991. enumerable: true,
  93992. configurable: true
  93993. });
  93994. /**
  93995. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93996. * @param mesh The mesh to replace the default mesh of the gizmo
  93997. */
  93998. Gizmo.prototype.setCustomMesh = function (mesh) {
  93999. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  94000. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  94001. }
  94002. this._rootMesh.getChildMeshes().forEach(function (c) {
  94003. c.dispose();
  94004. });
  94005. mesh.parent = this._rootMesh;
  94006. this._customMeshSet = true;
  94007. };
  94008. Gizmo.prototype._attachedMeshChanged = function (value) {
  94009. };
  94010. /**
  94011. * @hidden
  94012. * Updates the gizmo to match the attached mesh's position/rotation
  94013. */
  94014. Gizmo.prototype._update = function () {
  94015. if (this.attachedMesh) {
  94016. if (this.updateGizmoRotationToMatchAttachedMesh) {
  94017. if (!this._rootMesh.rotationQuaternion) {
  94018. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  94019. }
  94020. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  94021. this._tempVector.copyFrom(this.attachedMesh.scaling);
  94022. if (this.attachedMesh.scaling.x < 0) {
  94023. this.attachedMesh.scaling.x *= -1;
  94024. }
  94025. if (this.attachedMesh.scaling.y < 0) {
  94026. this.attachedMesh.scaling.y *= -1;
  94027. }
  94028. if (this.attachedMesh.scaling.z < 0) {
  94029. this.attachedMesh.scaling.z *= -1;
  94030. }
  94031. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  94032. this.attachedMesh.scaling.copyFrom(this._tempVector);
  94033. this.attachedMesh.computeWorldMatrix();
  94034. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  94035. }
  94036. else if (this._rootMesh.rotationQuaternion) {
  94037. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  94038. }
  94039. if (this.updateGizmoPositionToMatchAttachedMesh) {
  94040. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  94041. }
  94042. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  94043. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  94044. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  94045. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  94046. }
  94047. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  94048. var dist = this._tempVector.length() * this.scaleRatio;
  94049. this._rootMesh.scaling.set(dist, dist, dist);
  94050. }
  94051. }
  94052. };
  94053. /**
  94054. * Disposes of the gizmo
  94055. */
  94056. Gizmo.prototype.dispose = function () {
  94057. this._rootMesh.dispose();
  94058. if (this._beforeRenderObserver) {
  94059. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  94060. }
  94061. };
  94062. return Gizmo;
  94063. }());
  94064. BABYLON.Gizmo = Gizmo;
  94065. })(BABYLON || (BABYLON = {}));
  94066. //# sourceMappingURL=babylon.gizmo.js.map
  94067. var BABYLON;
  94068. (function (BABYLON) {
  94069. /**
  94070. * Single axis drag gizmo
  94071. */
  94072. var AxisDragGizmo = /** @class */ (function (_super) {
  94073. __extends(AxisDragGizmo, _super);
  94074. /**
  94075. * Creates an AxisDragGizmo
  94076. * @param gizmoLayer The utility layer the gizmo will be added to
  94077. * @param dragAxis The axis which the gizmo will be able to drag on
  94078. * @param color The color of the gizmo
  94079. */
  94080. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  94081. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94082. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94083. var _this = _super.call(this, gizmoLayer) || this;
  94084. _this._pointerObserver = null;
  94085. /**
  94086. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94087. */
  94088. _this.snapDistance = 0;
  94089. /**
  94090. * Event that fires each time the gizmo snaps to a new location.
  94091. * * snapDistance is the the change in distance
  94092. */
  94093. _this.onSnapObservable = new BABYLON.Observable();
  94094. // Create Material
  94095. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94096. coloredMaterial.disableLighting = true;
  94097. coloredMaterial.emissiveColor = color;
  94098. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94099. hoverMaterial.disableLighting = true;
  94100. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94101. // Build mesh on root node
  94102. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94103. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  94104. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  94105. arrowTail.color = coloredMaterial.emissiveColor;
  94106. arrow.addChild(arrowMesh);
  94107. arrow.addChild(arrowTail);
  94108. // Position arrow pointing in its drag axis
  94109. arrowMesh.scaling.scaleInPlace(0.05);
  94110. arrowMesh.material = coloredMaterial;
  94111. arrowMesh.rotation.x = Math.PI / 2;
  94112. arrowMesh.position.z += 0.3;
  94113. arrowTail.scaling.scaleInPlace(0.26);
  94114. arrowTail.rotation.x = Math.PI / 2;
  94115. arrowTail.material = coloredMaterial;
  94116. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  94117. arrow.scaling.scaleInPlace(1 / 3);
  94118. _this._rootMesh.addChild(arrow);
  94119. var currentSnapDragDistance = 0;
  94120. var tmpVector = new BABYLON.Vector3();
  94121. var tmpSnapEvent = { snapDistance: 0 };
  94122. // Add drag behavior to handle events when the gizmo is dragged
  94123. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94124. _this.dragBehavior.moveAttached = false;
  94125. _this._rootMesh.addBehavior(_this.dragBehavior);
  94126. var localDelta = new BABYLON.Vector3();
  94127. var tmpMatrix = new BABYLON.Matrix();
  94128. _this.dragBehavior.onDragObservable.add(function (event) {
  94129. if (_this.attachedMesh) {
  94130. // Convert delta to local translation if it has a parent
  94131. if (_this.attachedMesh.parent) {
  94132. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  94133. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  94134. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  94135. }
  94136. else {
  94137. localDelta.copyFrom(event.delta);
  94138. }
  94139. // Snapping logic
  94140. if (_this.snapDistance == 0) {
  94141. _this.attachedMesh.position.addInPlace(localDelta);
  94142. }
  94143. else {
  94144. currentSnapDragDistance += event.dragDistance;
  94145. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94146. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  94147. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94148. localDelta.normalizeToRef(tmpVector);
  94149. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  94150. _this.attachedMesh.position.addInPlace(tmpVector);
  94151. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  94152. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94153. }
  94154. }
  94155. }
  94156. });
  94157. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94158. if (_this._customMeshSet) {
  94159. return;
  94160. }
  94161. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94162. var material = isHovered ? hoverMaterial : coloredMaterial;
  94163. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94164. m.material = material;
  94165. if (m.color) {
  94166. m.color = material.emissiveColor;
  94167. }
  94168. });
  94169. });
  94170. return _this;
  94171. }
  94172. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  94173. if (this.dragBehavior) {
  94174. this.dragBehavior.enabled = value ? true : false;
  94175. }
  94176. };
  94177. /**
  94178. * Disposes of the gizmo
  94179. */
  94180. AxisDragGizmo.prototype.dispose = function () {
  94181. this.onSnapObservable.clear();
  94182. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94183. this.dragBehavior.detach();
  94184. _super.prototype.dispose.call(this);
  94185. };
  94186. return AxisDragGizmo;
  94187. }(BABYLON.Gizmo));
  94188. BABYLON.AxisDragGizmo = AxisDragGizmo;
  94189. })(BABYLON || (BABYLON = {}));
  94190. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  94191. var BABYLON;
  94192. (function (BABYLON) {
  94193. /**
  94194. * Single axis scale gizmo
  94195. */
  94196. var AxisScaleGizmo = /** @class */ (function (_super) {
  94197. __extends(AxisScaleGizmo, _super);
  94198. /**
  94199. * Creates an AxisScaleGizmo
  94200. * @param gizmoLayer The utility layer the gizmo will be added to
  94201. * @param dragAxis The axis which the gizmo will be able to scale on
  94202. * @param color The color of the gizmo
  94203. */
  94204. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  94205. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94206. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94207. var _this = _super.call(this, gizmoLayer) || this;
  94208. _this._pointerObserver = null;
  94209. /**
  94210. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94211. */
  94212. _this.snapDistance = 0;
  94213. /**
  94214. * Event that fires each time the gizmo snaps to a new location.
  94215. * * snapDistance is the the change in distance
  94216. */
  94217. _this.onSnapObservable = new BABYLON.Observable();
  94218. /**
  94219. * If the scaling operation should be done on all axis (default: false)
  94220. */
  94221. _this.uniformScaling = false;
  94222. // Create Material
  94223. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94224. _this._coloredMaterial.disableLighting = true;
  94225. _this._coloredMaterial.emissiveColor = color;
  94226. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94227. hoverMaterial.disableLighting = true;
  94228. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94229. // Build mesh on root node
  94230. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94231. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  94232. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  94233. arrowTail.color = _this._coloredMaterial.emissiveColor;
  94234. arrow.addChild(arrowMesh);
  94235. arrow.addChild(arrowTail);
  94236. // Position arrow pointing in its drag axis
  94237. arrowMesh.scaling.scaleInPlace(0.1);
  94238. arrowMesh.material = _this._coloredMaterial;
  94239. arrowMesh.rotation.x = Math.PI / 2;
  94240. arrowMesh.position.z += 0.3;
  94241. arrowTail.scaling.scaleInPlace(0.26);
  94242. arrowTail.rotation.x = Math.PI / 2;
  94243. arrowTail.material = _this._coloredMaterial;
  94244. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  94245. _this._rootMesh.addChild(arrow);
  94246. arrow.scaling.scaleInPlace(1 / 3);
  94247. // Add drag behavior to handle events when the gizmo is dragged
  94248. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94249. _this.dragBehavior.moveAttached = false;
  94250. _this._rootMesh.addBehavior(_this.dragBehavior);
  94251. var currentSnapDragDistance = 0;
  94252. var tmpVector = new BABYLON.Vector3();
  94253. var tmpSnapEvent = { snapDistance: 0 };
  94254. _this.dragBehavior.onDragObservable.add(function (event) {
  94255. if (_this.attachedMesh) {
  94256. // Snapping logic
  94257. var snapped = false;
  94258. var dragSteps = 0;
  94259. if (_this.uniformScaling) {
  94260. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  94261. if (tmpVector.y < 0) {
  94262. tmpVector.scaleInPlace(-1);
  94263. }
  94264. }
  94265. else {
  94266. tmpVector.copyFrom(dragAxis);
  94267. }
  94268. if (_this.snapDistance == 0) {
  94269. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  94270. }
  94271. else {
  94272. currentSnapDragDistance += event.dragDistance;
  94273. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94274. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  94275. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94276. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  94277. snapped = true;
  94278. }
  94279. else {
  94280. tmpVector.scaleInPlace(0);
  94281. }
  94282. }
  94283. _this.attachedMesh.scaling.addInPlace(tmpVector);
  94284. if (snapped) {
  94285. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  94286. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94287. }
  94288. }
  94289. });
  94290. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94291. if (_this._customMeshSet) {
  94292. return;
  94293. }
  94294. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94295. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  94296. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94297. m.material = material;
  94298. if (m.color) {
  94299. m.color = material.emissiveColor;
  94300. }
  94301. });
  94302. });
  94303. return _this;
  94304. }
  94305. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  94306. if (this.dragBehavior) {
  94307. this.dragBehavior.enabled = value ? true : false;
  94308. }
  94309. };
  94310. /**
  94311. * Disposes of the gizmo
  94312. */
  94313. AxisScaleGizmo.prototype.dispose = function () {
  94314. this.onSnapObservable.clear();
  94315. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94316. this.dragBehavior.detach();
  94317. _super.prototype.dispose.call(this);
  94318. };
  94319. /**
  94320. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  94321. * @param mesh The mesh to replace the default mesh of the gizmo
  94322. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  94323. */
  94324. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  94325. var _this = this;
  94326. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  94327. _super.prototype.setCustomMesh.call(this, mesh);
  94328. if (useGizmoMaterial) {
  94329. this._rootMesh.getChildMeshes().forEach(function (m) {
  94330. m.material = _this._coloredMaterial;
  94331. if (m.color) {
  94332. m.color = _this._coloredMaterial.emissiveColor;
  94333. }
  94334. });
  94335. this._customMeshSet = false;
  94336. }
  94337. };
  94338. return AxisScaleGizmo;
  94339. }(BABYLON.Gizmo));
  94340. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  94341. })(BABYLON || (BABYLON = {}));
  94342. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  94343. var BABYLON;
  94344. (function (BABYLON) {
  94345. /**
  94346. * Single plane rotation gizmo
  94347. */
  94348. var PlaneRotationGizmo = /** @class */ (function (_super) {
  94349. __extends(PlaneRotationGizmo, _super);
  94350. /**
  94351. * Creates a PlaneRotationGizmo
  94352. * @param gizmoLayer The utility layer the gizmo will be added to
  94353. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  94354. * @param color The color of the gizmo
  94355. */
  94356. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  94357. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94358. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94359. var _this = _super.call(this, gizmoLayer) || this;
  94360. _this._pointerObserver = null;
  94361. /**
  94362. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  94363. */
  94364. _this.snapDistance = 0;
  94365. /**
  94366. * Event that fires each time the gizmo snaps to a new location.
  94367. * * snapDistance is the the change in distance
  94368. */
  94369. _this.onSnapObservable = new BABYLON.Observable();
  94370. // Create Material
  94371. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94372. coloredMaterial.disableLighting = true;
  94373. coloredMaterial.emissiveColor = color;
  94374. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94375. hoverMaterial.disableLighting = true;
  94376. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94377. // Build mesh on root node
  94378. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94379. // Create circle out of lines
  94380. var tessellation = 20;
  94381. var radius = 0.8;
  94382. var points = new Array();
  94383. for (var i = 0; i < tessellation; i++) {
  94384. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  94385. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  94386. }
  94387. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  94388. rotationMesh.color = coloredMaterial.emissiveColor;
  94389. // Position arrow pointing in its drag axis
  94390. rotationMesh.scaling.scaleInPlace(0.26);
  94391. rotationMesh.material = coloredMaterial;
  94392. rotationMesh.rotation.x = Math.PI / 2;
  94393. parentMesh.addChild(rotationMesh);
  94394. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  94395. _this._rootMesh.addChild(parentMesh);
  94396. parentMesh.scaling.scaleInPlace(1 / 3);
  94397. // Add drag behavior to handle events when the gizmo is dragged
  94398. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  94399. _this.dragBehavior.moveAttached = false;
  94400. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  94401. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  94402. _this._rootMesh.addBehavior(_this.dragBehavior);
  94403. var lastDragPosition = new BABYLON.Vector3();
  94404. _this.dragBehavior.onDragStartObservable.add(function (e) {
  94405. if (_this.attachedMesh) {
  94406. lastDragPosition.copyFrom(e.dragPlanePoint);
  94407. }
  94408. });
  94409. var rotationMatrix = new BABYLON.Matrix();
  94410. var planeNormalTowardsCamera = new BABYLON.Vector3();
  94411. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  94412. var tmpSnapEvent = { snapDistance: 0 };
  94413. var currentSnapDragDistance = 0;
  94414. var tmpMatrix = new BABYLON.Matrix();
  94415. var tmpVector = new BABYLON.Vector3();
  94416. var amountToRotate = new BABYLON.Quaternion();
  94417. _this.dragBehavior.onDragObservable.add(function (event) {
  94418. if (_this.attachedMesh) {
  94419. if (!_this.attachedMesh.rotationQuaternion) {
  94420. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94421. }
  94422. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  94423. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  94424. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  94425. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  94426. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  94427. var angle = Math.atan2(cross.length(), dot);
  94428. planeNormalTowardsCamera.copyFrom(planeNormal);
  94429. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  94430. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  94431. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  94432. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  94433. }
  94434. // Flip up vector depending on which side the camera is on
  94435. if (gizmoLayer.utilityLayerScene.activeCamera) {
  94436. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  94437. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  94438. planeNormalTowardsCamera.scaleInPlace(-1);
  94439. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  94440. }
  94441. }
  94442. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  94443. if (halfCircleSide)
  94444. angle = -angle;
  94445. // Snapping logic
  94446. var snapped = false;
  94447. if (_this.snapDistance != 0) {
  94448. currentSnapDragDistance += angle;
  94449. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94450. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  94451. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94452. angle = _this.snapDistance * dragSteps;
  94453. snapped = true;
  94454. }
  94455. else {
  94456. angle = 0;
  94457. }
  94458. }
  94459. // If the mesh has a parent, convert needed world rotation to local rotation
  94460. tmpMatrix.reset();
  94461. if (_this.attachedMesh.parent) {
  94462. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  94463. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  94464. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  94465. }
  94466. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  94467. var quaternionCoefficient = Math.sin(angle / 2);
  94468. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  94469. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  94470. if (tmpMatrix.determinant() > 0) {
  94471. amountToRotate.toEulerAnglesToRef(tmpVector);
  94472. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  94473. }
  94474. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  94475. // Rotate selected mesh quaternion over fixed axis
  94476. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  94477. }
  94478. else {
  94479. // Rotate selected mesh quaternion over rotated axis
  94480. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  94481. }
  94482. lastDragPosition.copyFrom(event.dragPlanePoint);
  94483. if (snapped) {
  94484. tmpSnapEvent.snapDistance = angle;
  94485. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94486. }
  94487. }
  94488. });
  94489. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94490. if (_this._customMeshSet) {
  94491. return;
  94492. }
  94493. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94494. var material = isHovered ? hoverMaterial : coloredMaterial;
  94495. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94496. m.material = material;
  94497. if (m.color) {
  94498. m.color = material.emissiveColor;
  94499. }
  94500. });
  94501. });
  94502. return _this;
  94503. }
  94504. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  94505. if (this.dragBehavior) {
  94506. this.dragBehavior.enabled = value ? true : false;
  94507. }
  94508. };
  94509. /**
  94510. * Disposes of the gizmo
  94511. */
  94512. PlaneRotationGizmo.prototype.dispose = function () {
  94513. this.onSnapObservable.clear();
  94514. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94515. this.dragBehavior.detach();
  94516. _super.prototype.dispose.call(this);
  94517. };
  94518. return PlaneRotationGizmo;
  94519. }(BABYLON.Gizmo));
  94520. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  94521. })(BABYLON || (BABYLON = {}));
  94522. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  94523. var BABYLON;
  94524. (function (BABYLON) {
  94525. /**
  94526. * Gizmo that enables dragging a mesh along 3 axis
  94527. */
  94528. var PositionGizmo = /** @class */ (function (_super) {
  94529. __extends(PositionGizmo, _super);
  94530. /**
  94531. * Creates a PositionGizmo
  94532. * @param gizmoLayer The utility layer the gizmo will be added to
  94533. */
  94534. function PositionGizmo(gizmoLayer) {
  94535. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94536. var _this = _super.call(this, gizmoLayer) || this;
  94537. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94538. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94539. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94540. _this.attachedMesh = null;
  94541. return _this;
  94542. }
  94543. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  94544. set: function (mesh) {
  94545. if (this.xGizmo) {
  94546. this.xGizmo.attachedMesh = mesh;
  94547. this.yGizmo.attachedMesh = mesh;
  94548. this.zGizmo.attachedMesh = mesh;
  94549. }
  94550. },
  94551. enumerable: true,
  94552. configurable: true
  94553. });
  94554. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94555. get: function () {
  94556. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94557. },
  94558. set: function (value) {
  94559. if (this.xGizmo) {
  94560. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94561. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94562. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94563. }
  94564. },
  94565. enumerable: true,
  94566. configurable: true
  94567. });
  94568. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  94569. get: function () {
  94570. return this.xGizmo.snapDistance;
  94571. },
  94572. /**
  94573. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94574. */
  94575. set: function (value) {
  94576. if (this.xGizmo) {
  94577. this.xGizmo.snapDistance = value;
  94578. this.yGizmo.snapDistance = value;
  94579. this.zGizmo.snapDistance = value;
  94580. }
  94581. },
  94582. enumerable: true,
  94583. configurable: true
  94584. });
  94585. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  94586. get: function () {
  94587. return this.xGizmo.scaleRatio;
  94588. },
  94589. /**
  94590. * Ratio for the scale of the gizmo (Default: 1)
  94591. */
  94592. set: function (value) {
  94593. if (this.xGizmo) {
  94594. this.xGizmo.scaleRatio = value;
  94595. this.yGizmo.scaleRatio = value;
  94596. this.zGizmo.scaleRatio = value;
  94597. }
  94598. },
  94599. enumerable: true,
  94600. configurable: true
  94601. });
  94602. /**
  94603. * Disposes of the gizmo
  94604. */
  94605. PositionGizmo.prototype.dispose = function () {
  94606. this.xGizmo.dispose();
  94607. this.yGizmo.dispose();
  94608. this.zGizmo.dispose();
  94609. };
  94610. /**
  94611. * CustomMeshes are not supported by this gizmo
  94612. * @param mesh The mesh to replace the default mesh of the gizmo
  94613. */
  94614. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  94615. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  94616. };
  94617. return PositionGizmo;
  94618. }(BABYLON.Gizmo));
  94619. BABYLON.PositionGizmo = PositionGizmo;
  94620. })(BABYLON || (BABYLON = {}));
  94621. //# sourceMappingURL=babylon.positionGizmo.js.map
  94622. var BABYLON;
  94623. (function (BABYLON) {
  94624. /**
  94625. * Gizmo that enables rotating a mesh along 3 axis
  94626. */
  94627. var RotationGizmo = /** @class */ (function (_super) {
  94628. __extends(RotationGizmo, _super);
  94629. /**
  94630. * Creates a RotationGizmo
  94631. * @param gizmoLayer The utility layer the gizmo will be added to
  94632. */
  94633. function RotationGizmo(gizmoLayer) {
  94634. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94635. var _this = _super.call(this, gizmoLayer) || this;
  94636. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94637. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94638. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94639. _this.attachedMesh = null;
  94640. return _this;
  94641. }
  94642. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  94643. set: function (mesh) {
  94644. if (this.xGizmo) {
  94645. this.xGizmo.attachedMesh = mesh;
  94646. this.yGizmo.attachedMesh = mesh;
  94647. this.zGizmo.attachedMesh = mesh;
  94648. }
  94649. },
  94650. enumerable: true,
  94651. configurable: true
  94652. });
  94653. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94654. get: function () {
  94655. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94656. },
  94657. set: function (value) {
  94658. if (this.xGizmo) {
  94659. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94660. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94661. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94662. }
  94663. },
  94664. enumerable: true,
  94665. configurable: true
  94666. });
  94667. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  94668. get: function () {
  94669. return this.xGizmo.snapDistance;
  94670. },
  94671. /**
  94672. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94673. */
  94674. set: function (value) {
  94675. if (this.xGizmo) {
  94676. this.xGizmo.snapDistance = value;
  94677. this.yGizmo.snapDistance = value;
  94678. this.zGizmo.snapDistance = value;
  94679. }
  94680. },
  94681. enumerable: true,
  94682. configurable: true
  94683. });
  94684. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  94685. get: function () {
  94686. return this.xGizmo.scaleRatio;
  94687. },
  94688. /**
  94689. * Ratio for the scale of the gizmo (Default: 1)
  94690. */
  94691. set: function (value) {
  94692. if (this.xGizmo) {
  94693. this.xGizmo.scaleRatio = value;
  94694. this.yGizmo.scaleRatio = value;
  94695. this.zGizmo.scaleRatio = value;
  94696. }
  94697. },
  94698. enumerable: true,
  94699. configurable: true
  94700. });
  94701. /**
  94702. * Disposes of the gizmo
  94703. */
  94704. RotationGizmo.prototype.dispose = function () {
  94705. this.xGizmo.dispose();
  94706. this.yGizmo.dispose();
  94707. this.zGizmo.dispose();
  94708. };
  94709. /**
  94710. * CustomMeshes are not supported by this gizmo
  94711. * @param mesh The mesh to replace the default mesh of the gizmo
  94712. */
  94713. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  94714. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  94715. };
  94716. return RotationGizmo;
  94717. }(BABYLON.Gizmo));
  94718. BABYLON.RotationGizmo = RotationGizmo;
  94719. })(BABYLON || (BABYLON = {}));
  94720. //# sourceMappingURL=babylon.rotationGizmo.js.map
  94721. var BABYLON;
  94722. (function (BABYLON) {
  94723. /**
  94724. * Gizmo that enables scaling a mesh along 3 axis
  94725. */
  94726. var ScaleGizmo = /** @class */ (function (_super) {
  94727. __extends(ScaleGizmo, _super);
  94728. /**
  94729. * Creates a ScaleGizmo
  94730. * @param gizmoLayer The utility layer the gizmo will be added to
  94731. */
  94732. function ScaleGizmo(gizmoLayer) {
  94733. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94734. var _this = _super.call(this, gizmoLayer) || this;
  94735. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94736. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94737. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94738. // Create uniform scale gizmo
  94739. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  94740. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94741. _this._uniformGizmo.uniformScaling = true;
  94742. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  94743. octahedron.scaling.scaleInPlace(0.007);
  94744. _this._uniformGizmo.setCustomMesh(octahedron, true);
  94745. _this.attachedMesh = null;
  94746. return _this;
  94747. }
  94748. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  94749. set: function (mesh) {
  94750. if (this.xGizmo) {
  94751. this.xGizmo.attachedMesh = mesh;
  94752. this.yGizmo.attachedMesh = mesh;
  94753. this.zGizmo.attachedMesh = mesh;
  94754. this._uniformGizmo.attachedMesh = mesh;
  94755. }
  94756. },
  94757. enumerable: true,
  94758. configurable: true
  94759. });
  94760. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94761. get: function () {
  94762. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94763. },
  94764. set: function (value) {
  94765. if (this.xGizmo) {
  94766. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94767. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94768. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94769. }
  94770. },
  94771. enumerable: true,
  94772. configurable: true
  94773. });
  94774. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  94775. get: function () {
  94776. return this.xGizmo.snapDistance;
  94777. },
  94778. /**
  94779. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94780. */
  94781. set: function (value) {
  94782. if (this.xGizmo) {
  94783. this.xGizmo.snapDistance = value;
  94784. this.yGizmo.snapDistance = value;
  94785. this.zGizmo.snapDistance = value;
  94786. this._uniformGizmo.snapDistance = value;
  94787. }
  94788. },
  94789. enumerable: true,
  94790. configurable: true
  94791. });
  94792. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  94793. get: function () {
  94794. return this.xGizmo.scaleRatio;
  94795. },
  94796. /**
  94797. * Ratio for the scale of the gizmo (Default: 1)
  94798. */
  94799. set: function (value) {
  94800. if (this.xGizmo) {
  94801. this.xGizmo.scaleRatio = value;
  94802. this.yGizmo.scaleRatio = value;
  94803. this.zGizmo.scaleRatio = value;
  94804. this._uniformGizmo.scaleRatio = value;
  94805. }
  94806. },
  94807. enumerable: true,
  94808. configurable: true
  94809. });
  94810. /**
  94811. * Disposes of the gizmo
  94812. */
  94813. ScaleGizmo.prototype.dispose = function () {
  94814. this.xGizmo.dispose();
  94815. this.yGizmo.dispose();
  94816. this.zGizmo.dispose();
  94817. this._uniformGizmo.dispose();
  94818. };
  94819. return ScaleGizmo;
  94820. }(BABYLON.Gizmo));
  94821. BABYLON.ScaleGizmo = ScaleGizmo;
  94822. })(BABYLON || (BABYLON = {}));
  94823. //# sourceMappingURL=babylon.scaleGizmo.js.map
  94824. var BABYLON;
  94825. (function (BABYLON) {
  94826. /**
  94827. * Bounding box gizmo
  94828. */
  94829. var BoundingBoxGizmo = /** @class */ (function (_super) {
  94830. __extends(BoundingBoxGizmo, _super);
  94831. /**
  94832. * Creates an BoundingBoxGizmo
  94833. * @param gizmoLayer The utility layer the gizmo will be added to
  94834. * @param color The color of the gizmo
  94835. */
  94836. function BoundingBoxGizmo(color, gizmoLayer) {
  94837. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94838. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  94839. var _this = _super.call(this, gizmoLayer) || this;
  94840. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  94841. _this._renderObserver = null;
  94842. _this._pointerObserver = null;
  94843. _this._scaleDragSpeed = 0.2;
  94844. _this._tmpQuaternion = new BABYLON.Quaternion();
  94845. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  94846. _this._tmpRotationMatrix = new BABYLON.Matrix();
  94847. /**
  94848. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  94849. */
  94850. _this.ignoreChildren = false;
  94851. /**
  94852. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  94853. */
  94854. _this.includeChildPredicate = null;
  94855. /**
  94856. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  94857. */
  94858. _this.rotationSphereSize = 0.1;
  94859. /**
  94860. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  94861. */
  94862. _this.scaleBoxSize = 0.1;
  94863. /**
  94864. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  94865. */
  94866. _this.fixedDragMeshScreenSize = false;
  94867. /**
  94868. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  94869. */
  94870. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  94871. /**
  94872. * Fired when a rotation sphere or scale box is dragged
  94873. */
  94874. _this.onDragStartObservable = new BABYLON.Observable();
  94875. /**
  94876. * Fired when a scale box is dragged
  94877. */
  94878. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  94879. /**
  94880. * Fired when a scale box drag is ended
  94881. */
  94882. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  94883. /**
  94884. * Fired when a rotation sphere is dragged
  94885. */
  94886. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  94887. /**
  94888. * Fired when a rotation sphere drag is ended
  94889. */
  94890. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  94891. /**
  94892. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  94893. */
  94894. _this.scalePivot = null;
  94895. _this._existingMeshScale = new BABYLON.Vector3();
  94896. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  94897. _this._updateScale = false;
  94898. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  94899. // Create Materials
  94900. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94901. coloredMaterial.disableLighting = true;
  94902. coloredMaterial.emissiveColor = color;
  94903. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94904. hoverColoredMaterial.disableLighting = true;
  94905. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94906. // Build bounding box out of lines
  94907. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94908. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  94909. var lines = [];
  94910. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  94911. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94912. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94913. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94914. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94915. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94916. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94917. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94918. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94919. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94920. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94921. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94922. lines.forEach(function (l) {
  94923. l.color = color;
  94924. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  94925. l.isPickable = false;
  94926. _this._lineBoundingBox.addChild(l);
  94927. });
  94928. _this._rootMesh.addChild(_this._lineBoundingBox);
  94929. // Create rotation spheres
  94930. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94931. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  94932. var _loop_1 = function (i_1) {
  94933. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  94934. sphere.rotationQuaternion = new BABYLON.Quaternion();
  94935. sphere.material = coloredMaterial;
  94936. // Drag behavior
  94937. _dragBehavior = new BABYLON.PointerDragBehavior({});
  94938. _dragBehavior.moveAttached = false;
  94939. _dragBehavior.updateDragPlane = false;
  94940. sphere.addBehavior(_dragBehavior);
  94941. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  94942. var totalTurnAmountOfDrag = 0;
  94943. _dragBehavior.onDragStartObservable.add(function (event) {
  94944. startingTurnDirection.copyFrom(sphere.forward);
  94945. totalTurnAmountOfDrag = 0;
  94946. });
  94947. _dragBehavior.onDragObservable.add(function (event) {
  94948. _this.onRotationSphereDragObservable.notifyObservers({});
  94949. if (_this.attachedMesh) {
  94950. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94951. var worldDragDirection = startingTurnDirection;
  94952. // Project the world right on to the drag plane
  94953. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  94954. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  94955. // project drag delta on to the resulting drag axis and rotate based on that
  94956. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  94957. // Make rotation relative to size of mesh.
  94958. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94959. // Rotate based on axis
  94960. if (!_this.attachedMesh.rotationQuaternion) {
  94961. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94962. }
  94963. if (!_this._anchorMesh.rotationQuaternion) {
  94964. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  94965. }
  94966. // Do not allow the object to turn more than a full circle
  94967. totalTurnAmountOfDrag += projectDist;
  94968. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  94969. if (i_1 >= 8) {
  94970. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  94971. }
  94972. else if (i_1 >= 4) {
  94973. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  94974. }
  94975. else {
  94976. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  94977. }
  94978. // Rotate around center of bounding box
  94979. _this._anchorMesh.addChild(_this.attachedMesh);
  94980. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  94981. _this._anchorMesh.removeChild(_this.attachedMesh);
  94982. }
  94983. _this.updateBoundingBox();
  94984. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94985. }
  94986. });
  94987. // Selection/deselection
  94988. _dragBehavior.onDragStartObservable.add(function () {
  94989. _this.onDragStartObservable.notifyObservers({});
  94990. _this._selectNode(sphere);
  94991. });
  94992. _dragBehavior.onDragEndObservable.add(function () {
  94993. _this.onRotationSphereDragEndObservable.notifyObservers({});
  94994. _this._selectNode(null);
  94995. });
  94996. this_1._rotateSpheresParent.addChild(sphere);
  94997. };
  94998. var this_1 = this, _dragBehavior;
  94999. for (var i_1 = 0; i_1 < 12; i_1++) {
  95000. _loop_1(i_1);
  95001. }
  95002. _this._rootMesh.addChild(_this._rotateSpheresParent);
  95003. // Create scale cubes
  95004. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95005. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  95006. for (var i = 0; i < 2; i++) {
  95007. for (var j = 0; j < 2; j++) {
  95008. var _loop_2 = function () {
  95009. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  95010. box.material = coloredMaterial;
  95011. // Dragging logic
  95012. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  95013. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  95014. _dragBehavior.moveAttached = false;
  95015. box.addBehavior(_dragBehavior);
  95016. _dragBehavior.onDragObservable.add(function (event) {
  95017. _this.onScaleBoxDragObservable.notifyObservers({});
  95018. if (_this.attachedMesh) {
  95019. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  95020. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  95021. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  95022. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  95023. _this.updateBoundingBox();
  95024. if (_this.scalePivot) {
  95025. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  95026. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  95027. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  95028. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  95029. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  95030. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  95031. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  95032. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  95033. }
  95034. else {
  95035. // Scale from the position of the opposite corner
  95036. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  95037. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  95038. }
  95039. _this._anchorMesh.addChild(_this.attachedMesh);
  95040. _this._anchorMesh.scaling.addInPlace(deltaScale);
  95041. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  95042. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  95043. }
  95044. _this._anchorMesh.removeChild(_this.attachedMesh);
  95045. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  95046. }
  95047. });
  95048. // Selection/deselection
  95049. _dragBehavior.onDragStartObservable.add(function () {
  95050. _this.onDragStartObservable.notifyObservers({});
  95051. _this._selectNode(box);
  95052. });
  95053. _dragBehavior.onDragEndObservable.add(function () {
  95054. _this.onScaleBoxDragEndObservable.notifyObservers({});
  95055. _this._selectNode(null);
  95056. });
  95057. this_2._scaleBoxesParent.addChild(box);
  95058. };
  95059. var this_2 = this, _dragBehavior;
  95060. for (var k = 0; k < 2; k++) {
  95061. _loop_2();
  95062. }
  95063. }
  95064. }
  95065. _this._rootMesh.addChild(_this._scaleBoxesParent);
  95066. // Hover color change
  95067. var pointerIds = new Array();
  95068. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  95069. if (!pointerIds[pointerInfo.event.pointerId]) {
  95070. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  95071. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  95072. pointerIds[pointerInfo.event.pointerId] = mesh;
  95073. mesh.material = hoverColoredMaterial;
  95074. }
  95075. });
  95076. }
  95077. else {
  95078. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  95079. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  95080. delete pointerIds[pointerInfo.event.pointerId];
  95081. }
  95082. }
  95083. });
  95084. // Update bounding box positions
  95085. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  95086. // Only update the bouding box if scaling has changed
  95087. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  95088. _this.updateBoundingBox();
  95089. }
  95090. });
  95091. _this.updateBoundingBox();
  95092. return _this;
  95093. }
  95094. /** @hidden */
  95095. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  95096. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  95097. // Save old pivot and set pivot to 0,0,0
  95098. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  95099. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  95100. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  95101. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  95102. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  95103. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  95104. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  95105. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  95106. }
  95107. }
  95108. BoundingBoxGizmo._PivotCached++;
  95109. };
  95110. /** @hidden */
  95111. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  95112. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  95113. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  95114. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  95115. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  95116. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  95117. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  95118. }
  95119. this._PivotCached--;
  95120. };
  95121. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  95122. if (value) {
  95123. // Reset anchor mesh to match attached mesh's scale
  95124. // This is needed to avoid invalid box/sphere position on first drag
  95125. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  95126. this._anchorMesh.addChild(value);
  95127. this._anchorMesh.removeChild(value);
  95128. BoundingBoxGizmo._RestorePivotPoint(value);
  95129. this.updateBoundingBox();
  95130. }
  95131. };
  95132. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  95133. this._rotateSpheresParent.getChildMeshes()
  95134. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  95135. m.isVisible = (!selectedMesh || m == selectedMesh);
  95136. });
  95137. };
  95138. /**
  95139. * Updates the bounding box information for the Gizmo
  95140. */
  95141. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  95142. if (this.attachedMesh) {
  95143. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  95144. this._update();
  95145. // Rotate based on axis
  95146. if (!this.attachedMesh.rotationQuaternion) {
  95147. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  95148. }
  95149. if (!this._anchorMesh.rotationQuaternion) {
  95150. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  95151. }
  95152. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  95153. // Store original position and reset mesh to origin before computing the bounding box
  95154. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  95155. this._tmpVector.copyFrom(this.attachedMesh.position);
  95156. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  95157. this.attachedMesh.position.set(0, 0, 0);
  95158. // Update bounding dimensions/positions
  95159. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  95160. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  95161. // Update gizmo to match bounding box scaling and rotation
  95162. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  95163. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  95164. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  95165. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  95166. this._lineBoundingBox.computeWorldMatrix();
  95167. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  95168. // restore position/rotation values
  95169. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  95170. this.attachedMesh.position.copyFrom(this._tmpVector);
  95171. }
  95172. // Update rotation sphere locations
  95173. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  95174. for (var i = 0; i < 3; i++) {
  95175. for (var j = 0; j < 2; j++) {
  95176. for (var k = 0; k < 2; k++) {
  95177. var index = ((i * 4) + (j * 2)) + k;
  95178. if (i == 0) {
  95179. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  95180. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95181. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95182. }
  95183. if (i == 1) {
  95184. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  95185. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95186. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95187. }
  95188. if (i == 2) {
  95189. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  95190. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95191. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95192. }
  95193. if (this.fixedDragMeshScreenSize) {
  95194. this._rootMesh.computeWorldMatrix();
  95195. this._rotateSpheresParent.computeWorldMatrix();
  95196. rotateSpheres[index].computeWorldMatrix();
  95197. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  95198. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  95199. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  95200. }
  95201. else {
  95202. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  95203. }
  95204. }
  95205. }
  95206. }
  95207. // Update scale box locations
  95208. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  95209. for (var i = 0; i < 2; i++) {
  95210. for (var j = 0; j < 2; j++) {
  95211. for (var k = 0; k < 2; k++) {
  95212. var index = ((i * 4) + (j * 2)) + k;
  95213. if (scaleBoxes[index]) {
  95214. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  95215. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95216. if (this.fixedDragMeshScreenSize) {
  95217. this._rootMesh.computeWorldMatrix();
  95218. this._scaleBoxesParent.computeWorldMatrix();
  95219. scaleBoxes[index].computeWorldMatrix();
  95220. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  95221. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  95222. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  95223. }
  95224. else {
  95225. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  95226. }
  95227. }
  95228. }
  95229. }
  95230. }
  95231. if (this.attachedMesh) {
  95232. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  95233. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  95234. }
  95235. };
  95236. /**
  95237. * Enables rotation on the specified axis and disables rotation on the others
  95238. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  95239. */
  95240. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  95241. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  95242. if (i < 4) {
  95243. m.setEnabled(axis.indexOf("x") != -1);
  95244. }
  95245. else if (i < 8) {
  95246. m.setEnabled(axis.indexOf("y") != -1);
  95247. }
  95248. else {
  95249. m.setEnabled(axis.indexOf("z") != -1);
  95250. }
  95251. });
  95252. };
  95253. /**
  95254. * Disposes of the gizmo
  95255. */
  95256. BoundingBoxGizmo.prototype.dispose = function () {
  95257. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  95258. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  95259. this._lineBoundingBox.dispose();
  95260. this._rotateSpheresParent.dispose();
  95261. this._scaleBoxesParent.dispose();
  95262. _super.prototype.dispose.call(this);
  95263. };
  95264. /**
  95265. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  95266. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  95267. * @returns the bounding box mesh with the passed in mesh as a child
  95268. */
  95269. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  95270. var makeNotPickable = function (root) {
  95271. root.isPickable = false;
  95272. root.getChildMeshes().forEach(function (c) {
  95273. makeNotPickable(c);
  95274. });
  95275. };
  95276. makeNotPickable(mesh);
  95277. // Reset position to get boudning box from origin with no rotation
  95278. if (!mesh.rotationQuaternion) {
  95279. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  95280. }
  95281. var oldPos = mesh.position.clone();
  95282. var oldRot = mesh.rotationQuaternion.clone();
  95283. mesh.rotationQuaternion.set(0, 0, 0, 1);
  95284. mesh.position.set(0, 0, 0);
  95285. // Update bounding dimensions/positions
  95286. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  95287. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  95288. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  95289. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  95290. // Restore original positions
  95291. mesh.addChild(box);
  95292. mesh.rotationQuaternion.copyFrom(oldRot);
  95293. mesh.position.copyFrom(oldPos);
  95294. // Reverse parenting
  95295. mesh.removeChild(box);
  95296. box.addChild(mesh);
  95297. box.visibility = 0;
  95298. return box;
  95299. };
  95300. /**
  95301. * CustomMeshes are not supported by this gizmo
  95302. * @param mesh The mesh to replace the default mesh of the gizmo
  95303. */
  95304. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  95305. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  95306. };
  95307. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  95308. // store/remove pivot point should only be applied during their outermost calls
  95309. BoundingBoxGizmo._PivotCached = 0;
  95310. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  95311. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  95312. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  95313. return BoundingBoxGizmo;
  95314. }(BABYLON.Gizmo));
  95315. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  95316. })(BABYLON || (BABYLON = {}));
  95317. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  95318. var BABYLON;
  95319. (function (BABYLON) {
  95320. /**
  95321. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  95322. */
  95323. var GizmoManager = /** @class */ (function () {
  95324. /**
  95325. * Instatiates a gizmo manager
  95326. * @param scene the scene to overlay the gizmos on top of
  95327. */
  95328. function GizmoManager(scene) {
  95329. var _this = this;
  95330. this.scene = scene;
  95331. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  95332. this._pointerObserver = null;
  95333. this._attachedMesh = null;
  95334. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  95335. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  95336. /**
  95337. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  95338. */
  95339. this.attachableMeshes = null;
  95340. /**
  95341. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  95342. */
  95343. this.usePointerToAttachGizmos = true;
  95344. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  95345. // Instatiate/dispose gizmos based on pointer actions
  95346. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  95347. if (!_this.usePointerToAttachGizmos) {
  95348. return;
  95349. }
  95350. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95351. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  95352. var node = pointerInfo.pickInfo.pickedMesh;
  95353. if (_this.attachableMeshes == null) {
  95354. // Attach to the most parent node
  95355. while (node && node.parent != null) {
  95356. node = node.parent;
  95357. }
  95358. }
  95359. else {
  95360. // Attach to the parent node that is an attachableMesh
  95361. var found = false;
  95362. _this.attachableMeshes.forEach(function (mesh) {
  95363. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  95364. node = mesh;
  95365. found = true;
  95366. }
  95367. });
  95368. if (!found) {
  95369. node = null;
  95370. }
  95371. }
  95372. if (node instanceof BABYLON.AbstractMesh) {
  95373. _this.attachToMesh(node);
  95374. }
  95375. else {
  95376. _this.attachToMesh(null);
  95377. }
  95378. }
  95379. else {
  95380. _this.attachToMesh(null);
  95381. }
  95382. }
  95383. });
  95384. }
  95385. /**
  95386. * Attaches a set of gizmos to the specified mesh
  95387. * @param mesh The mesh the gizmo's should be attached to
  95388. */
  95389. GizmoManager.prototype.attachToMesh = function (mesh) {
  95390. if (this._attachedMesh) {
  95391. this._attachedMesh.removeBehavior(this._dragBehavior);
  95392. }
  95393. this._attachedMesh = mesh;
  95394. for (var key in this.gizmos) {
  95395. var gizmo = (this.gizmos[key]);
  95396. if (gizmo && this._gizmosEnabled[key]) {
  95397. gizmo.attachedMesh = mesh;
  95398. }
  95399. }
  95400. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  95401. this._attachedMesh.addBehavior(this._dragBehavior);
  95402. }
  95403. };
  95404. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  95405. get: function () {
  95406. return this._gizmosEnabled.positionGizmo;
  95407. },
  95408. /**
  95409. * If the position gizmo is enabled
  95410. */
  95411. set: function (value) {
  95412. if (value) {
  95413. if (!this.gizmos.positionGizmo) {
  95414. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  95415. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95416. }
  95417. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  95418. }
  95419. else if (this.gizmos.positionGizmo) {
  95420. this.gizmos.positionGizmo.attachedMesh = null;
  95421. }
  95422. this._gizmosEnabled.positionGizmo = value;
  95423. },
  95424. enumerable: true,
  95425. configurable: true
  95426. });
  95427. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  95428. get: function () {
  95429. return this._gizmosEnabled.rotationGizmo;
  95430. },
  95431. /**
  95432. * If the rotation gizmo is enabled
  95433. */
  95434. set: function (value) {
  95435. if (value) {
  95436. if (!this.gizmos.rotationGizmo) {
  95437. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  95438. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95439. }
  95440. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  95441. }
  95442. else if (this.gizmos.rotationGizmo) {
  95443. this.gizmos.rotationGizmo.attachedMesh = null;
  95444. }
  95445. this._gizmosEnabled.rotationGizmo = value;
  95446. },
  95447. enumerable: true,
  95448. configurable: true
  95449. });
  95450. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  95451. get: function () {
  95452. return this._gizmosEnabled.scaleGizmo;
  95453. },
  95454. /**
  95455. * If the scale gizmo is enabled
  95456. */
  95457. set: function (value) {
  95458. if (value) {
  95459. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  95460. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  95461. }
  95462. else if (this.gizmos.scaleGizmo) {
  95463. this.gizmos.scaleGizmo.attachedMesh = null;
  95464. }
  95465. this._gizmosEnabled.scaleGizmo = value;
  95466. },
  95467. enumerable: true,
  95468. configurable: true
  95469. });
  95470. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  95471. get: function () {
  95472. return this._gizmosEnabled.boundingBoxGizmo;
  95473. },
  95474. /**
  95475. * If the boundingBox gizmo is enabled
  95476. */
  95477. set: function (value) {
  95478. if (value) {
  95479. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  95480. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  95481. if (this._attachedMesh) {
  95482. this._attachedMesh.removeBehavior(this._dragBehavior);
  95483. this._attachedMesh.addBehavior(this._dragBehavior);
  95484. }
  95485. }
  95486. else if (this.gizmos.boundingBoxGizmo) {
  95487. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  95488. }
  95489. this._gizmosEnabled.boundingBoxGizmo = value;
  95490. },
  95491. enumerable: true,
  95492. configurable: true
  95493. });
  95494. /**
  95495. * Disposes of the gizmo manager
  95496. */
  95497. GizmoManager.prototype.dispose = function () {
  95498. this.scene.onPointerObservable.remove(this._pointerObserver);
  95499. for (var key in this.gizmos) {
  95500. var gizmo = (this.gizmos[key]);
  95501. if (gizmo) {
  95502. gizmo.dispose();
  95503. }
  95504. }
  95505. this._dragBehavior.detach();
  95506. };
  95507. return GizmoManager;
  95508. }());
  95509. BABYLON.GizmoManager = GizmoManager;
  95510. })(BABYLON || (BABYLON = {}));
  95511. //# sourceMappingURL=babylon.gizmoManager.js.map
  95512. var BABYLON;
  95513. (function (BABYLON) {
  95514. /**
  95515. * Defines a target to use with MorphTargetManager
  95516. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95517. */
  95518. var MorphTarget = /** @class */ (function () {
  95519. /**
  95520. * Creates a new MorphTarget
  95521. * @param name defines the name of the target
  95522. * @param influence defines the influence to use
  95523. */
  95524. function MorphTarget(
  95525. /** defines the name of the target */
  95526. name, influence, scene) {
  95527. if (influence === void 0) { influence = 0; }
  95528. if (scene === void 0) { scene = null; }
  95529. this.name = name;
  95530. /**
  95531. * Gets or sets the list of animations
  95532. */
  95533. this.animations = new Array();
  95534. this._positions = null;
  95535. this._normals = null;
  95536. this._tangents = null;
  95537. /**
  95538. * Observable raised when the influence changes
  95539. */
  95540. this.onInfluenceChanged = new BABYLON.Observable();
  95541. this._animationPropertiesOverride = null;
  95542. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95543. this.influence = influence;
  95544. }
  95545. Object.defineProperty(MorphTarget.prototype, "influence", {
  95546. /**
  95547. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  95548. */
  95549. get: function () {
  95550. return this._influence;
  95551. },
  95552. set: function (influence) {
  95553. if (this._influence === influence) {
  95554. return;
  95555. }
  95556. var previous = this._influence;
  95557. this._influence = influence;
  95558. if (this.onInfluenceChanged.hasObservers) {
  95559. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  95560. }
  95561. },
  95562. enumerable: true,
  95563. configurable: true
  95564. });
  95565. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  95566. /**
  95567. * Gets or sets the animation properties override
  95568. */
  95569. get: function () {
  95570. if (!this._animationPropertiesOverride && this._scene) {
  95571. return this._scene.animationPropertiesOverride;
  95572. }
  95573. return this._animationPropertiesOverride;
  95574. },
  95575. set: function (value) {
  95576. this._animationPropertiesOverride = value;
  95577. },
  95578. enumerable: true,
  95579. configurable: true
  95580. });
  95581. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  95582. /**
  95583. * Gets a boolean defining if the target contains position data
  95584. */
  95585. get: function () {
  95586. return !!this._positions;
  95587. },
  95588. enumerable: true,
  95589. configurable: true
  95590. });
  95591. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  95592. /**
  95593. * Gets a boolean defining if the target contains normal data
  95594. */
  95595. get: function () {
  95596. return !!this._normals;
  95597. },
  95598. enumerable: true,
  95599. configurable: true
  95600. });
  95601. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  95602. /**
  95603. * Gets a boolean defining if the target contains tangent data
  95604. */
  95605. get: function () {
  95606. return !!this._tangents;
  95607. },
  95608. enumerable: true,
  95609. configurable: true
  95610. });
  95611. /**
  95612. * Affects position data to this target
  95613. * @param data defines the position data to use
  95614. */
  95615. MorphTarget.prototype.setPositions = function (data) {
  95616. this._positions = data;
  95617. };
  95618. /**
  95619. * Gets the position data stored in this target
  95620. * @returns a FloatArray containing the position data (or null if not present)
  95621. */
  95622. MorphTarget.prototype.getPositions = function () {
  95623. return this._positions;
  95624. };
  95625. /**
  95626. * Affects normal data to this target
  95627. * @param data defines the normal data to use
  95628. */
  95629. MorphTarget.prototype.setNormals = function (data) {
  95630. this._normals = data;
  95631. };
  95632. /**
  95633. * Gets the normal data stored in this target
  95634. * @returns a FloatArray containing the normal data (or null if not present)
  95635. */
  95636. MorphTarget.prototype.getNormals = function () {
  95637. return this._normals;
  95638. };
  95639. /**
  95640. * Affects tangent data to this target
  95641. * @param data defines the tangent data to use
  95642. */
  95643. MorphTarget.prototype.setTangents = function (data) {
  95644. this._tangents = data;
  95645. };
  95646. /**
  95647. * Gets the tangent data stored in this target
  95648. * @returns a FloatArray containing the tangent data (or null if not present)
  95649. */
  95650. MorphTarget.prototype.getTangents = function () {
  95651. return this._tangents;
  95652. };
  95653. /**
  95654. * Serializes the current target into a Serialization object
  95655. * @returns the serialized object
  95656. */
  95657. MorphTarget.prototype.serialize = function () {
  95658. var serializationObject = {};
  95659. serializationObject.name = this.name;
  95660. serializationObject.influence = this.influence;
  95661. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  95662. if (this.hasNormals) {
  95663. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  95664. }
  95665. if (this.hasTangents) {
  95666. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  95667. }
  95668. // Animations
  95669. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  95670. return serializationObject;
  95671. };
  95672. // Statics
  95673. /**
  95674. * Creates a new target from serialized data
  95675. * @param serializationObject defines the serialized data to use
  95676. * @returns a new MorphTarget
  95677. */
  95678. MorphTarget.Parse = function (serializationObject) {
  95679. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  95680. result.setPositions(serializationObject.positions);
  95681. if (serializationObject.normals) {
  95682. result.setNormals(serializationObject.normals);
  95683. }
  95684. if (serializationObject.tangents) {
  95685. result.setTangents(serializationObject.tangents);
  95686. }
  95687. // Animations
  95688. if (serializationObject.animations) {
  95689. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  95690. var parsedAnimation = serializationObject.animations[animationIndex];
  95691. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  95692. }
  95693. }
  95694. return result;
  95695. };
  95696. /**
  95697. * Creates a MorphTarget from mesh data
  95698. * @param mesh defines the source mesh
  95699. * @param name defines the name to use for the new target
  95700. * @param influence defines the influence to attach to the target
  95701. * @returns a new MorphTarget
  95702. */
  95703. MorphTarget.FromMesh = function (mesh, name, influence) {
  95704. if (!name) {
  95705. name = mesh.name;
  95706. }
  95707. var result = new MorphTarget(name, influence, mesh.getScene());
  95708. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  95709. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95710. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  95711. }
  95712. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  95713. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  95714. }
  95715. return result;
  95716. };
  95717. return MorphTarget;
  95718. }());
  95719. BABYLON.MorphTarget = MorphTarget;
  95720. })(BABYLON || (BABYLON = {}));
  95721. //# sourceMappingURL=babylon.morphTarget.js.map
  95722. var BABYLON;
  95723. (function (BABYLON) {
  95724. /**
  95725. * This class is used to deform meshes using morphing between different targets
  95726. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95727. */
  95728. var MorphTargetManager = /** @class */ (function () {
  95729. /**
  95730. * Creates a new MorphTargetManager
  95731. * @param scene defines the current scene
  95732. */
  95733. function MorphTargetManager(scene) {
  95734. if (scene === void 0) { scene = null; }
  95735. this._targets = new Array();
  95736. this._targetObservable = new Array();
  95737. this._activeTargets = new BABYLON.SmartArray(16);
  95738. this._supportsNormals = false;
  95739. this._supportsTangents = false;
  95740. this._vertexCount = 0;
  95741. this._uniqueId = 0;
  95742. this._tempInfluences = new Array();
  95743. if (!scene) {
  95744. scene = BABYLON.Engine.LastCreatedScene;
  95745. }
  95746. this._scene = scene;
  95747. if (this._scene) {
  95748. this._scene.morphTargetManagers.push(this);
  95749. this._uniqueId = this._scene.getUniqueId();
  95750. }
  95751. }
  95752. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  95753. /**
  95754. * Gets the unique ID of this manager
  95755. */
  95756. get: function () {
  95757. return this._uniqueId;
  95758. },
  95759. enumerable: true,
  95760. configurable: true
  95761. });
  95762. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  95763. /**
  95764. * Gets the number of vertices handled by this manager
  95765. */
  95766. get: function () {
  95767. return this._vertexCount;
  95768. },
  95769. enumerable: true,
  95770. configurable: true
  95771. });
  95772. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  95773. /**
  95774. * Gets a boolean indicating if this manager supports morphing of normals
  95775. */
  95776. get: function () {
  95777. return this._supportsNormals;
  95778. },
  95779. enumerable: true,
  95780. configurable: true
  95781. });
  95782. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  95783. /**
  95784. * Gets a boolean indicating if this manager supports morphing of tangents
  95785. */
  95786. get: function () {
  95787. return this._supportsTangents;
  95788. },
  95789. enumerable: true,
  95790. configurable: true
  95791. });
  95792. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  95793. /**
  95794. * Gets the number of targets stored in this manager
  95795. */
  95796. get: function () {
  95797. return this._targets.length;
  95798. },
  95799. enumerable: true,
  95800. configurable: true
  95801. });
  95802. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  95803. /**
  95804. * Gets the number of influencers (ie. the number of targets with influences > 0)
  95805. */
  95806. get: function () {
  95807. return this._activeTargets.length;
  95808. },
  95809. enumerable: true,
  95810. configurable: true
  95811. });
  95812. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  95813. /**
  95814. * Gets the list of influences (one per target)
  95815. */
  95816. get: function () {
  95817. return this._influences;
  95818. },
  95819. enumerable: true,
  95820. configurable: true
  95821. });
  95822. /**
  95823. * Gets the active target at specified index. An active target is a target with an influence > 0
  95824. * @param index defines the index to check
  95825. * @returns the requested target
  95826. */
  95827. MorphTargetManager.prototype.getActiveTarget = function (index) {
  95828. return this._activeTargets.data[index];
  95829. };
  95830. /**
  95831. * Gets the target at specified index
  95832. * @param index defines the index to check
  95833. * @returns the requested target
  95834. */
  95835. MorphTargetManager.prototype.getTarget = function (index) {
  95836. return this._targets[index];
  95837. };
  95838. /**
  95839. * Add a new target to this manager
  95840. * @param target defines the target to add
  95841. */
  95842. MorphTargetManager.prototype.addTarget = function (target) {
  95843. var _this = this;
  95844. this._targets.push(target);
  95845. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  95846. _this._syncActiveTargets(needUpdate);
  95847. }));
  95848. this._syncActiveTargets(true);
  95849. };
  95850. /**
  95851. * Removes a target from the manager
  95852. * @param target defines the target to remove
  95853. */
  95854. MorphTargetManager.prototype.removeTarget = function (target) {
  95855. var index = this._targets.indexOf(target);
  95856. if (index >= 0) {
  95857. this._targets.splice(index, 1);
  95858. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  95859. this._syncActiveTargets(true);
  95860. }
  95861. };
  95862. /**
  95863. * Serializes the current manager into a Serialization object
  95864. * @returns the serialized object
  95865. */
  95866. MorphTargetManager.prototype.serialize = function () {
  95867. var serializationObject = {};
  95868. serializationObject.id = this.uniqueId;
  95869. serializationObject.targets = [];
  95870. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95871. var target = _a[_i];
  95872. serializationObject.targets.push(target.serialize());
  95873. }
  95874. return serializationObject;
  95875. };
  95876. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  95877. var influenceCount = 0;
  95878. this._activeTargets.reset();
  95879. this._supportsNormals = true;
  95880. this._supportsTangents = true;
  95881. this._vertexCount = 0;
  95882. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95883. var target = _a[_i];
  95884. this._activeTargets.push(target);
  95885. this._tempInfluences[influenceCount++] = target.influence;
  95886. var positions = target.getPositions();
  95887. if (positions) {
  95888. this._supportsNormals = this._supportsNormals && target.hasNormals;
  95889. this._supportsTangents = this._supportsTangents && target.hasTangents;
  95890. var vertexCount = positions.length / 3;
  95891. if (this._vertexCount === 0) {
  95892. this._vertexCount = vertexCount;
  95893. }
  95894. else if (this._vertexCount !== vertexCount) {
  95895. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  95896. return;
  95897. }
  95898. }
  95899. }
  95900. if (!this._influences || this._influences.length !== influenceCount) {
  95901. this._influences = new Float32Array(influenceCount);
  95902. }
  95903. for (var index = 0; index < influenceCount; index++) {
  95904. this._influences[index] = this._tempInfluences[index];
  95905. }
  95906. if (needUpdate) {
  95907. this.synchronize();
  95908. }
  95909. };
  95910. /**
  95911. * Syncrhonize the targets with all the meshes using this morph target manager
  95912. */
  95913. MorphTargetManager.prototype.synchronize = function () {
  95914. if (!this._scene) {
  95915. return;
  95916. }
  95917. // Flag meshes as dirty to resync with the active targets
  95918. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  95919. var mesh = _a[_i];
  95920. if (mesh.morphTargetManager === this) {
  95921. mesh._syncGeometryWithMorphTargetManager();
  95922. }
  95923. }
  95924. };
  95925. // Statics
  95926. /**
  95927. * Creates a new MorphTargetManager from serialized data
  95928. * @param serializationObject defines the serialized data
  95929. * @param scene defines the hosting scene
  95930. * @returns the new MorphTargetManager
  95931. */
  95932. MorphTargetManager.Parse = function (serializationObject, scene) {
  95933. var result = new MorphTargetManager(scene);
  95934. result._uniqueId = serializationObject.id;
  95935. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  95936. var targetData = _a[_i];
  95937. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  95938. }
  95939. return result;
  95940. };
  95941. return MorphTargetManager;
  95942. }());
  95943. BABYLON.MorphTargetManager = MorphTargetManager;
  95944. })(BABYLON || (BABYLON = {}));
  95945. //# sourceMappingURL=babylon.morphTargetManager.js.map
  95946. var BABYLON;
  95947. (function (BABYLON) {
  95948. var Octree = /** @class */ (function () {
  95949. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  95950. if (maxDepth === void 0) { maxDepth = 2; }
  95951. this.maxDepth = maxDepth;
  95952. this.dynamicContent = new Array();
  95953. this._maxBlockCapacity = maxBlockCapacity || 64;
  95954. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  95955. this._creationFunc = creationFunc;
  95956. }
  95957. // Methods
  95958. Octree.prototype.update = function (worldMin, worldMax, entries) {
  95959. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  95960. };
  95961. Octree.prototype.addMesh = function (entry) {
  95962. for (var index = 0; index < this.blocks.length; index++) {
  95963. var block = this.blocks[index];
  95964. block.addEntry(entry);
  95965. }
  95966. };
  95967. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  95968. this._selectionContent.reset();
  95969. for (var index = 0; index < this.blocks.length; index++) {
  95970. var block = this.blocks[index];
  95971. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  95972. }
  95973. if (allowDuplicate) {
  95974. this._selectionContent.concat(this.dynamicContent);
  95975. }
  95976. else {
  95977. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95978. }
  95979. return this._selectionContent;
  95980. };
  95981. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  95982. this._selectionContent.reset();
  95983. for (var index = 0; index < this.blocks.length; index++) {
  95984. var block = this.blocks[index];
  95985. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  95986. }
  95987. if (allowDuplicate) {
  95988. this._selectionContent.concat(this.dynamicContent);
  95989. }
  95990. else {
  95991. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95992. }
  95993. return this._selectionContent;
  95994. };
  95995. Octree.prototype.intersectsRay = function (ray) {
  95996. this._selectionContent.reset();
  95997. for (var index = 0; index < this.blocks.length; index++) {
  95998. var block = this.blocks[index];
  95999. block.intersectsRay(ray, this._selectionContent);
  96000. }
  96001. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  96002. return this._selectionContent;
  96003. };
  96004. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  96005. target.blocks = new Array();
  96006. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  96007. // Segmenting space
  96008. for (var x = 0; x < 2; x++) {
  96009. for (var y = 0; y < 2; y++) {
  96010. for (var z = 0; z < 2; z++) {
  96011. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  96012. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  96013. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  96014. block.addEntries(entries);
  96015. target.blocks.push(block);
  96016. }
  96017. }
  96018. }
  96019. };
  96020. Octree.CreationFuncForMeshes = function (entry, block) {
  96021. var boundingInfo = entry.getBoundingInfo();
  96022. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  96023. block.entries.push(entry);
  96024. }
  96025. };
  96026. Octree.CreationFuncForSubMeshes = function (entry, block) {
  96027. var boundingInfo = entry.getBoundingInfo();
  96028. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  96029. block.entries.push(entry);
  96030. }
  96031. };
  96032. return Octree;
  96033. }());
  96034. BABYLON.Octree = Octree;
  96035. })(BABYLON || (BABYLON = {}));
  96036. //# sourceMappingURL=babylon.octree.js.map
  96037. var BABYLON;
  96038. (function (BABYLON) {
  96039. var OctreeBlock = /** @class */ (function () {
  96040. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  96041. this.entries = new Array();
  96042. this._boundingVectors = new Array();
  96043. this._capacity = capacity;
  96044. this._depth = depth;
  96045. this._maxDepth = maxDepth;
  96046. this._creationFunc = creationFunc;
  96047. this._minPoint = minPoint;
  96048. this._maxPoint = maxPoint;
  96049. this._boundingVectors.push(minPoint.clone());
  96050. this._boundingVectors.push(maxPoint.clone());
  96051. this._boundingVectors.push(minPoint.clone());
  96052. this._boundingVectors[2].x = maxPoint.x;
  96053. this._boundingVectors.push(minPoint.clone());
  96054. this._boundingVectors[3].y = maxPoint.y;
  96055. this._boundingVectors.push(minPoint.clone());
  96056. this._boundingVectors[4].z = maxPoint.z;
  96057. this._boundingVectors.push(maxPoint.clone());
  96058. this._boundingVectors[5].z = minPoint.z;
  96059. this._boundingVectors.push(maxPoint.clone());
  96060. this._boundingVectors[6].x = minPoint.x;
  96061. this._boundingVectors.push(maxPoint.clone());
  96062. this._boundingVectors[7].y = minPoint.y;
  96063. }
  96064. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  96065. // Property
  96066. get: function () {
  96067. return this._capacity;
  96068. },
  96069. enumerable: true,
  96070. configurable: true
  96071. });
  96072. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  96073. get: function () {
  96074. return this._minPoint;
  96075. },
  96076. enumerable: true,
  96077. configurable: true
  96078. });
  96079. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  96080. get: function () {
  96081. return this._maxPoint;
  96082. },
  96083. enumerable: true,
  96084. configurable: true
  96085. });
  96086. // Methods
  96087. OctreeBlock.prototype.addEntry = function (entry) {
  96088. if (this.blocks) {
  96089. for (var index = 0; index < this.blocks.length; index++) {
  96090. var block = this.blocks[index];
  96091. block.addEntry(entry);
  96092. }
  96093. return;
  96094. }
  96095. this._creationFunc(entry, this);
  96096. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  96097. this.createInnerBlocks();
  96098. }
  96099. };
  96100. OctreeBlock.prototype.addEntries = function (entries) {
  96101. for (var index = 0; index < entries.length; index++) {
  96102. var mesh = entries[index];
  96103. this.addEntry(mesh);
  96104. }
  96105. };
  96106. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  96107. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  96108. if (this.blocks) {
  96109. for (var index = 0; index < this.blocks.length; index++) {
  96110. var block = this.blocks[index];
  96111. block.select(frustumPlanes, selection, allowDuplicate);
  96112. }
  96113. return;
  96114. }
  96115. if (allowDuplicate) {
  96116. selection.concat(this.entries);
  96117. }
  96118. else {
  96119. selection.concatWithNoDuplicate(this.entries);
  96120. }
  96121. }
  96122. };
  96123. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  96124. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  96125. if (this.blocks) {
  96126. for (var index = 0; index < this.blocks.length; index++) {
  96127. var block = this.blocks[index];
  96128. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  96129. }
  96130. return;
  96131. }
  96132. if (allowDuplicate) {
  96133. selection.concat(this.entries);
  96134. }
  96135. else {
  96136. selection.concatWithNoDuplicate(this.entries);
  96137. }
  96138. }
  96139. };
  96140. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  96141. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  96142. if (this.blocks) {
  96143. for (var index = 0; index < this.blocks.length; index++) {
  96144. var block = this.blocks[index];
  96145. block.intersectsRay(ray, selection);
  96146. }
  96147. return;
  96148. }
  96149. selection.concatWithNoDuplicate(this.entries);
  96150. }
  96151. };
  96152. OctreeBlock.prototype.createInnerBlocks = function () {
  96153. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  96154. };
  96155. return OctreeBlock;
  96156. }());
  96157. BABYLON.OctreeBlock = OctreeBlock;
  96158. })(BABYLON || (BABYLON = {}));
  96159. //# sourceMappingURL=babylon.octreeBlock.js.map
  96160. var BABYLON;
  96161. (function (BABYLON) {
  96162. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  96163. if (maxCapacity === void 0) { maxCapacity = 64; }
  96164. if (maxDepth === void 0) { maxDepth = 2; }
  96165. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  96166. if (!component) {
  96167. component = new OctreeSceneComponent(this);
  96168. this._addComponent(component);
  96169. }
  96170. if (!this._selectionOctree) {
  96171. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  96172. }
  96173. var worldExtends = this.getWorldExtends();
  96174. // Update octree
  96175. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  96176. return this._selectionOctree;
  96177. };
  96178. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  96179. get: function () {
  96180. return this._selectionOctree;
  96181. },
  96182. enumerable: true,
  96183. configurable: true
  96184. });
  96185. /**
  96186. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  96187. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  96188. * @param maxCapacity defines the maximum size of each block (64 by default)
  96189. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  96190. * @returns the new octree
  96191. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  96192. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  96193. */
  96194. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  96195. if (maxCapacity === void 0) { maxCapacity = 64; }
  96196. if (maxDepth === void 0) { maxDepth = 2; }
  96197. var scene = this.getScene();
  96198. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  96199. if (!component) {
  96200. component = new OctreeSceneComponent(scene);
  96201. scene._addComponent(component);
  96202. }
  96203. if (!this._submeshesOctree) {
  96204. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  96205. }
  96206. this.computeWorldMatrix(true);
  96207. var boundingInfo = this.getBoundingInfo();
  96208. // Update octree
  96209. var bbox = boundingInfo.boundingBox;
  96210. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  96211. return this._submeshesOctree;
  96212. };
  96213. /**
  96214. * Defines the octree scene component responsible to manage any octrees
  96215. * in a given scene.
  96216. */
  96217. var OctreeSceneComponent = /** @class */ (function () {
  96218. /**
  96219. * Creates a new instance of the component for the given scene
  96220. * @param scene Defines the scene to register the component in
  96221. */
  96222. function OctreeSceneComponent(scene) {
  96223. /**
  96224. * The component name helpfull to identify the component in the list of scene components.
  96225. */
  96226. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  96227. /**
  96228. * Indicates if the meshes have been checked to make sure they are isEnabled()
  96229. */
  96230. this.checksIsEnabled = true;
  96231. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  96232. this.scene = scene;
  96233. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  96234. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  96235. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  96236. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  96237. }
  96238. /**
  96239. * Registers the component in a given scene
  96240. */
  96241. OctreeSceneComponent.prototype.register = function () {
  96242. var _this = this;
  96243. this.scene.onMeshRemovedObservable.add(function (mesh) {
  96244. var sceneOctree = _this.scene.selectionOctree;
  96245. if (sceneOctree !== undefined && sceneOctree !== null) {
  96246. var index = sceneOctree.dynamicContent.indexOf(mesh);
  96247. if (index !== -1) {
  96248. sceneOctree.dynamicContent.splice(index, 1);
  96249. }
  96250. }
  96251. });
  96252. this.scene.onMeshImportedObservable.add(function (mesh) {
  96253. var sceneOctree = _this.scene.selectionOctree;
  96254. if (sceneOctree !== undefined && sceneOctree !== null) {
  96255. sceneOctree.addMesh(mesh);
  96256. }
  96257. });
  96258. };
  96259. /**
  96260. * Return the list of active meshes
  96261. * @returns the list of active meshes
  96262. */
  96263. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  96264. if (this.scene._selectionOctree) {
  96265. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  96266. return selection;
  96267. }
  96268. return this.scene._getDefaultMeshCandidates();
  96269. };
  96270. /**
  96271. * Return the list of active sub meshes
  96272. * @param mesh The mesh to get the candidates sub meshes from
  96273. * @returns the list of active sub meshes
  96274. */
  96275. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  96276. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  96277. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  96278. return intersections;
  96279. }
  96280. return this.scene._getDefaultSubMeshCandidates(mesh);
  96281. };
  96282. /**
  96283. * Return the list of sub meshes intersecting with a given local ray
  96284. * @param mesh defines the mesh to find the submesh for
  96285. * @param localRay defines the ray in local space
  96286. * @returns the list of intersecting sub meshes
  96287. */
  96288. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  96289. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  96290. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  96291. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  96292. return intersections;
  96293. }
  96294. return this.scene._getDefaultSubMeshCandidates(mesh);
  96295. };
  96296. /**
  96297. * Return the list of sub meshes colliding with a collider
  96298. * @param mesh defines the mesh to find the submesh for
  96299. * @param collider defines the collider to evaluate the collision against
  96300. * @returns the list of colliding sub meshes
  96301. */
  96302. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  96303. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  96304. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  96305. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  96306. return intersections;
  96307. }
  96308. return this.scene._getDefaultSubMeshCandidates(mesh);
  96309. };
  96310. /**
  96311. * Rebuilds the elements related to this component in case of
  96312. * context lost for instance.
  96313. */
  96314. OctreeSceneComponent.prototype.rebuild = function () {
  96315. // Nothing to do here.
  96316. };
  96317. /**
  96318. * Disposes the component and the associated ressources.
  96319. */
  96320. OctreeSceneComponent.prototype.dispose = function () {
  96321. // Nothing to do here.
  96322. };
  96323. return OctreeSceneComponent;
  96324. }());
  96325. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  96326. })(BABYLON || (BABYLON = {}));
  96327. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  96328. var BABYLON;
  96329. (function (BABYLON) {
  96330. /**
  96331. * Postprocess used to generate anaglyphic rendering
  96332. */
  96333. var AnaglyphPostProcess = /** @class */ (function (_super) {
  96334. __extends(AnaglyphPostProcess, _super);
  96335. /**
  96336. * Creates a new AnaglyphPostProcess
  96337. * @param name defines postprocess name
  96338. * @param options defines creation options or target ratio scale
  96339. * @param rigCameras defines cameras using this postprocess
  96340. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  96341. * @param engine defines hosting engine
  96342. * @param reusable defines if the postprocess will be reused multiple times per frame
  96343. */
  96344. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  96345. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  96346. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96347. _this.onApplyObservable.add(function (effect) {
  96348. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  96349. });
  96350. return _this;
  96351. }
  96352. return AnaglyphPostProcess;
  96353. }(BABYLON.PostProcess));
  96354. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  96355. })(BABYLON || (BABYLON = {}));
  96356. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  96357. var BABYLON;
  96358. (function (BABYLON) {
  96359. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  96360. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96361. });
  96362. /**
  96363. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  96364. */
  96365. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  96366. __extends(AnaglyphArcRotateCamera, _super);
  96367. /**
  96368. * Creates a new AnaglyphArcRotateCamera
  96369. * @param name defines camera name
  96370. * @param alpha defines alpha angle (in radians)
  96371. * @param beta defines beta angle (in radians)
  96372. * @param radius defines radius
  96373. * @param target defines camera target
  96374. * @param interaxialDistance defines distance between each color axis
  96375. * @param scene defines the hosting scene
  96376. */
  96377. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  96378. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96379. _this.interaxialDistance = interaxialDistance;
  96380. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96381. return _this;
  96382. }
  96383. /**
  96384. * Gets camera class name
  96385. * @returns AnaglyphArcRotateCamera
  96386. */
  96387. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  96388. return "AnaglyphArcRotateCamera";
  96389. };
  96390. return AnaglyphArcRotateCamera;
  96391. }(BABYLON.ArcRotateCamera));
  96392. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  96393. })(BABYLON || (BABYLON = {}));
  96394. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  96395. var BABYLON;
  96396. (function (BABYLON) {
  96397. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  96398. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96399. });
  96400. /**
  96401. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  96402. */
  96403. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  96404. __extends(AnaglyphFreeCamera, _super);
  96405. /**
  96406. * Creates a new AnaglyphFreeCamera
  96407. * @param name defines camera name
  96408. * @param position defines initial position
  96409. * @param interaxialDistance defines distance between each color axis
  96410. * @param scene defines the hosting scene
  96411. */
  96412. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  96413. var _this = _super.call(this, name, position, scene) || this;
  96414. _this.interaxialDistance = interaxialDistance;
  96415. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96416. return _this;
  96417. }
  96418. /**
  96419. * Gets camera class name
  96420. * @returns AnaglyphFreeCamera
  96421. */
  96422. AnaglyphFreeCamera.prototype.getClassName = function () {
  96423. return "AnaglyphFreeCamera";
  96424. };
  96425. return AnaglyphFreeCamera;
  96426. }(BABYLON.FreeCamera));
  96427. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  96428. })(BABYLON || (BABYLON = {}));
  96429. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  96430. var BABYLON;
  96431. (function (BABYLON) {
  96432. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  96433. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96434. });
  96435. /**
  96436. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  96437. */
  96438. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  96439. __extends(AnaglyphGamepadCamera, _super);
  96440. /**
  96441. * Creates a new AnaglyphGamepadCamera
  96442. * @param name defines camera name
  96443. * @param position defines initial position
  96444. * @param interaxialDistance defines distance between each color axis
  96445. * @param scene defines the hosting scene
  96446. */
  96447. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  96448. var _this = _super.call(this, name, position, scene) || this;
  96449. _this.interaxialDistance = interaxialDistance;
  96450. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96451. return _this;
  96452. }
  96453. /**
  96454. * Gets camera class name
  96455. * @returns AnaglyphGamepadCamera
  96456. */
  96457. AnaglyphGamepadCamera.prototype.getClassName = function () {
  96458. return "AnaglyphGamepadCamera";
  96459. };
  96460. return AnaglyphGamepadCamera;
  96461. }(BABYLON.GamepadCamera));
  96462. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  96463. })(BABYLON || (BABYLON = {}));
  96464. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  96465. var BABYLON;
  96466. (function (BABYLON) {
  96467. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  96468. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96469. });
  96470. /**
  96471. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  96472. */
  96473. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  96474. __extends(AnaglyphUniversalCamera, _super);
  96475. /**
  96476. * Creates a new AnaglyphUniversalCamera
  96477. * @param name defines camera name
  96478. * @param position defines initial position
  96479. * @param interaxialDistance defines distance between each color axis
  96480. * @param scene defines the hosting scene
  96481. */
  96482. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  96483. var _this = _super.call(this, name, position, scene) || this;
  96484. _this.interaxialDistance = interaxialDistance;
  96485. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96486. return _this;
  96487. }
  96488. /**
  96489. * Gets camera class name
  96490. * @returns AnaglyphUniversalCamera
  96491. */
  96492. AnaglyphUniversalCamera.prototype.getClassName = function () {
  96493. return "AnaglyphUniversalCamera";
  96494. };
  96495. return AnaglyphUniversalCamera;
  96496. }(BABYLON.UniversalCamera));
  96497. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  96498. })(BABYLON || (BABYLON = {}));
  96499. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  96500. var BABYLON;
  96501. (function (BABYLON) {
  96502. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  96503. __extends(StereoscopicInterlacePostProcess, _super);
  96504. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  96505. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  96506. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96507. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96508. _this.onSizeChangedObservable.add(function () {
  96509. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96510. });
  96511. _this.onApplyObservable.add(function (effect) {
  96512. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  96513. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  96514. });
  96515. return _this;
  96516. }
  96517. return StereoscopicInterlacePostProcess;
  96518. }(BABYLON.PostProcess));
  96519. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  96520. })(BABYLON || (BABYLON = {}));
  96521. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  96522. var BABYLON;
  96523. (function (BABYLON) {
  96524. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  96525. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96526. });
  96527. /**
  96528. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  96529. */
  96530. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  96531. __extends(StereoscopicArcRotateCamera, _super);
  96532. /**
  96533. * Creates a new StereoscopicArcRotateCamera
  96534. * @param name defines camera name
  96535. * @param alpha defines alpha angle (in radians)
  96536. * @param beta defines beta angle (in radians)
  96537. * @param radius defines radius
  96538. * @param target defines camera target
  96539. * @param interaxialDistance defines distance between each color axis
  96540. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96541. * @param scene defines the hosting scene
  96542. */
  96543. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  96544. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96545. _this.interaxialDistance = interaxialDistance;
  96546. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96547. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96548. return _this;
  96549. }
  96550. /**
  96551. * Gets camera class name
  96552. * @returns StereoscopicArcRotateCamera
  96553. */
  96554. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  96555. return "StereoscopicArcRotateCamera";
  96556. };
  96557. return StereoscopicArcRotateCamera;
  96558. }(BABYLON.ArcRotateCamera));
  96559. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  96560. })(BABYLON || (BABYLON = {}));
  96561. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  96562. var BABYLON;
  96563. (function (BABYLON) {
  96564. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96565. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96566. });
  96567. /**
  96568. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  96569. */
  96570. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  96571. __extends(StereoscopicFreeCamera, _super);
  96572. /**
  96573. * Creates a new StereoscopicFreeCamera
  96574. * @param name defines camera name
  96575. * @param position defines initial position
  96576. * @param interaxialDistance defines distance between each color axis
  96577. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96578. * @param scene defines the hosting scene
  96579. */
  96580. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96581. var _this = _super.call(this, name, position, scene) || this;
  96582. _this.interaxialDistance = interaxialDistance;
  96583. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96584. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96585. return _this;
  96586. }
  96587. /**
  96588. * Gets camera class name
  96589. * @returns StereoscopicFreeCamera
  96590. */
  96591. StereoscopicFreeCamera.prototype.getClassName = function () {
  96592. return "StereoscopicFreeCamera";
  96593. };
  96594. return StereoscopicFreeCamera;
  96595. }(BABYLON.FreeCamera));
  96596. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  96597. })(BABYLON || (BABYLON = {}));
  96598. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  96599. var BABYLON;
  96600. (function (BABYLON) {
  96601. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  96602. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96603. });
  96604. /**
  96605. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  96606. */
  96607. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  96608. __extends(StereoscopicGamepadCamera, _super);
  96609. /**
  96610. * Creates a new StereoscopicGamepadCamera
  96611. * @param name defines camera name
  96612. * @param position defines initial position
  96613. * @param interaxialDistance defines distance between each color axis
  96614. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96615. * @param scene defines the hosting scene
  96616. */
  96617. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96618. var _this = _super.call(this, name, position, scene) || this;
  96619. _this.interaxialDistance = interaxialDistance;
  96620. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96621. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96622. return _this;
  96623. }
  96624. /**
  96625. * Gets camera class name
  96626. * @returns StereoscopicGamepadCamera
  96627. */
  96628. StereoscopicGamepadCamera.prototype.getClassName = function () {
  96629. return "StereoscopicGamepadCamera";
  96630. };
  96631. return StereoscopicGamepadCamera;
  96632. }(BABYLON.GamepadCamera));
  96633. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  96634. })(BABYLON || (BABYLON = {}));
  96635. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  96636. var BABYLON;
  96637. (function (BABYLON) {
  96638. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96639. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96640. });
  96641. /**
  96642. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  96643. */
  96644. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  96645. __extends(StereoscopicUniversalCamera, _super);
  96646. /**
  96647. * Creates a new StereoscopicUniversalCamera
  96648. * @param name defines camera name
  96649. * @param position defines initial position
  96650. * @param interaxialDistance defines distance between each color axis
  96651. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96652. * @param scene defines the hosting scene
  96653. */
  96654. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96655. var _this = _super.call(this, name, position, scene) || this;
  96656. _this.interaxialDistance = interaxialDistance;
  96657. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96658. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96659. return _this;
  96660. }
  96661. /**
  96662. * Gets camera class name
  96663. * @returns StereoscopicUniversalCamera
  96664. */
  96665. StereoscopicUniversalCamera.prototype.getClassName = function () {
  96666. return "StereoscopicUniversalCamera";
  96667. };
  96668. return StereoscopicUniversalCamera;
  96669. }(BABYLON.UniversalCamera));
  96670. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  96671. })(BABYLON || (BABYLON = {}));
  96672. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  96673. var BABYLON;
  96674. (function (BABYLON) {
  96675. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  96676. __extends(VRDistortionCorrectionPostProcess, _super);
  96677. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  96678. var _this = _super.call(this, name, "vrDistortionCorrection", [
  96679. 'LensCenter',
  96680. 'Scale',
  96681. 'ScaleIn',
  96682. 'HmdWarpParam'
  96683. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  96684. _this._isRightEye = isRightEye;
  96685. _this._distortionFactors = vrMetrics.distortionK;
  96686. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  96687. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  96688. _this.adaptScaleToCurrentViewport = true;
  96689. _this.onSizeChangedObservable.add(function () {
  96690. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  96691. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  96692. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  96693. });
  96694. _this.onApplyObservable.add(function (effect) {
  96695. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  96696. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  96697. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  96698. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  96699. });
  96700. return _this;
  96701. }
  96702. return VRDistortionCorrectionPostProcess;
  96703. }(BABYLON.PostProcess));
  96704. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  96705. })(BABYLON || (BABYLON = {}));
  96706. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  96707. var BABYLON;
  96708. (function (BABYLON) {
  96709. /**
  96710. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  96711. * Screen rotation is taken into account.
  96712. */
  96713. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  96714. function FreeCameraDeviceOrientationInput() {
  96715. var _this = this;
  96716. this._screenOrientationAngle = 0;
  96717. this._screenQuaternion = new BABYLON.Quaternion();
  96718. this._alpha = 0;
  96719. this._beta = 0;
  96720. this._gamma = 0;
  96721. this._orientationChanged = function () {
  96722. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  96723. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  96724. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  96725. };
  96726. this._deviceOrientation = function (evt) {
  96727. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  96728. _this._beta = evt.beta !== null ? evt.beta : 0;
  96729. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  96730. };
  96731. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  96732. this._orientationChanged();
  96733. }
  96734. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  96735. get: function () {
  96736. return this._camera;
  96737. },
  96738. set: function (camera) {
  96739. this._camera = camera;
  96740. if (this._camera != null && !this._camera.rotationQuaternion) {
  96741. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  96742. }
  96743. },
  96744. enumerable: true,
  96745. configurable: true
  96746. });
  96747. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96748. window.addEventListener("orientationchange", this._orientationChanged);
  96749. window.addEventListener("deviceorientation", this._deviceOrientation);
  96750. //In certain cases, the attach control is called AFTER orientation was changed,
  96751. //So this is needed.
  96752. this._orientationChanged();
  96753. };
  96754. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  96755. window.removeEventListener("orientationchange", this._orientationChanged);
  96756. window.removeEventListener("deviceorientation", this._deviceOrientation);
  96757. };
  96758. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  96759. //if no device orientation provided, don't update the rotation.
  96760. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  96761. if (!this._alpha)
  96762. return;
  96763. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  96764. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  96765. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  96766. //Mirror on XY Plane
  96767. this._camera.rotationQuaternion.z *= -1;
  96768. this._camera.rotationQuaternion.w *= -1;
  96769. };
  96770. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  96771. return "FreeCameraDeviceOrientationInput";
  96772. };
  96773. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  96774. return "deviceOrientation";
  96775. };
  96776. return FreeCameraDeviceOrientationInput;
  96777. }());
  96778. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  96779. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  96780. })(BABYLON || (BABYLON = {}));
  96781. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  96782. var BABYLON;
  96783. (function (BABYLON) {
  96784. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  96785. function ArcRotateCameraVRDeviceOrientationInput() {
  96786. this.alphaCorrection = 1;
  96787. this.betaCorrection = 1;
  96788. this.gammaCorrection = 1;
  96789. this._alpha = 0;
  96790. this._gamma = 0;
  96791. this._dirty = false;
  96792. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  96793. }
  96794. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96795. this.camera.attachControl(element, noPreventDefault);
  96796. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  96797. };
  96798. /** @hidden */
  96799. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  96800. if (evt.alpha !== null) {
  96801. this._alpha = +evt.alpha | 0;
  96802. }
  96803. if (evt.gamma !== null) {
  96804. this._gamma = +evt.gamma | 0;
  96805. }
  96806. this._dirty = true;
  96807. };
  96808. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  96809. if (this._dirty) {
  96810. this._dirty = false;
  96811. if (this._gamma < 0) {
  96812. this._gamma = 180 + this._gamma;
  96813. }
  96814. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  96815. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  96816. }
  96817. };
  96818. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  96819. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  96820. };
  96821. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  96822. return "ArcRotateCameraVRDeviceOrientationInput";
  96823. };
  96824. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  96825. return "VRDeviceOrientation";
  96826. };
  96827. return ArcRotateCameraVRDeviceOrientationInput;
  96828. }());
  96829. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  96830. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  96831. })(BABYLON || (BABYLON = {}));
  96832. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  96833. var BABYLON;
  96834. (function (BABYLON) {
  96835. var VRCameraMetrics = /** @class */ (function () {
  96836. function VRCameraMetrics() {
  96837. this.compensateDistortion = true;
  96838. }
  96839. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  96840. get: function () {
  96841. return this.hResolution / (2 * this.vResolution);
  96842. },
  96843. enumerable: true,
  96844. configurable: true
  96845. });
  96846. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  96847. get: function () {
  96848. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  96849. },
  96850. enumerable: true,
  96851. configurable: true
  96852. });
  96853. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  96854. get: function () {
  96855. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96856. var h = (4 * meters) / this.hScreenSize;
  96857. return BABYLON.Matrix.Translation(h, 0, 0);
  96858. },
  96859. enumerable: true,
  96860. configurable: true
  96861. });
  96862. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  96863. get: function () {
  96864. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96865. var h = (4 * meters) / this.hScreenSize;
  96866. return BABYLON.Matrix.Translation(-h, 0, 0);
  96867. },
  96868. enumerable: true,
  96869. configurable: true
  96870. });
  96871. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  96872. get: function () {
  96873. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  96874. },
  96875. enumerable: true,
  96876. configurable: true
  96877. });
  96878. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  96879. get: function () {
  96880. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  96881. },
  96882. enumerable: true,
  96883. configurable: true
  96884. });
  96885. VRCameraMetrics.GetDefault = function () {
  96886. var result = new VRCameraMetrics();
  96887. result.hResolution = 1280;
  96888. result.vResolution = 800;
  96889. result.hScreenSize = 0.149759993;
  96890. result.vScreenSize = 0.0935999975;
  96891. result.vScreenCenter = 0.0467999987;
  96892. result.eyeToScreenDistance = 0.0410000011;
  96893. result.lensSeparationDistance = 0.0635000020;
  96894. result.interpupillaryDistance = 0.0640000030;
  96895. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  96896. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  96897. result.postProcessScaleFactor = 1.714605507808412;
  96898. result.lensCenterOffset = 0.151976421;
  96899. return result;
  96900. };
  96901. return VRCameraMetrics;
  96902. }());
  96903. BABYLON.VRCameraMetrics = VRCameraMetrics;
  96904. })(BABYLON || (BABYLON = {}));
  96905. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  96906. var BABYLON;
  96907. (function (BABYLON) {
  96908. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  96909. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96910. });
  96911. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  96912. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96913. });
  96914. /**
  96915. * This represents a WebVR camera.
  96916. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  96917. * @example http://doc.babylonjs.com/how_to/webvr_camera
  96918. */
  96919. var WebVRFreeCamera = /** @class */ (function (_super) {
  96920. __extends(WebVRFreeCamera, _super);
  96921. /**
  96922. * Instantiates a WebVRFreeCamera.
  96923. * @param name The name of the WebVRFreeCamera
  96924. * @param position The starting anchor position for the camera
  96925. * @param scene The scene the camera belongs to
  96926. * @param webVROptions a set of customizable options for the webVRCamera
  96927. */
  96928. function WebVRFreeCamera(name, position, scene, webVROptions) {
  96929. if (webVROptions === void 0) { webVROptions = {}; }
  96930. var _this = _super.call(this, name, position, scene) || this;
  96931. _this.webVROptions = webVROptions;
  96932. /**
  96933. * @hidden
  96934. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  96935. */
  96936. _this._vrDevice = null;
  96937. /**
  96938. * The rawPose of the vrDevice.
  96939. */
  96940. _this.rawPose = null;
  96941. _this._specsVersion = "1.1";
  96942. _this._attached = false;
  96943. _this._descendants = [];
  96944. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  96945. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  96946. /** @hidden */
  96947. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  96948. _this._standingMatrix = null;
  96949. /**
  96950. * Represents device position in babylon space.
  96951. */
  96952. _this.devicePosition = BABYLON.Vector3.Zero();
  96953. /**
  96954. * Represents device rotation in babylon space.
  96955. */
  96956. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  96957. /**
  96958. * The scale of the device to be used when translating from device space to babylon space.
  96959. */
  96960. _this.deviceScaleFactor = 1;
  96961. _this._deviceToWorld = BABYLON.Matrix.Identity();
  96962. _this._worldToDevice = BABYLON.Matrix.Identity();
  96963. /**
  96964. * References to the webVR controllers for the vrDevice.
  96965. */
  96966. _this.controllers = [];
  96967. /**
  96968. * Emits an event when a controller is attached.
  96969. */
  96970. _this.onControllersAttachedObservable = new BABYLON.Observable();
  96971. /**
  96972. * Emits an event when a controller's mesh has been loaded;
  96973. */
  96974. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  96975. /**
  96976. * Emits an event when the HMD's pose has been updated.
  96977. */
  96978. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  96979. _this._poseSet = false;
  96980. /**
  96981. * If the rig cameras be used as parent instead of this camera.
  96982. */
  96983. _this.rigParenting = true;
  96984. _this._defaultHeight = undefined;
  96985. _this._htmlElementAttached = null;
  96986. _this._detachIfAttached = function () {
  96987. var vrDisplay = _this.getEngine().getVRDevice();
  96988. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  96989. _this.detachControl(_this._htmlElementAttached);
  96990. }
  96991. };
  96992. _this._workingVector = BABYLON.Vector3.Zero();
  96993. _this._oneVector = BABYLON.Vector3.One();
  96994. _this._workingMatrix = BABYLON.Matrix.Identity();
  96995. _this._tmpMatrix = new BABYLON.Matrix();
  96996. _this._cache.position = BABYLON.Vector3.Zero();
  96997. if (webVROptions.defaultHeight) {
  96998. _this._defaultHeight = webVROptions.defaultHeight;
  96999. _this.position.y = _this._defaultHeight;
  97000. }
  97001. _this.minZ = 0.1;
  97002. //legacy support - the compensation boolean was removed.
  97003. if (arguments.length === 5) {
  97004. _this.webVROptions = arguments[4];
  97005. }
  97006. // default webVR options
  97007. if (_this.webVROptions.trackPosition == undefined) {
  97008. _this.webVROptions.trackPosition = true;
  97009. }
  97010. if (_this.webVROptions.controllerMeshes == undefined) {
  97011. _this.webVROptions.controllerMeshes = true;
  97012. }
  97013. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  97014. _this.webVROptions.defaultLightingOnControllers = true;
  97015. }
  97016. _this.rotationQuaternion = new BABYLON.Quaternion();
  97017. if (_this.webVROptions && _this.webVROptions.positionScale) {
  97018. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  97019. }
  97020. //enable VR
  97021. var engine = _this.getEngine();
  97022. _this._onVREnabled = function (success) { if (success) {
  97023. _this.initControllers();
  97024. } };
  97025. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  97026. engine.initWebVR().add(function (event) {
  97027. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  97028. return;
  97029. }
  97030. _this._vrDevice = event.vrDisplay;
  97031. //reset the rig parameters.
  97032. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  97033. if (_this._attached) {
  97034. _this.getEngine().enableVR();
  97035. }
  97036. });
  97037. if (typeof (VRFrameData) !== "undefined")
  97038. _this._frameData = new VRFrameData();
  97039. /**
  97040. * The idea behind the following lines:
  97041. * objects that have the camera as parent should actually have the rig cameras as a parent.
  97042. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  97043. * the second will not show it correctly.
  97044. *
  97045. * To solve this - each object that has the camera as parent will be added to a protected array.
  97046. * When the rig camera renders, it will take this array and set all of those to be its children.
  97047. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  97048. * Amazing!
  97049. */
  97050. scene.onBeforeCameraRenderObservable.add(function (camera) {
  97051. if (camera.parent === _this && _this.rigParenting) {
  97052. _this._descendants = _this.getDescendants(true, function (n) {
  97053. // don't take the cameras or the controllers!
  97054. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  97055. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  97056. return !isController && !isRigCamera;
  97057. });
  97058. _this._descendants.forEach(function (node) {
  97059. node.parent = camera;
  97060. });
  97061. }
  97062. });
  97063. scene.onAfterCameraRenderObservable.add(function (camera) {
  97064. if (camera.parent === _this && _this.rigParenting) {
  97065. _this._descendants.forEach(function (node) {
  97066. node.parent = _this;
  97067. });
  97068. }
  97069. });
  97070. return _this;
  97071. }
  97072. /**
  97073. * Gets the device distance from the ground in meters.
  97074. * @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.
  97075. */
  97076. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  97077. if (this._standingMatrix) {
  97078. // Add standing matrix offset to get real offset from ground in room
  97079. this._standingMatrix.getTranslationToRef(this._workingVector);
  97080. return this._deviceRoomPosition.y + this._workingVector.y;
  97081. }
  97082. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  97083. return this._defaultHeight || 0;
  97084. };
  97085. /**
  97086. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  97087. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  97088. */
  97089. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  97090. var _this = this;
  97091. if (callback === void 0) { callback = function (bool) { }; }
  97092. // Use standing matrix if available
  97093. this.getEngine().initWebVRAsync().then(function (result) {
  97094. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  97095. callback(false);
  97096. }
  97097. else {
  97098. _this._standingMatrix = new BABYLON.Matrix();
  97099. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  97100. if (!_this.getScene().useRightHandedSystem) {
  97101. [2, 6, 8, 9, 14].forEach(function (num) {
  97102. if (_this._standingMatrix) {
  97103. _this._standingMatrix.m[num] *= -1;
  97104. }
  97105. });
  97106. }
  97107. callback(true);
  97108. }
  97109. });
  97110. };
  97111. /**
  97112. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  97113. * @returns A promise with a boolean set to if the standing matrix is supported.
  97114. */
  97115. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  97116. var _this = this;
  97117. return new Promise(function (res, rej) {
  97118. _this.useStandingMatrix(function (supported) {
  97119. res(supported);
  97120. });
  97121. });
  97122. };
  97123. /**
  97124. * Disposes the camera
  97125. */
  97126. WebVRFreeCamera.prototype.dispose = function () {
  97127. this._detachIfAttached();
  97128. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  97129. _super.prototype.dispose.call(this);
  97130. };
  97131. /**
  97132. * Gets a vrController by name.
  97133. * @param name The name of the controller to retreive
  97134. * @returns the controller matching the name specified or null if not found
  97135. */
  97136. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  97137. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  97138. var gp = _a[_i];
  97139. if (gp.hand === name) {
  97140. return gp;
  97141. }
  97142. }
  97143. return null;
  97144. };
  97145. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  97146. /**
  97147. * The controller corrisponding to the users left hand.
  97148. */
  97149. get: function () {
  97150. if (!this._leftController) {
  97151. this._leftController = this.getControllerByName("left");
  97152. }
  97153. return this._leftController;
  97154. },
  97155. enumerable: true,
  97156. configurable: true
  97157. });
  97158. ;
  97159. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  97160. /**
  97161. * The controller corrisponding to the users right hand.
  97162. */
  97163. get: function () {
  97164. if (!this._rightController) {
  97165. this._rightController = this.getControllerByName("right");
  97166. }
  97167. return this._rightController;
  97168. },
  97169. enumerable: true,
  97170. configurable: true
  97171. });
  97172. ;
  97173. /**
  97174. * Casts a ray forward from the vrCamera's gaze.
  97175. * @param length Length of the ray (default: 100)
  97176. * @returns the ray corrisponding to the gaze
  97177. */
  97178. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  97179. if (length === void 0) { length = 100; }
  97180. if (this.leftCamera) {
  97181. // Use left eye to avoid computation to compute center on every call
  97182. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  97183. }
  97184. else {
  97185. return _super.prototype.getForwardRay.call(this, length);
  97186. }
  97187. };
  97188. /**
  97189. * @hidden
  97190. * Updates the camera based on device's frame data
  97191. */
  97192. WebVRFreeCamera.prototype._checkInputs = function () {
  97193. if (this._vrDevice && this._vrDevice.isPresenting) {
  97194. this._vrDevice.getFrameData(this._frameData);
  97195. this.updateFromDevice(this._frameData.pose);
  97196. }
  97197. _super.prototype._checkInputs.call(this);
  97198. };
  97199. /**
  97200. * Updates the poseControlled values based on the input device pose.
  97201. * @param poseData Pose coming from the device
  97202. */
  97203. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  97204. if (poseData && poseData.orientation) {
  97205. this.rawPose = poseData;
  97206. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  97207. if (this.getScene().useRightHandedSystem) {
  97208. this._deviceRoomRotationQuaternion.z *= -1;
  97209. this._deviceRoomRotationQuaternion.w *= -1;
  97210. }
  97211. if (this.webVROptions.trackPosition && this.rawPose.position) {
  97212. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  97213. if (this.getScene().useRightHandedSystem) {
  97214. this._deviceRoomPosition.z *= -1;
  97215. }
  97216. }
  97217. this._poseSet = true;
  97218. }
  97219. };
  97220. /**
  97221. * WebVR's attach control will start broadcasting frames to the device.
  97222. * Note that in certain browsers (chrome for example) this function must be called
  97223. * within a user-interaction callback. Example:
  97224. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  97225. *
  97226. * @param element html element to attach the vrDevice to
  97227. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  97228. */
  97229. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  97230. _super.prototype.attachControl.call(this, element, noPreventDefault);
  97231. this._attached = true;
  97232. this._htmlElementAttached = element;
  97233. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  97234. if (this._vrDevice) {
  97235. this.getEngine().enableVR();
  97236. }
  97237. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  97238. };
  97239. /**
  97240. * Detaches the camera from the html element and disables VR
  97241. *
  97242. * @param element html element to detach from
  97243. */
  97244. WebVRFreeCamera.prototype.detachControl = function (element) {
  97245. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  97246. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  97247. _super.prototype.detachControl.call(this, element);
  97248. this._attached = false;
  97249. this.getEngine().disableVR();
  97250. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  97251. };
  97252. /**
  97253. * @returns the name of this class
  97254. */
  97255. WebVRFreeCamera.prototype.getClassName = function () {
  97256. return "WebVRFreeCamera";
  97257. };
  97258. /**
  97259. * Calls resetPose on the vrDisplay
  97260. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  97261. */
  97262. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  97263. //uses the vrDisplay's "resetPose()".
  97264. //pitch and roll won't be affected.
  97265. this._vrDevice.resetPose();
  97266. };
  97267. /**
  97268. * @hidden
  97269. * Updates the rig cameras (left and right eye)
  97270. */
  97271. WebVRFreeCamera.prototype._updateRigCameras = function () {
  97272. var camLeft = this._rigCameras[0];
  97273. var camRight = this._rigCameras[1];
  97274. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  97275. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  97276. camLeft.position.copyFrom(this._deviceRoomPosition);
  97277. camRight.position.copyFrom(this._deviceRoomPosition);
  97278. };
  97279. // Remove translation from 6dof headset if trackposition is set to false
  97280. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  97281. if (isViewMatrix === void 0) { isViewMatrix = false; }
  97282. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  97283. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  97284. if (!isViewMatrix) {
  97285. this._tmpMatrix.invert();
  97286. }
  97287. this._tmpMatrix.multiplyToRef(matrix, matrix);
  97288. }
  97289. };
  97290. /**
  97291. * @hidden
  97292. * Updates the cached values of the camera
  97293. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  97294. */
  97295. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  97296. var _this = this;
  97297. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  97298. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  97299. if (!this.updateCacheCalled) {
  97300. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  97301. this.updateCacheCalled = true;
  97302. this.update();
  97303. }
  97304. // Set working vector to the device position in room space rotated by the new rotation
  97305. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  97306. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  97307. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  97308. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  97309. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  97310. // Add translation from anchor position
  97311. this._deviceToWorld.getTranslationToRef(this._workingVector);
  97312. this._workingVector.addInPlace(this.position);
  97313. this._workingVector.subtractInPlace(this._cache.position);
  97314. this._deviceToWorld.setTranslation(this._workingVector);
  97315. // Set an inverted matrix to be used when updating the camera
  97316. this._deviceToWorld.invertToRef(this._worldToDevice);
  97317. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  97318. this.controllers.forEach(function (controller) {
  97319. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  97320. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  97321. controller.update();
  97322. });
  97323. }
  97324. if (!ignoreParentClass) {
  97325. _super.prototype._updateCache.call(this);
  97326. }
  97327. this.updateCacheCalled = false;
  97328. };
  97329. /**
  97330. * Updates the current device position and rotation in the babylon world
  97331. */
  97332. WebVRFreeCamera.prototype.update = function () {
  97333. // Get current device position in babylon world
  97334. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  97335. // Get current device rotation in babylon world
  97336. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  97337. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  97338. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  97339. if (this._poseSet) {
  97340. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  97341. }
  97342. _super.prototype.update.call(this);
  97343. };
  97344. /**
  97345. * @hidden
  97346. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  97347. * @returns an identity matrix
  97348. */
  97349. WebVRFreeCamera.prototype._getViewMatrix = function () {
  97350. return BABYLON.Matrix.Identity();
  97351. };
  97352. /**
  97353. * This function is called by the two RIG cameras.
  97354. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  97355. */
  97356. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  97357. var _this = this;
  97358. // Update the parent camera prior to using a child camera to avoid desynchronization
  97359. var parentCamera = this._cameraRigParams["parentCamera"];
  97360. parentCamera._updateCache();
  97361. //WebVR 1.1
  97362. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  97363. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  97364. if (!this.getScene().useRightHandedSystem) {
  97365. [2, 6, 8, 9, 14].forEach(function (num) {
  97366. _this._webvrViewMatrix.m[num] *= -1;
  97367. });
  97368. }
  97369. // update the camera rotation matrix
  97370. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  97371. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  97372. // Computing target and final matrix
  97373. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  97374. // should the view matrix be updated with scale and position offset?
  97375. if (parentCamera.deviceScaleFactor !== 1) {
  97376. this._webvrViewMatrix.invert();
  97377. // scale the position, if set
  97378. if (parentCamera.deviceScaleFactor) {
  97379. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  97380. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  97381. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  97382. }
  97383. this._webvrViewMatrix.invert();
  97384. }
  97385. // Remove translation from 6dof headset if trackposition is set to false
  97386. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  97387. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  97388. // Compute global position
  97389. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  97390. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  97391. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  97392. this._workingMatrix.getTranslationToRef(this._globalPosition);
  97393. this._markSyncedWithParent();
  97394. return this._webvrViewMatrix;
  97395. };
  97396. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  97397. var _this = this;
  97398. var parentCamera = this.parent;
  97399. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  97400. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  97401. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  97402. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  97403. //babylon compatible matrix
  97404. if (!this.getScene().useRightHandedSystem) {
  97405. [8, 9, 10, 11].forEach(function (num) {
  97406. _this._projectionMatrix.m[num] *= -1;
  97407. });
  97408. }
  97409. return this._projectionMatrix;
  97410. };
  97411. /**
  97412. * Initializes the controllers and their meshes
  97413. */
  97414. WebVRFreeCamera.prototype.initControllers = function () {
  97415. var _this = this;
  97416. this.controllers = [];
  97417. var manager = this.getScene().gamepadManager;
  97418. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  97419. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  97420. var webVrController = gamepad;
  97421. if (webVrController.defaultModel) {
  97422. webVrController.defaultModel.setEnabled(false);
  97423. }
  97424. if (webVrController.hand === "right") {
  97425. _this._rightController = null;
  97426. }
  97427. if (webVrController.hand === "left") {
  97428. _this._leftController = null;
  97429. }
  97430. var controllerIndex = _this.controllers.indexOf(webVrController);
  97431. if (controllerIndex !== -1) {
  97432. _this.controllers.splice(controllerIndex, 1);
  97433. }
  97434. }
  97435. });
  97436. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  97437. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  97438. var webVrController_1 = gamepad;
  97439. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  97440. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  97441. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  97442. if (_this.webVROptions.controllerMeshes) {
  97443. if (webVrController_1.defaultModel) {
  97444. webVrController_1.defaultModel.setEnabled(true);
  97445. }
  97446. else {
  97447. // Load the meshes
  97448. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  97449. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  97450. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  97451. if (_this.webVROptions.defaultLightingOnControllers) {
  97452. if (!_this._lightOnControllers) {
  97453. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  97454. }
  97455. var activateLightOnSubMeshes_1 = function (mesh, light) {
  97456. var children = mesh.getChildren();
  97457. if (children && children.length !== 0) {
  97458. children.forEach(function (mesh) {
  97459. light.includedOnlyMeshes.push(mesh);
  97460. activateLightOnSubMeshes_1(mesh, light);
  97461. });
  97462. }
  97463. };
  97464. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  97465. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  97466. }
  97467. });
  97468. }
  97469. }
  97470. webVrController_1.attachToPoseControlledCamera(_this);
  97471. // since this is async - sanity check. Is the controller already stored?
  97472. if (_this.controllers.indexOf(webVrController_1) === -1) {
  97473. //add to the controllers array
  97474. _this.controllers.push(webVrController_1);
  97475. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  97476. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  97477. // So we're overriding setting left & right manually to be sure
  97478. var firstViveWandDetected = false;
  97479. for (var i = 0; i < _this.controllers.length; i++) {
  97480. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  97481. if (!firstViveWandDetected) {
  97482. firstViveWandDetected = true;
  97483. _this.controllers[i].hand = "left";
  97484. }
  97485. else {
  97486. _this.controllers[i].hand = "right";
  97487. }
  97488. }
  97489. }
  97490. //did we find enough controllers? Great! let the developer know.
  97491. if (_this.controllers.length >= 2) {
  97492. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  97493. }
  97494. }
  97495. }
  97496. });
  97497. };
  97498. return WebVRFreeCamera;
  97499. }(BABYLON.FreeCamera));
  97500. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  97501. })(BABYLON || (BABYLON = {}));
  97502. //# sourceMappingURL=babylon.webVRCamera.js.map
  97503. var BABYLON;
  97504. (function (BABYLON) {
  97505. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  97506. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  97507. });
  97508. // We're mainly based on the logic defined into the FreeCamera code
  97509. /**
  97510. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  97511. * being tilted forward or back and left or right.
  97512. */
  97513. var DeviceOrientationCamera = /** @class */ (function (_super) {
  97514. __extends(DeviceOrientationCamera, _super);
  97515. /**
  97516. * Creates a new device orientation camera
  97517. * @param name The name of the camera
  97518. * @param position The start position camera
  97519. * @param scene The scene the camera belongs to
  97520. */
  97521. function DeviceOrientationCamera(name, position, scene) {
  97522. var _this = _super.call(this, name, position, scene) || this;
  97523. _this._quaternionCache = new BABYLON.Quaternion();
  97524. _this.inputs.addDeviceOrientation();
  97525. return _this;
  97526. }
  97527. /**
  97528. * Gets the current instance class name ("DeviceOrientationCamera").
  97529. * This helps avoiding instanceof at run time.
  97530. * @returns the class name
  97531. */
  97532. DeviceOrientationCamera.prototype.getClassName = function () {
  97533. return "DeviceOrientationCamera";
  97534. };
  97535. /**
  97536. * @hidden
  97537. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  97538. */
  97539. DeviceOrientationCamera.prototype._checkInputs = function () {
  97540. _super.prototype._checkInputs.call(this);
  97541. this._quaternionCache.copyFrom(this.rotationQuaternion);
  97542. if (this._initialQuaternion) {
  97543. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97544. }
  97545. };
  97546. /**
  97547. * Reset the camera to its default orientation on the specified axis only.
  97548. * @param axis The axis to reset
  97549. */
  97550. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  97551. var _this = this;
  97552. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  97553. //can only work if this camera has a rotation quaternion already.
  97554. if (!this.rotationQuaternion)
  97555. return;
  97556. if (!this._initialQuaternion) {
  97557. this._initialQuaternion = new BABYLON.Quaternion();
  97558. }
  97559. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  97560. ['x', 'y', 'z'].forEach(function (axisName) {
  97561. if (!axis[axisName]) {
  97562. _this._initialQuaternion[axisName] = 0;
  97563. }
  97564. else {
  97565. _this._initialQuaternion[axisName] *= -1;
  97566. }
  97567. });
  97568. this._initialQuaternion.normalize();
  97569. //force rotation update
  97570. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97571. };
  97572. return DeviceOrientationCamera;
  97573. }(BABYLON.FreeCamera));
  97574. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  97575. })(BABYLON || (BABYLON = {}));
  97576. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  97577. var BABYLON;
  97578. (function (BABYLON) {
  97579. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97580. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97581. });
  97582. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  97583. __extends(VRDeviceOrientationFreeCamera, _super);
  97584. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97585. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97586. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97587. var _this = _super.call(this, name, position, scene) || this;
  97588. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97589. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97590. return _this;
  97591. }
  97592. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  97593. return "VRDeviceOrientationFreeCamera";
  97594. };
  97595. return VRDeviceOrientationFreeCamera;
  97596. }(BABYLON.DeviceOrientationCamera));
  97597. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  97598. })(BABYLON || (BABYLON = {}));
  97599. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  97600. var BABYLON;
  97601. (function (BABYLON) {
  97602. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97603. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  97604. });
  97605. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  97606. __extends(VRDeviceOrientationArcRotateCamera, _super);
  97607. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  97608. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97609. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97610. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97611. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97612. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97613. _this.inputs.addVRDeviceOrientation();
  97614. return _this;
  97615. }
  97616. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  97617. return "VRDeviceOrientationArcRotateCamera";
  97618. };
  97619. return VRDeviceOrientationArcRotateCamera;
  97620. }(BABYLON.ArcRotateCamera));
  97621. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  97622. })(BABYLON || (BABYLON = {}));
  97623. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  97624. var BABYLON;
  97625. (function (BABYLON) {
  97626. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  97627. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  97628. });
  97629. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  97630. __extends(VRDeviceOrientationGamepadCamera, _super);
  97631. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97632. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97633. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97634. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  97635. _this.inputs.addGamepad();
  97636. return _this;
  97637. }
  97638. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  97639. return "VRDeviceOrientationGamepadCamera";
  97640. };
  97641. return VRDeviceOrientationGamepadCamera;
  97642. }(BABYLON.VRDeviceOrientationFreeCamera));
  97643. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  97644. })(BABYLON || (BABYLON = {}));
  97645. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  97646. var BABYLON;
  97647. (function (BABYLON) {
  97648. var VRExperienceHelperGazer = /** @class */ (function () {
  97649. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  97650. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  97651. this.scene = scene;
  97652. /** @hidden */
  97653. this._pointerDownOnMeshAsked = false;
  97654. /** @hidden */
  97655. this._isActionableMesh = false;
  97656. /** @hidden */
  97657. this._teleportationRequestInitiated = false;
  97658. /** @hidden */
  97659. this._teleportationBackRequestInitiated = false;
  97660. /** @hidden */
  97661. this._rotationRightAsked = false;
  97662. /** @hidden */
  97663. this._rotationLeftAsked = false;
  97664. /** @hidden */
  97665. this._dpadPressed = true;
  97666. /** @hidden */
  97667. this._activePointer = false;
  97668. this._id = VRExperienceHelperGazer._idCounter++;
  97669. // Gaze tracker
  97670. if (!gazeTrackerToClone) {
  97671. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  97672. this._gazeTracker.bakeCurrentTransformIntoVertices();
  97673. this._gazeTracker.isPickable = false;
  97674. this._gazeTracker.isVisible = false;
  97675. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  97676. targetMat.specularColor = BABYLON.Color3.Black();
  97677. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97678. targetMat.backFaceCulling = false;
  97679. this._gazeTracker.material = targetMat;
  97680. }
  97681. else {
  97682. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  97683. }
  97684. }
  97685. /** @hidden */
  97686. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  97687. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  97688. };
  97689. /** @hidden */
  97690. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  97691. this._pointerDownOnMeshAsked = true;
  97692. if (this._currentHit) {
  97693. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  97694. }
  97695. };
  97696. /** @hidden */
  97697. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  97698. if (this._currentHit) {
  97699. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  97700. }
  97701. this._pointerDownOnMeshAsked = false;
  97702. };
  97703. /** @hidden */
  97704. VRExperienceHelperGazer.prototype._activatePointer = function () {
  97705. this._activePointer = true;
  97706. };
  97707. /** @hidden */
  97708. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  97709. this._activePointer = false;
  97710. };
  97711. /** @hidden */
  97712. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  97713. if (distance === void 0) { distance = 100; }
  97714. };
  97715. VRExperienceHelperGazer.prototype.dispose = function () {
  97716. this._interactionsEnabled = false;
  97717. this._teleportationEnabled = false;
  97718. if (this._gazeTracker) {
  97719. this._gazeTracker.dispose();
  97720. }
  97721. };
  97722. VRExperienceHelperGazer._idCounter = 0;
  97723. return VRExperienceHelperGazer;
  97724. }());
  97725. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  97726. __extends(VRExperienceHelperControllerGazer, _super);
  97727. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  97728. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  97729. _this.webVRController = webVRController;
  97730. // Laser pointer
  97731. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  97732. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  97733. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97734. laserPointerMaterial.alpha = 0.6;
  97735. _this._laserPointer.material = laserPointerMaterial;
  97736. _this._laserPointer.rotation.x = Math.PI / 2;
  97737. _this._laserPointer.position.z = -0.5;
  97738. _this._laserPointer.isVisible = false;
  97739. _this._laserPointer.isPickable = false;
  97740. if (!webVRController.mesh) {
  97741. // Create an empty mesh that is used prior to loading the high quality model
  97742. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  97743. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  97744. preloadPointerPose.rotation.x = -0.7;
  97745. preloadMesh.addChild(preloadPointerPose);
  97746. webVRController.attachToMesh(preloadMesh);
  97747. }
  97748. _this._setLaserPointerParent(webVRController.mesh);
  97749. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  97750. _this._setLaserPointerParent(mesh);
  97751. });
  97752. return _this;
  97753. }
  97754. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  97755. return this.webVRController.getForwardRay(length);
  97756. };
  97757. /** @hidden */
  97758. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  97759. _super.prototype._activatePointer.call(this);
  97760. this._laserPointer.isVisible = true;
  97761. };
  97762. /** @hidden */
  97763. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  97764. _super.prototype._deactivatePointer.call(this);
  97765. this._laserPointer.isVisible = false;
  97766. };
  97767. /** @hidden */
  97768. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  97769. this._laserPointer.material.emissiveColor = color;
  97770. };
  97771. /** @hidden */
  97772. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  97773. var makeNotPick = function (root) {
  97774. root.isPickable = false;
  97775. root.getChildMeshes().forEach(function (c) {
  97776. makeNotPick(c);
  97777. });
  97778. };
  97779. makeNotPick(mesh);
  97780. var childMeshes = mesh.getChildMeshes();
  97781. this.webVRController._pointingPoseNode = null;
  97782. for (var i = 0; i < childMeshes.length; i++) {
  97783. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  97784. mesh = childMeshes[i];
  97785. this.webVRController._pointingPoseNode = mesh;
  97786. break;
  97787. }
  97788. }
  97789. this._laserPointer.parent = mesh;
  97790. };
  97791. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  97792. if (distance === void 0) { distance = 100; }
  97793. this._laserPointer.scaling.y = distance;
  97794. this._laserPointer.position.z = -distance / 2;
  97795. };
  97796. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  97797. _super.prototype.dispose.call(this);
  97798. this._laserPointer.dispose();
  97799. if (this._meshAttachedObserver) {
  97800. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  97801. }
  97802. };
  97803. return VRExperienceHelperControllerGazer;
  97804. }(VRExperienceHelperGazer));
  97805. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  97806. __extends(VRExperienceHelperCameraGazer, _super);
  97807. function VRExperienceHelperCameraGazer(getCamera, scene) {
  97808. var _this = _super.call(this, scene) || this;
  97809. _this.getCamera = getCamera;
  97810. return _this;
  97811. }
  97812. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  97813. var camera = this.getCamera();
  97814. if (camera) {
  97815. return camera.getForwardRay(length);
  97816. }
  97817. else {
  97818. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  97819. }
  97820. };
  97821. return VRExperienceHelperCameraGazer;
  97822. }(VRExperienceHelperGazer));
  97823. /**
  97824. * Helps to quickly add VR support to an existing scene.
  97825. * See http://doc.babylonjs.com/how_to/webvr_helper
  97826. */
  97827. var VRExperienceHelper = /** @class */ (function () {
  97828. /**
  97829. * Instantiates a VRExperienceHelper.
  97830. * Helps to quickly add VR support to an existing scene.
  97831. * @param scene The scene the VRExperienceHelper belongs to.
  97832. * @param webVROptions Options to modify the vr experience helper's behavior.
  97833. */
  97834. function VRExperienceHelper(scene,
  97835. /** Options to modify the vr experience helper's behavior. */
  97836. webVROptions) {
  97837. if (webVROptions === void 0) { webVROptions = {}; }
  97838. var _this = this;
  97839. this.webVROptions = webVROptions;
  97840. // Can the system support WebVR, even if a headset isn't plugged in?
  97841. this._webVRsupported = false;
  97842. // If WebVR is supported, is a headset plugged in and are we ready to present?
  97843. this._webVRready = false;
  97844. // Are we waiting for the requestPresent callback to complete?
  97845. this._webVRrequesting = false;
  97846. // Are we presenting to the headset right now? (this is the vrDevice state)
  97847. this._webVRpresenting = false;
  97848. // Are we presenting in the fullscreen fallback?
  97849. this._fullscreenVRpresenting = false;
  97850. /**
  97851. * Observable raised when entering VR.
  97852. */
  97853. this.onEnteringVRObservable = new BABYLON.Observable();
  97854. /**
  97855. * Observable raised when exiting VR.
  97856. */
  97857. this.onExitingVRObservable = new BABYLON.Observable();
  97858. /**
  97859. * Observable raised when controller mesh is loaded.
  97860. */
  97861. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  97862. this._useCustomVRButton = false;
  97863. this._teleportationRequested = false;
  97864. this._teleportActive = false;
  97865. this._floorMeshesCollection = [];
  97866. this._rotationAllowed = true;
  97867. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  97868. this._isDefaultTeleportationTarget = true;
  97869. this._teleportationFillColor = "#444444";
  97870. this._teleportationBorderColor = "#FFFFFF";
  97871. this._rotationAngle = 0;
  97872. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  97873. this._padSensibilityUp = 0.65;
  97874. this._padSensibilityDown = 0.35;
  97875. this._leftController = null;
  97876. this._rightController = null;
  97877. /**
  97878. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  97879. */
  97880. this.onNewMeshSelected = new BABYLON.Observable();
  97881. /**
  97882. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  97883. */
  97884. this.onNewMeshPicked = new BABYLON.Observable();
  97885. /**
  97886. * Observable raised before camera teleportation
  97887. */
  97888. this.onBeforeCameraTeleport = new BABYLON.Observable();
  97889. /**
  97890. * Observable raised after camera teleportation
  97891. */
  97892. this.onAfterCameraTeleport = new BABYLON.Observable();
  97893. /**
  97894. * Observable raised when current selected mesh gets unselected
  97895. */
  97896. this.onSelectedMeshUnselected = new BABYLON.Observable();
  97897. /**
  97898. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  97899. */
  97900. this.teleportationEnabled = true;
  97901. this._teleportationInitialized = false;
  97902. this._interactionsEnabled = false;
  97903. this._interactionsRequested = false;
  97904. this._displayGaze = true;
  97905. this._displayLaserPointer = true;
  97906. /**
  97907. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  97908. */
  97909. this.updateGazeTrackerScale = true;
  97910. this._onResize = function () {
  97911. _this.moveButtonToBottomRight();
  97912. if (_this._fullscreenVRpresenting && _this._webVRready) {
  97913. _this.exitVR();
  97914. }
  97915. };
  97916. this._onFullscreenChange = function () {
  97917. if (document.fullscreen !== undefined) {
  97918. _this._fullscreenVRpresenting = document.fullscreen;
  97919. }
  97920. else if (document.mozFullScreen !== undefined) {
  97921. _this._fullscreenVRpresenting = document.mozFullScreen;
  97922. }
  97923. else if (document.webkitIsFullScreen !== undefined) {
  97924. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  97925. }
  97926. else if (document.msIsFullScreen !== undefined) {
  97927. _this._fullscreenVRpresenting = document.msIsFullScreen;
  97928. }
  97929. else if (document.msFullscreenElement !== undefined) {
  97930. _this._fullscreenVRpresenting = document.msFullscreenElement;
  97931. }
  97932. if (!_this._fullscreenVRpresenting && _this._canvas) {
  97933. _this.exitVR();
  97934. if (!_this._useCustomVRButton) {
  97935. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  97936. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  97937. }
  97938. }
  97939. };
  97940. this.beforeRender = function () {
  97941. if (_this._leftController && _this._leftController._activePointer) {
  97942. _this._castRayAndSelectObject(_this._leftController);
  97943. }
  97944. if (_this._rightController && _this._rightController._activePointer) {
  97945. _this._castRayAndSelectObject(_this._rightController);
  97946. }
  97947. if (_this._noControllerIsActive) {
  97948. _this._castRayAndSelectObject(_this._cameraGazer);
  97949. }
  97950. else {
  97951. _this._cameraGazer._gazeTracker.isVisible = false;
  97952. }
  97953. };
  97954. this._onNewGamepadConnected = function (gamepad) {
  97955. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  97956. if (gamepad.leftStick) {
  97957. gamepad.onleftstickchanged(function (stickValues) {
  97958. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  97959. // Listening to classic/xbox gamepad only if no VR controller is active
  97960. if ((!_this._leftController && !_this._rightController) ||
  97961. ((_this._leftController && !_this._leftController._activePointer) &&
  97962. (_this._rightController && !_this._rightController._activePointer))) {
  97963. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  97964. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  97965. }
  97966. }
  97967. });
  97968. }
  97969. if (gamepad.rightStick) {
  97970. gamepad.onrightstickchanged(function (stickValues) {
  97971. if (_this._teleportationInitialized) {
  97972. _this._checkRotate(stickValues, _this._cameraGazer);
  97973. }
  97974. });
  97975. }
  97976. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  97977. gamepad.onbuttondown(function (buttonPressed) {
  97978. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97979. _this._cameraGazer._selectionPointerDown();
  97980. }
  97981. });
  97982. gamepad.onbuttonup(function (buttonPressed) {
  97983. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97984. _this._cameraGazer._selectionPointerUp();
  97985. }
  97986. });
  97987. }
  97988. }
  97989. else {
  97990. var webVRController = gamepad;
  97991. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  97992. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  97993. _this._rightController = controller;
  97994. }
  97995. else {
  97996. _this._leftController = controller;
  97997. }
  97998. _this._tryEnableInteractionOnController(controller);
  97999. }
  98000. };
  98001. // 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
  98002. this._tryEnableInteractionOnController = function (controller) {
  98003. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  98004. _this._enableInteractionOnController(controller);
  98005. }
  98006. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  98007. _this._enableTeleportationOnController(controller);
  98008. }
  98009. };
  98010. this._onNewGamepadDisconnected = function (gamepad) {
  98011. if (gamepad instanceof BABYLON.WebVRController) {
  98012. if (gamepad.hand === "left" && _this._leftController != null) {
  98013. _this._leftController.dispose();
  98014. _this._leftController = null;
  98015. }
  98016. if (gamepad.hand === "right" && _this._rightController != null) {
  98017. _this._rightController.dispose();
  98018. _this._rightController = null;
  98019. }
  98020. }
  98021. };
  98022. this._workingVector = BABYLON.Vector3.Zero();
  98023. this._workingQuaternion = BABYLON.Quaternion.Identity();
  98024. this._workingMatrix = BABYLON.Matrix.Identity();
  98025. this._scene = scene;
  98026. this._canvas = scene.getEngine().getRenderingCanvas();
  98027. // Parse options
  98028. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  98029. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  98030. }
  98031. if (webVROptions.createDeviceOrientationCamera === undefined) {
  98032. webVROptions.createDeviceOrientationCamera = true;
  98033. }
  98034. if (webVROptions.laserToggle === undefined) {
  98035. webVROptions.laserToggle = true;
  98036. }
  98037. if (webVROptions.defaultHeight === undefined) {
  98038. webVROptions.defaultHeight = 1.7;
  98039. }
  98040. if (webVROptions.useCustomVRButton) {
  98041. this._useCustomVRButton = true;
  98042. if (webVROptions.customVRButton) {
  98043. this._btnVR = webVROptions.customVRButton;
  98044. }
  98045. }
  98046. if (webVROptions.rayLength) {
  98047. this._rayLength = webVROptions.rayLength;
  98048. }
  98049. this._defaultHeight = webVROptions.defaultHeight;
  98050. if (webVROptions.positionScale) {
  98051. this._rayLength *= webVROptions.positionScale;
  98052. this._defaultHeight *= webVROptions.positionScale;
  98053. }
  98054. this._hasEnteredVR = false;
  98055. // Set position
  98056. if (this._scene.activeCamera) {
  98057. this._position = this._scene.activeCamera.position.clone();
  98058. }
  98059. else {
  98060. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  98061. }
  98062. // Set non-vr camera
  98063. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  98064. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  98065. // Copy data from existing camera
  98066. if (this._scene.activeCamera) {
  98067. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98068. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  98069. // Set rotation from previous camera
  98070. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  98071. var targetCamera = this._scene.activeCamera;
  98072. if (targetCamera.rotationQuaternion) {
  98073. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  98074. }
  98075. else {
  98076. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  98077. }
  98078. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  98079. }
  98080. }
  98081. this._scene.activeCamera = this._deviceOrientationCamera;
  98082. if (this._canvas) {
  98083. this._scene.activeCamera.attachControl(this._canvas);
  98084. }
  98085. }
  98086. else {
  98087. this._existingCamera = this._scene.activeCamera;
  98088. }
  98089. // Create VR cameras
  98090. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  98091. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  98092. }
  98093. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  98094. this._webVRCamera.useStandingMatrix();
  98095. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  98096. // Create default button
  98097. if (!this._useCustomVRButton) {
  98098. this._btnVR = document.createElement("BUTTON");
  98099. this._btnVR.className = "babylonVRicon";
  98100. this._btnVR.id = "babylonVRiconbtn";
  98101. this._btnVR.title = "Click to switch to VR";
  98102. 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) }";
  98103. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  98104. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  98105. // css += ".babylonVRicon.vrdisplaysupported { }";
  98106. // css += ".babylonVRicon.vrdisplayready { }";
  98107. // css += ".babylonVRicon.vrdisplayrequesting { }";
  98108. var style = document.createElement('style');
  98109. style.appendChild(document.createTextNode(css));
  98110. document.getElementsByTagName('head')[0].appendChild(style);
  98111. this.moveButtonToBottomRight();
  98112. }
  98113. // VR button click event
  98114. if (this._btnVR) {
  98115. this._btnVR.addEventListener("click", function () {
  98116. if (!_this.isInVRMode) {
  98117. _this.enterVR();
  98118. }
  98119. else {
  98120. _this.exitVR();
  98121. }
  98122. });
  98123. }
  98124. // Window events
  98125. window.addEventListener("resize", this._onResize);
  98126. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  98127. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  98128. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  98129. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  98130. document.onmsfullscreenchange = this._onFullscreenChange;
  98131. // Display vr button when headset is connected
  98132. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  98133. this.displayVRButton();
  98134. }
  98135. else {
  98136. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  98137. if (e.vrDisplay) {
  98138. _this.displayVRButton();
  98139. }
  98140. });
  98141. }
  98142. // Exiting VR mode using 'ESC' key on desktop
  98143. this._onKeyDown = function (event) {
  98144. if (event.keyCode === 27 && _this.isInVRMode) {
  98145. _this.exitVR();
  98146. }
  98147. };
  98148. document.addEventListener("keydown", this._onKeyDown);
  98149. // Exiting VR mode double tapping the touch screen
  98150. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  98151. if (_this.isInVRMode) {
  98152. _this.exitVR();
  98153. if (_this._fullscreenVRpresenting) {
  98154. _this._scene.getEngine().switchFullscreen(true);
  98155. }
  98156. }
  98157. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  98158. // Listen for WebVR display changes
  98159. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  98160. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  98161. this._onVRRequestPresentStart = function () {
  98162. _this._webVRrequesting = true;
  98163. _this.updateButtonVisibility();
  98164. };
  98165. this._onVRRequestPresentComplete = function (success) {
  98166. _this._webVRrequesting = false;
  98167. _this.updateButtonVisibility();
  98168. };
  98169. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  98170. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  98171. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  98172. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98173. scene.onDisposeObservable.add(function () {
  98174. _this.dispose();
  98175. });
  98176. // Gamepad connection events
  98177. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  98178. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  98179. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  98180. this.updateButtonVisibility();
  98181. //create easing functions
  98182. this._circleEase = new BABYLON.CircleEase();
  98183. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98184. if (this.webVROptions.floorMeshes) {
  98185. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  98186. }
  98187. }
  98188. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  98189. /** Return this.onEnteringVRObservable
  98190. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  98191. */
  98192. get: function () {
  98193. return this.onEnteringVRObservable;
  98194. },
  98195. enumerable: true,
  98196. configurable: true
  98197. });
  98198. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  98199. /** Return this.onExitingVRObservable
  98200. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  98201. */
  98202. get: function () {
  98203. return this.onExitingVRObservable;
  98204. },
  98205. enumerable: true,
  98206. configurable: true
  98207. });
  98208. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  98209. /** Return this.onControllerMeshLoadedObservable
  98210. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  98211. */
  98212. get: function () {
  98213. return this.onControllerMeshLoadedObservable;
  98214. },
  98215. enumerable: true,
  98216. configurable: true
  98217. });
  98218. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  98219. /**
  98220. * The mesh used to display where the user is going to teleport.
  98221. */
  98222. get: function () {
  98223. return this._teleportationTarget;
  98224. },
  98225. /**
  98226. * Sets the mesh to be used to display where the user is going to teleport.
  98227. */
  98228. set: function (value) {
  98229. if (value) {
  98230. value.name = "teleportationTarget";
  98231. this._isDefaultTeleportationTarget = false;
  98232. this._teleportationTarget = value;
  98233. }
  98234. },
  98235. enumerable: true,
  98236. configurable: true
  98237. });
  98238. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  98239. /**
  98240. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  98241. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  98242. * See http://doc.babylonjs.com/resources/baking_transformations
  98243. */
  98244. get: function () {
  98245. return this._cameraGazer._gazeTracker;
  98246. },
  98247. set: function (value) {
  98248. if (value) {
  98249. // Dispose of existing meshes
  98250. if (this._cameraGazer._gazeTracker) {
  98251. this._cameraGazer._gazeTracker.dispose();
  98252. }
  98253. if (this._leftController && this._leftController._gazeTracker) {
  98254. this._leftController._gazeTracker.dispose();
  98255. }
  98256. if (this._rightController && this._rightController._gazeTracker) {
  98257. this._rightController._gazeTracker.dispose();
  98258. }
  98259. // Set and create gaze trackers on head and controllers
  98260. this._cameraGazer._gazeTracker = value;
  98261. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  98262. this._cameraGazer._gazeTracker.isPickable = false;
  98263. this._cameraGazer._gazeTracker.isVisible = false;
  98264. this._cameraGazer._gazeTracker.name = "gazeTracker";
  98265. if (this._leftController) {
  98266. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  98267. }
  98268. if (this._rightController) {
  98269. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  98270. }
  98271. }
  98272. },
  98273. enumerable: true,
  98274. configurable: true
  98275. });
  98276. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  98277. /**
  98278. * The gaze tracking mesh corresponding to the left controller
  98279. */
  98280. get: function () {
  98281. if (this._leftController) {
  98282. return this._leftController._gazeTracker;
  98283. }
  98284. return null;
  98285. },
  98286. enumerable: true,
  98287. configurable: true
  98288. });
  98289. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  98290. /**
  98291. * The gaze tracking mesh corresponding to the right controller
  98292. */
  98293. get: function () {
  98294. if (this._rightController) {
  98295. return this._rightController._gazeTracker;
  98296. }
  98297. return null;
  98298. },
  98299. enumerable: true,
  98300. configurable: true
  98301. });
  98302. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  98303. /**
  98304. * If the ray of the gaze should be displayed.
  98305. */
  98306. get: function () {
  98307. return this._displayGaze;
  98308. },
  98309. /**
  98310. * Sets if the ray of the gaze should be displayed.
  98311. */
  98312. set: function (value) {
  98313. this._displayGaze = value;
  98314. if (!value) {
  98315. this._cameraGazer._gazeTracker.isVisible = false;
  98316. if (this._leftController) {
  98317. this._leftController._gazeTracker.isVisible = false;
  98318. }
  98319. if (this._rightController) {
  98320. this._rightController._gazeTracker.isVisible = false;
  98321. }
  98322. }
  98323. },
  98324. enumerable: true,
  98325. configurable: true
  98326. });
  98327. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  98328. /**
  98329. * If the ray of the LaserPointer should be displayed.
  98330. */
  98331. get: function () {
  98332. return this._displayLaserPointer;
  98333. },
  98334. /**
  98335. * Sets if the ray of the LaserPointer should be displayed.
  98336. */
  98337. set: function (value) {
  98338. this._displayLaserPointer = value;
  98339. if (!value) {
  98340. if (this._rightController) {
  98341. this._rightController._deactivatePointer();
  98342. this._rightController._gazeTracker.isVisible = false;
  98343. }
  98344. if (this._leftController) {
  98345. this._leftController._deactivatePointer();
  98346. this._leftController._gazeTracker.isVisible = false;
  98347. }
  98348. }
  98349. else {
  98350. if (this._rightController) {
  98351. this._rightController._activatePointer();
  98352. }
  98353. if (this._leftController) {
  98354. this._leftController._activatePointer();
  98355. }
  98356. }
  98357. },
  98358. enumerable: true,
  98359. configurable: true
  98360. });
  98361. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  98362. /**
  98363. * The deviceOrientationCamera used as the camera when not in VR.
  98364. */
  98365. get: function () {
  98366. return this._deviceOrientationCamera;
  98367. },
  98368. enumerable: true,
  98369. configurable: true
  98370. });
  98371. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  98372. /**
  98373. * Based on the current WebVR support, returns the current VR camera used.
  98374. */
  98375. get: function () {
  98376. if (this._webVRready) {
  98377. return this._webVRCamera;
  98378. }
  98379. else {
  98380. return this._scene.activeCamera;
  98381. }
  98382. },
  98383. enumerable: true,
  98384. configurable: true
  98385. });
  98386. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  98387. /**
  98388. * The webVRCamera which is used when in VR.
  98389. */
  98390. get: function () {
  98391. return this._webVRCamera;
  98392. },
  98393. enumerable: true,
  98394. configurable: true
  98395. });
  98396. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  98397. /**
  98398. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  98399. */
  98400. get: function () {
  98401. return this._vrDeviceOrientationCamera;
  98402. },
  98403. enumerable: true,
  98404. configurable: true
  98405. });
  98406. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  98407. get: function () {
  98408. var result = this._cameraGazer._teleportationRequestInitiated
  98409. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  98410. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  98411. return result;
  98412. },
  98413. enumerable: true,
  98414. configurable: true
  98415. });
  98416. // Raised when one of the controller has loaded successfully its associated default mesh
  98417. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  98418. if (this._leftController && this._leftController.webVRController == webVRController) {
  98419. if (webVRController.mesh) {
  98420. this._leftController._setLaserPointerParent(webVRController.mesh);
  98421. }
  98422. }
  98423. if (this._rightController && this._rightController.webVRController == webVRController) {
  98424. if (webVRController.mesh) {
  98425. this._rightController._setLaserPointerParent(webVRController.mesh);
  98426. }
  98427. }
  98428. try {
  98429. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  98430. }
  98431. catch (err) {
  98432. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  98433. }
  98434. };
  98435. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  98436. /**
  98437. * Gets a value indicating if we are currently in VR mode.
  98438. */
  98439. get: function () {
  98440. return this._webVRpresenting || this._fullscreenVRpresenting;
  98441. },
  98442. enumerable: true,
  98443. configurable: true
  98444. });
  98445. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  98446. var vrDisplay = this._scene.getEngine().getVRDevice();
  98447. if (vrDisplay) {
  98448. var wasPresenting = this._webVRpresenting;
  98449. this._webVRpresenting = vrDisplay.isPresenting;
  98450. if (wasPresenting && !this._webVRpresenting)
  98451. this.exitVR();
  98452. }
  98453. else {
  98454. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  98455. }
  98456. this.updateButtonVisibility();
  98457. };
  98458. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  98459. this._webVRsupported = eventArgs.vrSupported;
  98460. this._webVRready = !!eventArgs.vrDisplay;
  98461. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  98462. this.updateButtonVisibility();
  98463. };
  98464. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  98465. if (this._canvas && !this._useCustomVRButton) {
  98466. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  98467. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  98468. }
  98469. };
  98470. VRExperienceHelper.prototype.displayVRButton = function () {
  98471. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  98472. document.body.appendChild(this._btnVR);
  98473. this._btnVRDisplayed = true;
  98474. }
  98475. };
  98476. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  98477. if (!this._btnVR || this._useCustomVRButton) {
  98478. return;
  98479. }
  98480. this._btnVR.className = "babylonVRicon";
  98481. if (this.isInVRMode) {
  98482. this._btnVR.className += " vrdisplaypresenting";
  98483. }
  98484. else {
  98485. if (this._webVRready)
  98486. this._btnVR.className += " vrdisplayready";
  98487. if (this._webVRsupported)
  98488. this._btnVR.className += " vrdisplaysupported";
  98489. if (this._webVRrequesting)
  98490. this._btnVR.className += " vrdisplayrequesting";
  98491. }
  98492. };
  98493. /**
  98494. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  98495. * Otherwise, will use the fullscreen API.
  98496. */
  98497. VRExperienceHelper.prototype.enterVR = function () {
  98498. if (this.onEnteringVRObservable) {
  98499. try {
  98500. this.onEnteringVRObservable.notifyObservers(this);
  98501. }
  98502. catch (err) {
  98503. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  98504. }
  98505. }
  98506. if (this._scene.activeCamera) {
  98507. this._position = this._scene.activeCamera.position.clone();
  98508. // make sure that we return to the last active camera
  98509. this._existingCamera = this._scene.activeCamera;
  98510. }
  98511. if (this._webVRrequesting)
  98512. return;
  98513. // If WebVR is supported and a headset is connected
  98514. if (this._webVRready) {
  98515. if (!this._webVRpresenting) {
  98516. this._webVRCamera.position = this._position;
  98517. this._scene.activeCamera = this._webVRCamera;
  98518. }
  98519. }
  98520. else if (this._vrDeviceOrientationCamera) {
  98521. this._vrDeviceOrientationCamera.position = this._position;
  98522. if (this._scene.activeCamera) {
  98523. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98524. }
  98525. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  98526. this._scene.getEngine().switchFullscreen(true);
  98527. this.updateButtonVisibility();
  98528. }
  98529. if (this._scene.activeCamera && this._canvas) {
  98530. this._scene.activeCamera.attachControl(this._canvas);
  98531. }
  98532. if (this._interactionsEnabled) {
  98533. this._scene.registerBeforeRender(this.beforeRender);
  98534. }
  98535. this._hasEnteredVR = true;
  98536. };
  98537. /**
  98538. * Attempt to exit VR, or fullscreen.
  98539. */
  98540. VRExperienceHelper.prototype.exitVR = function () {
  98541. if (this._hasEnteredVR) {
  98542. if (this.onExitingVRObservable) {
  98543. try {
  98544. this.onExitingVRObservable.notifyObservers(this);
  98545. }
  98546. catch (err) {
  98547. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  98548. }
  98549. }
  98550. if (this._webVRpresenting) {
  98551. this._scene.getEngine().disableVR();
  98552. }
  98553. if (this._scene.activeCamera) {
  98554. this._position = this._scene.activeCamera.position.clone();
  98555. }
  98556. if (this._deviceOrientationCamera) {
  98557. this._deviceOrientationCamera.position = this._position;
  98558. this._scene.activeCamera = this._deviceOrientationCamera;
  98559. if (this._canvas) {
  98560. this._scene.activeCamera.attachControl(this._canvas);
  98561. }
  98562. }
  98563. else if (this._existingCamera) {
  98564. this._existingCamera.position = this._position;
  98565. this._scene.activeCamera = this._existingCamera;
  98566. }
  98567. this.updateButtonVisibility();
  98568. if (this._interactionsEnabled) {
  98569. this._scene.unregisterBeforeRender(this.beforeRender);
  98570. this._cameraGazer._gazeTracker.isVisible = false;
  98571. if (this._leftController) {
  98572. this._leftController._gazeTracker.isVisible = false;
  98573. }
  98574. if (this._rightController) {
  98575. this._rightController._gazeTracker.isVisible = false;
  98576. }
  98577. }
  98578. // resize to update width and height when exiting vr exits fullscreen
  98579. this._scene.getEngine().resize();
  98580. this._hasEnteredVR = false;
  98581. }
  98582. };
  98583. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  98584. /**
  98585. * The position of the vr experience helper.
  98586. */
  98587. get: function () {
  98588. return this._position;
  98589. },
  98590. /**
  98591. * Sets the position of the vr experience helper.
  98592. */
  98593. set: function (value) {
  98594. this._position = value;
  98595. if (this._scene.activeCamera) {
  98596. this._scene.activeCamera.position = value;
  98597. }
  98598. },
  98599. enumerable: true,
  98600. configurable: true
  98601. });
  98602. /**
  98603. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  98604. */
  98605. VRExperienceHelper.prototype.enableInteractions = function () {
  98606. var _this = this;
  98607. if (!this._interactionsEnabled) {
  98608. this._interactionsRequested = true;
  98609. if (this._leftController) {
  98610. this._enableInteractionOnController(this._leftController);
  98611. }
  98612. if (this._rightController) {
  98613. this._enableInteractionOnController(this._rightController);
  98614. }
  98615. this.raySelectionPredicate = function (mesh) {
  98616. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  98617. };
  98618. this.meshSelectionPredicate = function (mesh) {
  98619. return true;
  98620. };
  98621. this._raySelectionPredicate = function (mesh) {
  98622. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  98623. && mesh.name.indexOf("teleportationTarget") === -1
  98624. && mesh.name.indexOf("torusTeleportation") === -1)) {
  98625. return _this.raySelectionPredicate(mesh);
  98626. }
  98627. return false;
  98628. };
  98629. this._interactionsEnabled = true;
  98630. }
  98631. };
  98632. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  98633. get: function () {
  98634. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  98635. },
  98636. enumerable: true,
  98637. configurable: true
  98638. });
  98639. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  98640. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  98641. if (this._floorMeshesCollection[i].id === mesh.id) {
  98642. return true;
  98643. }
  98644. }
  98645. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  98646. return true;
  98647. }
  98648. return false;
  98649. };
  98650. /**
  98651. * Adds a floor mesh to be used for teleportation.
  98652. * @param floorMesh the mesh to be used for teleportation.
  98653. */
  98654. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  98655. if (!this._floorMeshesCollection) {
  98656. return;
  98657. }
  98658. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  98659. return;
  98660. }
  98661. this._floorMeshesCollection.push(floorMesh);
  98662. };
  98663. /**
  98664. * Removes a floor mesh from being used for teleportation.
  98665. * @param floorMesh the mesh to be removed.
  98666. */
  98667. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  98668. if (!this._floorMeshesCollection) {
  98669. return;
  98670. }
  98671. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  98672. if (meshIndex !== -1) {
  98673. this._floorMeshesCollection.splice(meshIndex, 1);
  98674. }
  98675. };
  98676. /**
  98677. * Enables interactions and teleportation using the VR controllers and gaze.
  98678. * @param vrTeleportationOptions options to modify teleportation behavior.
  98679. */
  98680. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  98681. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  98682. if (!this._teleportationInitialized) {
  98683. this._teleportationRequested = true;
  98684. this.enableInteractions();
  98685. if (vrTeleportationOptions.floorMeshName) {
  98686. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  98687. }
  98688. if (vrTeleportationOptions.floorMeshes) {
  98689. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  98690. }
  98691. if (this._leftController != null) {
  98692. this._enableTeleportationOnController(this._leftController);
  98693. }
  98694. if (this._rightController != null) {
  98695. this._enableTeleportationOnController(this._rightController);
  98696. }
  98697. // Creates an image processing post process for the vignette not relying
  98698. // on the main scene configuration for image processing to reduce setup and spaces
  98699. // (gamma/linear) conflicts.
  98700. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  98701. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  98702. imageProcessingConfiguration.vignetteEnabled = true;
  98703. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  98704. this._webVRCamera.detachPostProcess(this._postProcessMove);
  98705. this._teleportationInitialized = true;
  98706. if (this._isDefaultTeleportationTarget) {
  98707. this._createTeleportationCircles();
  98708. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  98709. }
  98710. }
  98711. };
  98712. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  98713. var _this = this;
  98714. var controllerMesh = controller.webVRController.mesh;
  98715. if (controllerMesh) {
  98716. controller._interactionsEnabled = true;
  98717. controller._activatePointer();
  98718. if (this.webVROptions.laserToggle) {
  98719. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  98720. // Enabling / disabling laserPointer
  98721. if (_this._displayLaserPointer && stateObject.value === 1) {
  98722. if (controller._activePointer) {
  98723. controller._deactivatePointer();
  98724. }
  98725. else {
  98726. controller._activatePointer();
  98727. }
  98728. if (_this.displayGaze) {
  98729. controller._gazeTracker.isVisible = controller._activePointer;
  98730. }
  98731. }
  98732. });
  98733. }
  98734. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  98735. var gazer = controller;
  98736. if (_this._noControllerIsActive) {
  98737. gazer = _this._cameraGazer;
  98738. }
  98739. if (!gazer._pointerDownOnMeshAsked) {
  98740. if (stateObject.value > _this._padSensibilityUp) {
  98741. gazer._selectionPointerDown();
  98742. }
  98743. }
  98744. else if (stateObject.value < _this._padSensibilityDown) {
  98745. gazer._selectionPointerUp();
  98746. }
  98747. });
  98748. }
  98749. };
  98750. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  98751. // Dont teleport if another gaze already requested teleportation
  98752. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  98753. return;
  98754. }
  98755. if (!gazer._teleportationRequestInitiated) {
  98756. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  98757. gazer._activatePointer();
  98758. gazer._teleportationRequestInitiated = true;
  98759. }
  98760. }
  98761. else {
  98762. // Listening to the proper controller values changes to confirm teleportation
  98763. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  98764. if (this._teleportActive) {
  98765. this.teleportCamera(this._haloCenter);
  98766. }
  98767. gazer._teleportationRequestInitiated = false;
  98768. }
  98769. }
  98770. };
  98771. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  98772. // Only rotate when user is not currently selecting a teleportation location
  98773. if (gazer._teleportationRequestInitiated) {
  98774. return;
  98775. }
  98776. if (!gazer._rotationLeftAsked) {
  98777. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  98778. gazer._rotationLeftAsked = true;
  98779. if (this._rotationAllowed) {
  98780. this._rotateCamera(false);
  98781. }
  98782. }
  98783. }
  98784. else {
  98785. if (stateObject.x > -this._padSensibilityDown) {
  98786. gazer._rotationLeftAsked = false;
  98787. }
  98788. }
  98789. if (!gazer._rotationRightAsked) {
  98790. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  98791. gazer._rotationRightAsked = true;
  98792. if (this._rotationAllowed) {
  98793. this._rotateCamera(true);
  98794. }
  98795. }
  98796. }
  98797. else {
  98798. if (stateObject.x < this._padSensibilityDown) {
  98799. gazer._rotationRightAsked = false;
  98800. }
  98801. }
  98802. };
  98803. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  98804. // Only teleport backwards when user is not currently selecting a teleportation location
  98805. if (gazer._teleportationRequestInitiated) {
  98806. return;
  98807. }
  98808. // Teleport backwards
  98809. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  98810. if (!gazer._teleportationBackRequestInitiated) {
  98811. if (!this.currentVRCamera) {
  98812. return;
  98813. }
  98814. // Get rotation and position of the current camera
  98815. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  98816. var position = this.currentVRCamera.position;
  98817. // If the camera has device position, use that instead
  98818. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  98819. rotation = this.currentVRCamera.deviceRotationQuaternion;
  98820. position = this.currentVRCamera.devicePosition;
  98821. }
  98822. // Get matrix with only the y rotation of the device rotation
  98823. rotation.toEulerAnglesToRef(this._workingVector);
  98824. this._workingVector.z = 0;
  98825. this._workingVector.x = 0;
  98826. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  98827. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  98828. // Rotate backwards ray by device rotation to cast at the ground behind the user
  98829. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  98830. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  98831. var ray = new BABYLON.Ray(position, this._workingVector);
  98832. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98833. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  98834. this.teleportCamera(hit.pickedPoint);
  98835. }
  98836. gazer._teleportationBackRequestInitiated = true;
  98837. }
  98838. }
  98839. else {
  98840. gazer._teleportationBackRequestInitiated = false;
  98841. }
  98842. };
  98843. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  98844. var _this = this;
  98845. var controllerMesh = controller.webVRController.mesh;
  98846. if (controllerMesh) {
  98847. if (!controller._interactionsEnabled) {
  98848. this._enableInteractionOnController(controller);
  98849. }
  98850. controller._interactionsEnabled = true;
  98851. controller._teleportationEnabled = true;
  98852. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  98853. controller._dpadPressed = false;
  98854. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  98855. controller._dpadPressed = stateObject.pressed;
  98856. if (!controller._dpadPressed) {
  98857. controller._rotationLeftAsked = false;
  98858. controller._rotationRightAsked = false;
  98859. controller._teleportationBackRequestInitiated = false;
  98860. }
  98861. });
  98862. }
  98863. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  98864. if (_this.teleportationEnabled) {
  98865. _this._checkTeleportBackwards(stateObject, controller);
  98866. _this._checkTeleportWithRay(stateObject, controller);
  98867. }
  98868. _this._checkRotate(stateObject, controller);
  98869. });
  98870. }
  98871. };
  98872. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  98873. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  98874. this._teleportationTarget.isPickable = false;
  98875. var length = 512;
  98876. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  98877. dynamicTexture.hasAlpha = true;
  98878. var context = dynamicTexture.getContext();
  98879. var centerX = length / 2;
  98880. var centerY = length / 2;
  98881. var radius = 200;
  98882. context.beginPath();
  98883. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  98884. context.fillStyle = this._teleportationFillColor;
  98885. context.fill();
  98886. context.lineWidth = 10;
  98887. context.strokeStyle = this._teleportationBorderColor;
  98888. context.stroke();
  98889. context.closePath();
  98890. dynamicTexture.update();
  98891. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  98892. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  98893. this._teleportationTarget.material = teleportationCircleMaterial;
  98894. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  98895. torus.isPickable = false;
  98896. torus.parent = this._teleportationTarget;
  98897. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  98898. var keys = [];
  98899. keys.push({
  98900. frame: 0,
  98901. value: 0
  98902. });
  98903. keys.push({
  98904. frame: 30,
  98905. value: 0.4
  98906. });
  98907. keys.push({
  98908. frame: 60,
  98909. value: 0
  98910. });
  98911. animationInnerCircle.setKeys(keys);
  98912. var easingFunction = new BABYLON.SineEase();
  98913. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98914. animationInnerCircle.setEasingFunction(easingFunction);
  98915. torus.animations = [];
  98916. torus.animations.push(animationInnerCircle);
  98917. this._scene.beginAnimation(torus, 0, 60, true);
  98918. this._hideTeleportationTarget();
  98919. };
  98920. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  98921. this._teleportActive = true;
  98922. if (this._teleportationInitialized) {
  98923. this._teleportationTarget.isVisible = true;
  98924. if (this._isDefaultTeleportationTarget) {
  98925. this._teleportationTarget.getChildren()[0].isVisible = true;
  98926. }
  98927. }
  98928. };
  98929. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  98930. this._teleportActive = false;
  98931. if (this._teleportationInitialized) {
  98932. this._teleportationTarget.isVisible = false;
  98933. if (this._isDefaultTeleportationTarget) {
  98934. this._teleportationTarget.getChildren()[0].isVisible = false;
  98935. }
  98936. }
  98937. };
  98938. VRExperienceHelper.prototype._rotateCamera = function (right) {
  98939. var _this = this;
  98940. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98941. return;
  98942. }
  98943. if (right) {
  98944. this._rotationAngle++;
  98945. }
  98946. else {
  98947. this._rotationAngle--;
  98948. }
  98949. this.currentVRCamera.animations = [];
  98950. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  98951. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98952. var animationRotationKeys = [];
  98953. animationRotationKeys.push({
  98954. frame: 0,
  98955. value: this.currentVRCamera.rotationQuaternion
  98956. });
  98957. animationRotationKeys.push({
  98958. frame: 6,
  98959. value: target
  98960. });
  98961. animationRotation.setKeys(animationRotationKeys);
  98962. animationRotation.setEasingFunction(this._circleEase);
  98963. this.currentVRCamera.animations.push(animationRotation);
  98964. this._postProcessMove.animations = [];
  98965. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98966. var vignetteWeightKeys = [];
  98967. vignetteWeightKeys.push({
  98968. frame: 0,
  98969. value: 0
  98970. });
  98971. vignetteWeightKeys.push({
  98972. frame: 3,
  98973. value: 4
  98974. });
  98975. vignetteWeightKeys.push({
  98976. frame: 6,
  98977. value: 0
  98978. });
  98979. animationPP.setKeys(vignetteWeightKeys);
  98980. animationPP.setEasingFunction(this._circleEase);
  98981. this._postProcessMove.animations.push(animationPP);
  98982. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98983. var vignetteStretchKeys = [];
  98984. vignetteStretchKeys.push({
  98985. frame: 0,
  98986. value: 0
  98987. });
  98988. vignetteStretchKeys.push({
  98989. frame: 3,
  98990. value: 10
  98991. });
  98992. vignetteStretchKeys.push({
  98993. frame: 6,
  98994. value: 0
  98995. });
  98996. animationPP2.setKeys(vignetteStretchKeys);
  98997. animationPP2.setEasingFunction(this._circleEase);
  98998. this._postProcessMove.animations.push(animationPP2);
  98999. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  99000. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  99001. this._postProcessMove.samples = 4;
  99002. this._webVRCamera.attachPostProcess(this._postProcessMove);
  99003. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  99004. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  99005. });
  99006. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  99007. };
  99008. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  99009. if (hit.pickedPoint) {
  99010. if (gazer._teleportationRequestInitiated) {
  99011. this._displayTeleportationTarget();
  99012. this._haloCenter.copyFrom(hit.pickedPoint);
  99013. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  99014. }
  99015. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  99016. if (pickNormal) {
  99017. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  99018. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  99019. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  99020. }
  99021. this._teleportationTarget.position.y += 0.1;
  99022. }
  99023. };
  99024. /**
  99025. * Teleports the users feet to the desired location
  99026. * @param location The location where the user's feet should be placed
  99027. */
  99028. VRExperienceHelper.prototype.teleportCamera = function (location) {
  99029. var _this = this;
  99030. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99031. return;
  99032. }
  99033. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  99034. // offset of the headset from the anchor.
  99035. if (this.webVRCamera.leftCamera) {
  99036. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  99037. this._workingVector.subtractInPlace(this.webVRCamera.position);
  99038. location.subtractToRef(this._workingVector, this._workingVector);
  99039. }
  99040. else {
  99041. this._workingVector.copyFrom(location);
  99042. }
  99043. // Add height to account for user's height offset
  99044. if (this.isInVRMode) {
  99045. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  99046. }
  99047. else {
  99048. this._workingVector.y += this._defaultHeight;
  99049. }
  99050. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  99051. // Create animation from the camera's position to the new location
  99052. this.currentVRCamera.animations = [];
  99053. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99054. var animationCameraTeleportationKeys = [{
  99055. frame: 0,
  99056. value: this.currentVRCamera.position
  99057. },
  99058. {
  99059. frame: 11,
  99060. value: this._workingVector
  99061. }
  99062. ];
  99063. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  99064. animationCameraTeleportation.setEasingFunction(this._circleEase);
  99065. this.currentVRCamera.animations.push(animationCameraTeleportation);
  99066. this._postProcessMove.animations = [];
  99067. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99068. var vignetteWeightKeys = [];
  99069. vignetteWeightKeys.push({
  99070. frame: 0,
  99071. value: 0
  99072. });
  99073. vignetteWeightKeys.push({
  99074. frame: 5,
  99075. value: 8
  99076. });
  99077. vignetteWeightKeys.push({
  99078. frame: 11,
  99079. value: 0
  99080. });
  99081. animationPP.setKeys(vignetteWeightKeys);
  99082. this._postProcessMove.animations.push(animationPP);
  99083. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99084. var vignetteStretchKeys = [];
  99085. vignetteStretchKeys.push({
  99086. frame: 0,
  99087. value: 0
  99088. });
  99089. vignetteStretchKeys.push({
  99090. frame: 5,
  99091. value: 10
  99092. });
  99093. vignetteStretchKeys.push({
  99094. frame: 11,
  99095. value: 0
  99096. });
  99097. animationPP2.setKeys(vignetteStretchKeys);
  99098. this._postProcessMove.animations.push(animationPP2);
  99099. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  99100. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  99101. this._webVRCamera.attachPostProcess(this._postProcessMove);
  99102. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  99103. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  99104. });
  99105. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  99106. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  99107. });
  99108. this._hideTeleportationTarget();
  99109. };
  99110. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  99111. if (normal) {
  99112. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  99113. if (angle < Math.PI / 2) {
  99114. normal.scaleInPlace(-1);
  99115. }
  99116. }
  99117. return normal;
  99118. };
  99119. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  99120. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99121. return;
  99122. }
  99123. var ray = gazer._getForwardRay(this._rayLength);
  99124. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  99125. if (hit) {
  99126. // Populate the contrllers mesh that can be used for drag/drop
  99127. if (gazer._laserPointer) {
  99128. hit.originMesh = gazer._laserPointer.parent;
  99129. }
  99130. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  99131. }
  99132. gazer._currentHit = hit;
  99133. // Moving the gazeTracker on the mesh face targetted
  99134. if (hit && hit.pickedPoint) {
  99135. if (this._displayGaze) {
  99136. var multiplier = 1;
  99137. gazer._gazeTracker.isVisible = true;
  99138. if (gazer._isActionableMesh) {
  99139. multiplier = 3;
  99140. }
  99141. if (this.updateGazeTrackerScale) {
  99142. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  99143. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  99144. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  99145. }
  99146. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  99147. // To avoid z-fighting
  99148. var deltaFighting = 0.002;
  99149. if (pickNormal) {
  99150. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  99151. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  99152. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  99153. }
  99154. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  99155. if (gazer._gazeTracker.position.x < 0) {
  99156. gazer._gazeTracker.position.x += deltaFighting;
  99157. }
  99158. else {
  99159. gazer._gazeTracker.position.x -= deltaFighting;
  99160. }
  99161. if (gazer._gazeTracker.position.y < 0) {
  99162. gazer._gazeTracker.position.y += deltaFighting;
  99163. }
  99164. else {
  99165. gazer._gazeTracker.position.y -= deltaFighting;
  99166. }
  99167. if (gazer._gazeTracker.position.z < 0) {
  99168. gazer._gazeTracker.position.z += deltaFighting;
  99169. }
  99170. else {
  99171. gazer._gazeTracker.position.z -= deltaFighting;
  99172. }
  99173. }
  99174. // Changing the size of the laser pointer based on the distance from the targetted point
  99175. gazer._updatePointerDistance(hit.distance);
  99176. }
  99177. else {
  99178. gazer._updatePointerDistance();
  99179. gazer._gazeTracker.isVisible = false;
  99180. }
  99181. if (hit && hit.pickedMesh) {
  99182. // The object selected is the floor, we're in a teleportation scenario
  99183. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  99184. // Moving the teleportation area to this targetted point
  99185. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  99186. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  99187. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99188. }
  99189. gazer._currentMeshSelected = null;
  99190. if (gazer._teleportationRequestInitiated) {
  99191. this._moveTeleportationSelectorTo(hit, gazer, ray);
  99192. }
  99193. return;
  99194. }
  99195. // If not, we're in a selection scenario
  99196. //this._teleportationAllowed = false;
  99197. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  99198. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  99199. this.onNewMeshPicked.notifyObservers(hit);
  99200. gazer._currentMeshSelected = hit.pickedMesh;
  99201. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  99202. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  99203. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  99204. gazer._isActionableMesh = true;
  99205. }
  99206. else {
  99207. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99208. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99209. gazer._isActionableMesh = false;
  99210. }
  99211. try {
  99212. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  99213. }
  99214. catch (err) {
  99215. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  99216. }
  99217. }
  99218. else {
  99219. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99220. gazer._currentMeshSelected = null;
  99221. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99222. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99223. }
  99224. }
  99225. }
  99226. else {
  99227. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99228. gazer._currentMeshSelected = null;
  99229. //this._teleportationAllowed = false;
  99230. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99231. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99232. }
  99233. };
  99234. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  99235. if (mesh) {
  99236. this.onSelectedMeshUnselected.notifyObservers(mesh);
  99237. }
  99238. };
  99239. /**
  99240. * Sets the color of the laser ray from the vr controllers.
  99241. * @param color new color for the ray.
  99242. */
  99243. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  99244. if (this._leftController) {
  99245. this._leftController._setLaserPointerColor(color);
  99246. }
  99247. if (this._rightController) {
  99248. this._rightController._setLaserPointerColor(color);
  99249. }
  99250. };
  99251. /**
  99252. * Sets the color of the ray from the vr headsets gaze.
  99253. * @param color new color for the ray.
  99254. */
  99255. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  99256. if (!this._cameraGazer._gazeTracker.material) {
  99257. return;
  99258. }
  99259. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  99260. if (this._leftController) {
  99261. this._leftController._gazeTracker.material.emissiveColor = color;
  99262. }
  99263. if (this._rightController) {
  99264. this._rightController._gazeTracker.material.emissiveColor = color;
  99265. }
  99266. };
  99267. /**
  99268. * Exits VR and disposes of the vr experience helper
  99269. */
  99270. VRExperienceHelper.prototype.dispose = function () {
  99271. if (this.isInVRMode) {
  99272. this.exitVR();
  99273. }
  99274. if (this._postProcessMove) {
  99275. this._postProcessMove.dispose();
  99276. }
  99277. if (this._webVRCamera) {
  99278. this._webVRCamera.dispose();
  99279. }
  99280. if (this._vrDeviceOrientationCamera) {
  99281. this._vrDeviceOrientationCamera.dispose();
  99282. }
  99283. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  99284. document.body.removeChild(this._btnVR);
  99285. }
  99286. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  99287. this._deviceOrientationCamera.dispose();
  99288. }
  99289. if (this._cameraGazer) {
  99290. this._cameraGazer.dispose();
  99291. }
  99292. if (this._leftController) {
  99293. this._leftController.dispose();
  99294. }
  99295. if (this._rightController) {
  99296. this._rightController.dispose();
  99297. }
  99298. if (this._teleportationTarget) {
  99299. this._teleportationTarget.dispose();
  99300. }
  99301. this._floorMeshesCollection = [];
  99302. document.removeEventListener("keydown", this._onKeyDown);
  99303. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99304. window.removeEventListener("resize", this._onResize);
  99305. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  99306. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  99307. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  99308. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  99309. document.onmsfullscreenchange = null;
  99310. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  99311. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  99312. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  99313. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99314. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  99315. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  99316. this._scene.unregisterBeforeRender(this.beforeRender);
  99317. };
  99318. /**
  99319. * Gets the name of the VRExperienceHelper class
  99320. * @returns "VRExperienceHelper"
  99321. */
  99322. VRExperienceHelper.prototype.getClassName = function () {
  99323. return "VRExperienceHelper";
  99324. };
  99325. return VRExperienceHelper;
  99326. }());
  99327. BABYLON.VRExperienceHelper = VRExperienceHelper;
  99328. })(BABYLON || (BABYLON = {}));
  99329. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  99330. // Mainly based on these 2 articles :
  99331. // 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
  99332. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  99333. var BABYLON;
  99334. (function (BABYLON) {
  99335. /**
  99336. * Defines the potential axis of a Joystick
  99337. */
  99338. var JoystickAxis;
  99339. (function (JoystickAxis) {
  99340. /** X axis */
  99341. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  99342. /** Y axis */
  99343. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  99344. /** Z axis */
  99345. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  99346. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  99347. /**
  99348. * Class used to define virtual joystick (used in touch mode)
  99349. */
  99350. var VirtualJoystick = /** @class */ (function () {
  99351. /**
  99352. * Creates a new virtual joystick
  99353. * @param leftJoystick defines that the joystick is for left hand (false by default)
  99354. */
  99355. function VirtualJoystick(leftJoystick) {
  99356. var _this = this;
  99357. if (leftJoystick) {
  99358. this._leftJoystick = true;
  99359. }
  99360. else {
  99361. this._leftJoystick = false;
  99362. }
  99363. VirtualJoystick._globalJoystickIndex++;
  99364. // By default left & right arrow keys are moving the X
  99365. // and up & down keys are moving the Y
  99366. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99367. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99368. this.reverseLeftRight = false;
  99369. this.reverseUpDown = false;
  99370. // collections of pointers
  99371. this._touches = new BABYLON.StringDictionary();
  99372. this.deltaPosition = BABYLON.Vector3.Zero();
  99373. this._joystickSensibility = 25;
  99374. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  99375. this._onResize = function (evt) {
  99376. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  99377. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  99378. if (VirtualJoystick.vjCanvas) {
  99379. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  99380. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  99381. }
  99382. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  99383. };
  99384. // injecting a canvas element on top of the canvas 3D game
  99385. if (!VirtualJoystick.vjCanvas) {
  99386. window.addEventListener("resize", this._onResize, false);
  99387. VirtualJoystick.vjCanvas = document.createElement("canvas");
  99388. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  99389. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  99390. VirtualJoystick.vjCanvas.width = window.innerWidth;
  99391. VirtualJoystick.vjCanvas.height = window.innerHeight;
  99392. VirtualJoystick.vjCanvas.style.width = "100%";
  99393. VirtualJoystick.vjCanvas.style.height = "100%";
  99394. VirtualJoystick.vjCanvas.style.position = "absolute";
  99395. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  99396. VirtualJoystick.vjCanvas.style.top = "0px";
  99397. VirtualJoystick.vjCanvas.style.left = "0px";
  99398. VirtualJoystick.vjCanvas.style.zIndex = "5";
  99399. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  99400. // Support for jQuery PEP polyfill
  99401. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  99402. var context = VirtualJoystick.vjCanvas.getContext('2d');
  99403. if (!context) {
  99404. throw new Error("Unable to create canvas for virtual joystick");
  99405. }
  99406. VirtualJoystick.vjCanvasContext = context;
  99407. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  99408. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99409. document.body.appendChild(VirtualJoystick.vjCanvas);
  99410. }
  99411. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  99412. this.pressed = false;
  99413. // default joystick color
  99414. this._joystickColor = "cyan";
  99415. this._joystickPointerID = -1;
  99416. // current joystick position
  99417. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  99418. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  99419. // origin joystick position
  99420. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  99421. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  99422. this._onPointerDownHandlerRef = function (evt) {
  99423. _this._onPointerDown(evt);
  99424. };
  99425. this._onPointerMoveHandlerRef = function (evt) {
  99426. _this._onPointerMove(evt);
  99427. };
  99428. this._onPointerUpHandlerRef = function (evt) {
  99429. _this._onPointerUp(evt);
  99430. };
  99431. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  99432. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  99433. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  99434. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  99435. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  99436. evt.preventDefault(); // Disables system menu
  99437. }, false);
  99438. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99439. }
  99440. /**
  99441. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  99442. * @param newJoystickSensibility defines the new sensibility
  99443. */
  99444. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  99445. this._joystickSensibility = newJoystickSensibility;
  99446. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  99447. };
  99448. VirtualJoystick.prototype._onPointerDown = function (e) {
  99449. var positionOnScreenCondition;
  99450. e.preventDefault();
  99451. if (this._leftJoystick === true) {
  99452. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  99453. }
  99454. else {
  99455. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  99456. }
  99457. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  99458. // First contact will be dedicated to the virtual joystick
  99459. this._joystickPointerID = e.pointerId;
  99460. this._joystickPointerStartPos.x = e.clientX;
  99461. this._joystickPointerStartPos.y = e.clientY;
  99462. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  99463. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  99464. this._deltaJoystickVector.x = 0;
  99465. this._deltaJoystickVector.y = 0;
  99466. this.pressed = true;
  99467. this._touches.add(e.pointerId.toString(), e);
  99468. }
  99469. else {
  99470. // You can only trigger the action buttons with a joystick declared
  99471. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  99472. this._action();
  99473. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  99474. }
  99475. }
  99476. };
  99477. VirtualJoystick.prototype._onPointerMove = function (e) {
  99478. // If the current pointer is the one associated to the joystick (first touch contact)
  99479. if (this._joystickPointerID == e.pointerId) {
  99480. this._joystickPointerPos.x = e.clientX;
  99481. this._joystickPointerPos.y = e.clientY;
  99482. this._deltaJoystickVector = this._joystickPointerPos.clone();
  99483. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  99484. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  99485. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  99486. switch (this._axisTargetedByLeftAndRight) {
  99487. case JoystickAxis.X:
  99488. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  99489. break;
  99490. case JoystickAxis.Y:
  99491. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  99492. break;
  99493. case JoystickAxis.Z:
  99494. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  99495. break;
  99496. }
  99497. var directionUpDown = this.reverseUpDown ? 1 : -1;
  99498. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  99499. switch (this._axisTargetedByUpAndDown) {
  99500. case JoystickAxis.X:
  99501. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  99502. break;
  99503. case JoystickAxis.Y:
  99504. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  99505. break;
  99506. case JoystickAxis.Z:
  99507. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  99508. break;
  99509. }
  99510. }
  99511. else {
  99512. var data = this._touches.get(e.pointerId.toString());
  99513. if (data) {
  99514. data.x = e.clientX;
  99515. data.y = e.clientY;
  99516. }
  99517. }
  99518. };
  99519. VirtualJoystick.prototype._onPointerUp = function (e) {
  99520. if (this._joystickPointerID == e.pointerId) {
  99521. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  99522. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  99523. this._joystickPointerID = -1;
  99524. this.pressed = false;
  99525. }
  99526. else {
  99527. var touch = this._touches.get(e.pointerId.toString());
  99528. if (touch) {
  99529. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99530. }
  99531. }
  99532. this._deltaJoystickVector.x = 0;
  99533. this._deltaJoystickVector.y = 0;
  99534. this._touches.remove(e.pointerId.toString());
  99535. };
  99536. /**
  99537. * Change the color of the virtual joystick
  99538. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  99539. */
  99540. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  99541. this._joystickColor = newColor;
  99542. };
  99543. /**
  99544. * Defines a callback to call when the joystick is touched
  99545. * @param action defines the callback
  99546. */
  99547. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  99548. this._action = action;
  99549. };
  99550. /**
  99551. * Defines which axis you'd like to control for left & right
  99552. * @param axis defines the axis to use
  99553. */
  99554. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  99555. switch (axis) {
  99556. case JoystickAxis.X:
  99557. case JoystickAxis.Y:
  99558. case JoystickAxis.Z:
  99559. this._axisTargetedByLeftAndRight = axis;
  99560. break;
  99561. default:
  99562. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99563. break;
  99564. }
  99565. };
  99566. /**
  99567. * Defines which axis you'd like to control for up & down
  99568. * @param axis defines the axis to use
  99569. */
  99570. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  99571. switch (axis) {
  99572. case JoystickAxis.X:
  99573. case JoystickAxis.Y:
  99574. case JoystickAxis.Z:
  99575. this._axisTargetedByUpAndDown = axis;
  99576. break;
  99577. default:
  99578. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99579. break;
  99580. }
  99581. };
  99582. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  99583. var _this = this;
  99584. if (this.pressed) {
  99585. this._touches.forEach(function (key, touch) {
  99586. if (touch.pointerId === _this._joystickPointerID) {
  99587. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  99588. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  99589. VirtualJoystick.vjCanvasContext.beginPath();
  99590. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99591. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99592. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  99593. VirtualJoystick.vjCanvasContext.stroke();
  99594. VirtualJoystick.vjCanvasContext.closePath();
  99595. VirtualJoystick.vjCanvasContext.beginPath();
  99596. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99597. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99598. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  99599. VirtualJoystick.vjCanvasContext.stroke();
  99600. VirtualJoystick.vjCanvasContext.closePath();
  99601. VirtualJoystick.vjCanvasContext.beginPath();
  99602. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99603. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  99604. VirtualJoystick.vjCanvasContext.stroke();
  99605. VirtualJoystick.vjCanvasContext.closePath();
  99606. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  99607. }
  99608. else {
  99609. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99610. VirtualJoystick.vjCanvasContext.beginPath();
  99611. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  99612. VirtualJoystick.vjCanvasContext.beginPath();
  99613. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  99614. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99615. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  99616. VirtualJoystick.vjCanvasContext.stroke();
  99617. VirtualJoystick.vjCanvasContext.closePath();
  99618. touch.prevX = touch.x;
  99619. touch.prevY = touch.y;
  99620. }
  99621. ;
  99622. });
  99623. }
  99624. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99625. };
  99626. /**
  99627. * Release internal HTML canvas
  99628. */
  99629. VirtualJoystick.prototype.releaseCanvas = function () {
  99630. if (VirtualJoystick.vjCanvas) {
  99631. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  99632. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  99633. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  99634. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  99635. window.removeEventListener("resize", this._onResize);
  99636. document.body.removeChild(VirtualJoystick.vjCanvas);
  99637. VirtualJoystick.vjCanvas = null;
  99638. }
  99639. };
  99640. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  99641. VirtualJoystick._globalJoystickIndex = 0;
  99642. return VirtualJoystick;
  99643. }());
  99644. BABYLON.VirtualJoystick = VirtualJoystick;
  99645. })(BABYLON || (BABYLON = {}));
  99646. //# sourceMappingURL=babylon.virtualJoystick.js.map
  99647. var BABYLON;
  99648. (function (BABYLON) {
  99649. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  99650. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  99651. });
  99652. // We're mainly based on the logic defined into the FreeCamera code
  99653. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  99654. __extends(VirtualJoysticksCamera, _super);
  99655. function VirtualJoysticksCamera(name, position, scene) {
  99656. var _this = _super.call(this, name, position, scene) || this;
  99657. _this.inputs.addVirtualJoystick();
  99658. return _this;
  99659. }
  99660. VirtualJoysticksCamera.prototype.getClassName = function () {
  99661. return "VirtualJoysticksCamera";
  99662. };
  99663. return VirtualJoysticksCamera;
  99664. }(BABYLON.FreeCamera));
  99665. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  99666. })(BABYLON || (BABYLON = {}));
  99667. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  99668. var BABYLON;
  99669. (function (BABYLON) {
  99670. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  99671. function FreeCameraVirtualJoystickInput() {
  99672. }
  99673. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  99674. return this._leftjoystick;
  99675. };
  99676. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  99677. return this._rightjoystick;
  99678. };
  99679. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  99680. if (this._leftjoystick) {
  99681. var camera = this.camera;
  99682. var speed = camera._computeLocalCameraSpeed() * 50;
  99683. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  99684. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  99685. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  99686. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  99687. if (!this._leftjoystick.pressed) {
  99688. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  99689. }
  99690. if (!this._rightjoystick.pressed) {
  99691. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  99692. }
  99693. }
  99694. };
  99695. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  99696. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  99697. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  99698. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  99699. this._leftjoystick.setJoystickSensibility(0.15);
  99700. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  99701. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  99702. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  99703. this._rightjoystick.reverseUpDown = true;
  99704. this._rightjoystick.setJoystickSensibility(0.05);
  99705. this._rightjoystick.setJoystickColor("yellow");
  99706. };
  99707. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  99708. this._leftjoystick.releaseCanvas();
  99709. this._rightjoystick.releaseCanvas();
  99710. };
  99711. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  99712. return "FreeCameraVirtualJoystickInput";
  99713. };
  99714. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  99715. return "virtualJoystick";
  99716. };
  99717. return FreeCameraVirtualJoystickInput;
  99718. }());
  99719. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  99720. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  99721. })(BABYLON || (BABYLON = {}));
  99722. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  99723. var BABYLON;
  99724. (function (BABYLON) {
  99725. var SimplificationSettings = /** @class */ (function () {
  99726. function SimplificationSettings(quality, distance, optimizeMesh) {
  99727. this.quality = quality;
  99728. this.distance = distance;
  99729. this.optimizeMesh = optimizeMesh;
  99730. }
  99731. return SimplificationSettings;
  99732. }());
  99733. BABYLON.SimplificationSettings = SimplificationSettings;
  99734. var SimplificationQueue = /** @class */ (function () {
  99735. function SimplificationQueue() {
  99736. this.running = false;
  99737. this._simplificationArray = [];
  99738. }
  99739. SimplificationQueue.prototype.addTask = function (task) {
  99740. this._simplificationArray.push(task);
  99741. };
  99742. SimplificationQueue.prototype.executeNext = function () {
  99743. var task = this._simplificationArray.pop();
  99744. if (task) {
  99745. this.running = true;
  99746. this.runSimplification(task);
  99747. }
  99748. else {
  99749. this.running = false;
  99750. }
  99751. };
  99752. SimplificationQueue.prototype.runSimplification = function (task) {
  99753. var _this = this;
  99754. if (task.parallelProcessing) {
  99755. //parallel simplifier
  99756. task.settings.forEach(function (setting) {
  99757. var simplifier = _this.getSimplifier(task);
  99758. simplifier.simplify(setting, function (newMesh) {
  99759. task.mesh.addLODLevel(setting.distance, newMesh);
  99760. newMesh.isVisible = true;
  99761. //check if it is the last
  99762. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  99763. //all done, run the success callback.
  99764. task.successCallback();
  99765. }
  99766. _this.executeNext();
  99767. });
  99768. });
  99769. }
  99770. else {
  99771. //single simplifier.
  99772. var simplifier = this.getSimplifier(task);
  99773. var runDecimation = function (setting, callback) {
  99774. simplifier.simplify(setting, function (newMesh) {
  99775. task.mesh.addLODLevel(setting.distance, newMesh);
  99776. newMesh.isVisible = true;
  99777. //run the next quality level
  99778. callback();
  99779. });
  99780. };
  99781. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  99782. runDecimation(task.settings[loop.index], function () {
  99783. loop.executeNext();
  99784. });
  99785. }, function () {
  99786. //execution ended, run the success callback.
  99787. if (task.successCallback) {
  99788. task.successCallback();
  99789. }
  99790. _this.executeNext();
  99791. });
  99792. }
  99793. };
  99794. SimplificationQueue.prototype.getSimplifier = function (task) {
  99795. switch (task.simplificationType) {
  99796. case SimplificationType.QUADRATIC:
  99797. default:
  99798. return new QuadraticErrorSimplification(task.mesh);
  99799. }
  99800. };
  99801. return SimplificationQueue;
  99802. }());
  99803. BABYLON.SimplificationQueue = SimplificationQueue;
  99804. /**
  99805. * The implemented types of simplification
  99806. * At the moment only Quadratic Error Decimation is implemented
  99807. */
  99808. var SimplificationType;
  99809. (function (SimplificationType) {
  99810. /** Quadratic error decimation */
  99811. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  99812. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  99813. var DecimationTriangle = /** @class */ (function () {
  99814. function DecimationTriangle(vertices) {
  99815. this.vertices = vertices;
  99816. this.error = new Array(4);
  99817. this.deleted = false;
  99818. this.isDirty = false;
  99819. this.deletePending = false;
  99820. this.borderFactor = 0;
  99821. }
  99822. return DecimationTriangle;
  99823. }());
  99824. BABYLON.DecimationTriangle = DecimationTriangle;
  99825. var DecimationVertex = /** @class */ (function () {
  99826. function DecimationVertex(position, id) {
  99827. this.position = position;
  99828. this.id = id;
  99829. this.isBorder = true;
  99830. this.q = new QuadraticMatrix();
  99831. this.triangleCount = 0;
  99832. this.triangleStart = 0;
  99833. this.originalOffsets = [];
  99834. }
  99835. DecimationVertex.prototype.updatePosition = function (newPosition) {
  99836. this.position.copyFrom(newPosition);
  99837. };
  99838. return DecimationVertex;
  99839. }());
  99840. BABYLON.DecimationVertex = DecimationVertex;
  99841. var QuadraticMatrix = /** @class */ (function () {
  99842. function QuadraticMatrix(data) {
  99843. this.data = new Array(10);
  99844. for (var i = 0; i < 10; ++i) {
  99845. if (data && data[i]) {
  99846. this.data[i] = data[i];
  99847. }
  99848. else {
  99849. this.data[i] = 0;
  99850. }
  99851. }
  99852. }
  99853. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  99854. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  99855. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  99856. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  99857. return det;
  99858. };
  99859. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  99860. for (var i = 0; i < 10; ++i) {
  99861. this.data[i] += matrix.data[i];
  99862. }
  99863. };
  99864. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  99865. for (var i = 0; i < 10; ++i) {
  99866. this.data[i] += data[i];
  99867. }
  99868. };
  99869. QuadraticMatrix.prototype.add = function (matrix) {
  99870. var m = new QuadraticMatrix();
  99871. for (var i = 0; i < 10; ++i) {
  99872. m.data[i] = this.data[i] + matrix.data[i];
  99873. }
  99874. return m;
  99875. };
  99876. QuadraticMatrix.FromData = function (a, b, c, d) {
  99877. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  99878. };
  99879. //returning an array to avoid garbage collection
  99880. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  99881. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  99882. };
  99883. return QuadraticMatrix;
  99884. }());
  99885. BABYLON.QuadraticMatrix = QuadraticMatrix;
  99886. var Reference = /** @class */ (function () {
  99887. function Reference(vertexId, triangleId) {
  99888. this.vertexId = vertexId;
  99889. this.triangleId = triangleId;
  99890. }
  99891. return Reference;
  99892. }());
  99893. BABYLON.Reference = Reference;
  99894. /**
  99895. * An implementation of the Quadratic Error simplification algorithm.
  99896. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  99897. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  99898. * @author RaananW
  99899. */
  99900. var QuadraticErrorSimplification = /** @class */ (function () {
  99901. function QuadraticErrorSimplification(_mesh) {
  99902. this._mesh = _mesh;
  99903. this.syncIterations = 5000;
  99904. this.aggressiveness = 7;
  99905. this.decimationIterations = 100;
  99906. this.boundingBoxEpsilon = BABYLON.Epsilon;
  99907. }
  99908. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  99909. var _this = this;
  99910. this.initDecimatedMesh();
  99911. //iterating through the submeshes array, one after the other.
  99912. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  99913. _this.initWithMesh(loop.index, function () {
  99914. _this.runDecimation(settings, loop.index, function () {
  99915. loop.executeNext();
  99916. });
  99917. }, settings.optimizeMesh);
  99918. }, function () {
  99919. setTimeout(function () {
  99920. successCallback(_this._reconstructedMesh);
  99921. }, 0);
  99922. });
  99923. };
  99924. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  99925. var _this = this;
  99926. var targetCount = ~~(this.triangles.length * settings.quality);
  99927. var deletedTriangles = 0;
  99928. var triangleCount = this.triangles.length;
  99929. var iterationFunction = function (iteration, callback) {
  99930. setTimeout(function () {
  99931. if (iteration % 5 === 0) {
  99932. _this.updateMesh(iteration === 0);
  99933. }
  99934. for (var i = 0; i < _this.triangles.length; ++i) {
  99935. _this.triangles[i].isDirty = false;
  99936. }
  99937. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  99938. var trianglesIterator = function (i) {
  99939. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  99940. var t = _this.triangles[tIdx];
  99941. if (!t)
  99942. return;
  99943. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  99944. return;
  99945. }
  99946. for (var j = 0; j < 3; ++j) {
  99947. if (t.error[j] < threshold) {
  99948. var deleted0 = [];
  99949. var deleted1 = [];
  99950. var v0 = t.vertices[j];
  99951. var v1 = t.vertices[(j + 1) % 3];
  99952. if (v0.isBorder || v1.isBorder)
  99953. continue;
  99954. var p = BABYLON.Vector3.Zero();
  99955. var n = BABYLON.Vector3.Zero();
  99956. var uv = BABYLON.Vector2.Zero();
  99957. var color = new BABYLON.Color4(0, 0, 0, 1);
  99958. _this.calculateError(v0, v1, p, n, uv, color);
  99959. var delTr = new Array();
  99960. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  99961. continue;
  99962. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  99963. continue;
  99964. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  99965. continue;
  99966. var uniqueArray = new Array();
  99967. delTr.forEach(function (deletedT) {
  99968. if (uniqueArray.indexOf(deletedT) === -1) {
  99969. deletedT.deletePending = true;
  99970. uniqueArray.push(deletedT);
  99971. }
  99972. });
  99973. if (uniqueArray.length % 2 !== 0) {
  99974. continue;
  99975. }
  99976. v0.q = v1.q.add(v0.q);
  99977. v0.updatePosition(p);
  99978. var tStart = _this.references.length;
  99979. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  99980. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  99981. var tCount = _this.references.length - tStart;
  99982. if (tCount <= v0.triangleCount) {
  99983. if (tCount) {
  99984. for (var c = 0; c < tCount; c++) {
  99985. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  99986. }
  99987. }
  99988. }
  99989. else {
  99990. v0.triangleStart = tStart;
  99991. }
  99992. v0.triangleCount = tCount;
  99993. break;
  99994. }
  99995. }
  99996. };
  99997. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  99998. }, 0);
  99999. };
  100000. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  100001. if (triangleCount - deletedTriangles <= targetCount)
  100002. loop.breakLoop();
  100003. else {
  100004. iterationFunction(loop.index, function () {
  100005. loop.executeNext();
  100006. });
  100007. }
  100008. }, function () {
  100009. setTimeout(function () {
  100010. //reconstruct this part of the mesh
  100011. _this.reconstructMesh(submeshIndex);
  100012. successCallback();
  100013. }, 0);
  100014. });
  100015. };
  100016. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  100017. var _this = this;
  100018. this.vertices = [];
  100019. this.triangles = [];
  100020. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  100021. var indices = this._mesh.getIndices();
  100022. var submesh = this._mesh.subMeshes[submeshIndex];
  100023. var findInVertices = function (positionToSearch) {
  100024. if (optimizeMesh) {
  100025. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  100026. if (_this.vertices[ii].position.equals(positionToSearch)) {
  100027. return _this.vertices[ii];
  100028. }
  100029. }
  100030. }
  100031. return null;
  100032. };
  100033. var vertexReferences = [];
  100034. var vertexInit = function (i) {
  100035. if (!positionData) {
  100036. return;
  100037. }
  100038. var offset = i + submesh.verticesStart;
  100039. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  100040. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  100041. vertex.originalOffsets.push(offset);
  100042. if (vertex.id === _this.vertices.length) {
  100043. _this.vertices.push(vertex);
  100044. }
  100045. vertexReferences.push(vertex.id);
  100046. };
  100047. //var totalVertices = mesh.getTotalVertices();
  100048. var totalVertices = submesh.verticesCount;
  100049. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  100050. var indicesInit = function (i) {
  100051. if (!indices) {
  100052. return;
  100053. }
  100054. var offset = (submesh.indexStart / 3) + i;
  100055. var pos = (offset * 3);
  100056. var i0 = indices[pos + 0];
  100057. var i1 = indices[pos + 1];
  100058. var i2 = indices[pos + 2];
  100059. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  100060. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  100061. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  100062. var triangle = new DecimationTriangle([v0, v1, v2]);
  100063. triangle.originalOffset = pos;
  100064. _this.triangles.push(triangle);
  100065. };
  100066. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  100067. _this.init(callback);
  100068. });
  100069. });
  100070. };
  100071. QuadraticErrorSimplification.prototype.init = function (callback) {
  100072. var _this = this;
  100073. var triangleInit1 = function (i) {
  100074. var t = _this.triangles[i];
  100075. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  100076. for (var j = 0; j < 3; j++) {
  100077. 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))));
  100078. }
  100079. };
  100080. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  100081. var triangleInit2 = function (i) {
  100082. var t = _this.triangles[i];
  100083. for (var j = 0; j < 3; ++j) {
  100084. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  100085. }
  100086. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  100087. };
  100088. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  100089. callback();
  100090. });
  100091. });
  100092. };
  100093. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  100094. var newTriangles = [];
  100095. var i;
  100096. for (i = 0; i < this.vertices.length; ++i) {
  100097. this.vertices[i].triangleCount = 0;
  100098. }
  100099. var t;
  100100. var j;
  100101. for (i = 0; i < this.triangles.length; ++i) {
  100102. if (!this.triangles[i].deleted) {
  100103. t = this.triangles[i];
  100104. for (j = 0; j < 3; ++j) {
  100105. t.vertices[j].triangleCount = 1;
  100106. }
  100107. newTriangles.push(t);
  100108. }
  100109. }
  100110. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  100111. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  100112. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  100113. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  100114. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  100115. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  100116. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  100117. var vertexCount = 0;
  100118. for (i = 0; i < this.vertices.length; ++i) {
  100119. var vertex = this.vertices[i];
  100120. vertex.id = vertexCount;
  100121. if (vertex.triangleCount) {
  100122. vertex.originalOffsets.forEach(function (originalOffset) {
  100123. if (!normalData) {
  100124. return;
  100125. }
  100126. newPositionData.push(vertex.position.x);
  100127. newPositionData.push(vertex.position.y);
  100128. newPositionData.push(vertex.position.z);
  100129. newNormalData.push(normalData[originalOffset * 3]);
  100130. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  100131. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  100132. if (uvs && uvs.length) {
  100133. newUVsData.push(uvs[(originalOffset * 2)]);
  100134. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  100135. }
  100136. else if (colorsData && colorsData.length) {
  100137. newColorsData.push(colorsData[(originalOffset * 4)]);
  100138. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  100139. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  100140. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  100141. }
  100142. ++vertexCount;
  100143. });
  100144. }
  100145. }
  100146. var startingIndex = this._reconstructedMesh.getTotalIndices();
  100147. var startingVertex = this._reconstructedMesh.getTotalVertices();
  100148. var submeshesArray = this._reconstructedMesh.subMeshes;
  100149. this._reconstructedMesh.subMeshes = [];
  100150. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  100151. var originalIndices = this._mesh.getIndices();
  100152. for (i = 0; i < newTriangles.length; ++i) {
  100153. t = newTriangles[i]; //now get the new referencing point for each vertex
  100154. [0, 1, 2].forEach(function (idx) {
  100155. var id = originalIndices[t.originalOffset + idx];
  100156. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  100157. if (offset < 0)
  100158. offset = 0;
  100159. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  100160. });
  100161. }
  100162. //overwriting the old vertex buffers and indices.
  100163. this._reconstructedMesh.setIndices(newIndicesArray);
  100164. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  100165. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  100166. if (newUVsData.length > 0)
  100167. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  100168. if (newColorsData.length > 0)
  100169. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  100170. //create submesh
  100171. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  100172. if (submeshIndex > 0) {
  100173. this._reconstructedMesh.subMeshes = [];
  100174. submeshesArray.forEach(function (submesh) {
  100175. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  100176. });
  100177. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  100178. }
  100179. };
  100180. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  100181. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  100182. this._reconstructedMesh.material = this._mesh.material;
  100183. this._reconstructedMesh.parent = this._mesh.parent;
  100184. this._reconstructedMesh.isVisible = false;
  100185. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  100186. };
  100187. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  100188. for (var i = 0; i < vertex1.triangleCount; ++i) {
  100189. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  100190. if (t.deleted)
  100191. continue;
  100192. var s = this.references[vertex1.triangleStart + i].vertexId;
  100193. var v1 = t.vertices[(s + 1) % 3];
  100194. var v2 = t.vertices[(s + 2) % 3];
  100195. if ((v1 === vertex2 || v2 === vertex2)) {
  100196. deletedArray[i] = true;
  100197. delTr.push(t);
  100198. continue;
  100199. }
  100200. var d1 = v1.position.subtract(point);
  100201. d1 = d1.normalize();
  100202. var d2 = v2.position.subtract(point);
  100203. d2 = d2.normalize();
  100204. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  100205. return true;
  100206. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  100207. deletedArray[i] = false;
  100208. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  100209. return true;
  100210. }
  100211. return false;
  100212. };
  100213. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  100214. var newDeleted = deletedTriangles;
  100215. for (var i = 0; i < vertex.triangleCount; ++i) {
  100216. var ref = this.references[vertex.triangleStart + i];
  100217. var t = this.triangles[ref.triangleId];
  100218. if (t.deleted)
  100219. continue;
  100220. if (deletedArray[i] && t.deletePending) {
  100221. t.deleted = true;
  100222. newDeleted++;
  100223. continue;
  100224. }
  100225. t.vertices[ref.vertexId] = origVertex;
  100226. t.isDirty = true;
  100227. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  100228. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  100229. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  100230. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  100231. this.references.push(ref);
  100232. }
  100233. return newDeleted;
  100234. };
  100235. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  100236. for (var i = 0; i < this.vertices.length; ++i) {
  100237. var vCount = [];
  100238. var vId = [];
  100239. var v = this.vertices[i];
  100240. var j;
  100241. for (j = 0; j < v.triangleCount; ++j) {
  100242. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  100243. for (var ii = 0; ii < 3; ii++) {
  100244. var ofs = 0;
  100245. var vv = triangle.vertices[ii];
  100246. while (ofs < vCount.length) {
  100247. if (vId[ofs] === vv.id)
  100248. break;
  100249. ++ofs;
  100250. }
  100251. if (ofs === vCount.length) {
  100252. vCount.push(1);
  100253. vId.push(vv.id);
  100254. }
  100255. else {
  100256. vCount[ofs]++;
  100257. }
  100258. }
  100259. }
  100260. for (j = 0; j < vCount.length; ++j) {
  100261. if (vCount[j] === 1) {
  100262. this.vertices[vId[j]].isBorder = true;
  100263. }
  100264. else {
  100265. this.vertices[vId[j]].isBorder = false;
  100266. }
  100267. }
  100268. }
  100269. };
  100270. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  100271. if (identifyBorders === void 0) { identifyBorders = false; }
  100272. var i;
  100273. if (!identifyBorders) {
  100274. var newTrianglesVector = [];
  100275. for (i = 0; i < this.triangles.length; ++i) {
  100276. if (!this.triangles[i].deleted) {
  100277. newTrianglesVector.push(this.triangles[i]);
  100278. }
  100279. }
  100280. this.triangles = newTrianglesVector;
  100281. }
  100282. for (i = 0; i < this.vertices.length; ++i) {
  100283. this.vertices[i].triangleCount = 0;
  100284. this.vertices[i].triangleStart = 0;
  100285. }
  100286. var t;
  100287. var j;
  100288. var v;
  100289. for (i = 0; i < this.triangles.length; ++i) {
  100290. t = this.triangles[i];
  100291. for (j = 0; j < 3; ++j) {
  100292. v = t.vertices[j];
  100293. v.triangleCount++;
  100294. }
  100295. }
  100296. var tStart = 0;
  100297. for (i = 0; i < this.vertices.length; ++i) {
  100298. this.vertices[i].triangleStart = tStart;
  100299. tStart += this.vertices[i].triangleCount;
  100300. this.vertices[i].triangleCount = 0;
  100301. }
  100302. var newReferences = new Array(this.triangles.length * 3);
  100303. for (i = 0; i < this.triangles.length; ++i) {
  100304. t = this.triangles[i];
  100305. for (j = 0; j < 3; ++j) {
  100306. v = t.vertices[j];
  100307. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  100308. v.triangleCount++;
  100309. }
  100310. }
  100311. this.references = newReferences;
  100312. if (identifyBorders) {
  100313. this.identifyBorder();
  100314. }
  100315. };
  100316. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  100317. var x = point.x;
  100318. var y = point.y;
  100319. var z = point.z;
  100320. 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
  100321. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  100322. };
  100323. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  100324. var q = vertex1.q.add(vertex2.q);
  100325. var border = vertex1.isBorder && vertex2.isBorder;
  100326. var error = 0;
  100327. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  100328. if (qDet !== 0 && !border) {
  100329. if (!pointResult) {
  100330. pointResult = BABYLON.Vector3.Zero();
  100331. }
  100332. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  100333. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  100334. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  100335. error = this.vertexError(q, pointResult);
  100336. }
  100337. else {
  100338. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  100339. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  100340. var error1 = this.vertexError(q, vertex1.position);
  100341. var error2 = this.vertexError(q, vertex2.position);
  100342. var error3 = this.vertexError(q, p3);
  100343. error = Math.min(error1, error2, error3);
  100344. if (error === error1) {
  100345. if (pointResult) {
  100346. pointResult.copyFrom(vertex1.position);
  100347. }
  100348. }
  100349. else if (error === error2) {
  100350. if (pointResult) {
  100351. pointResult.copyFrom(vertex2.position);
  100352. }
  100353. }
  100354. else {
  100355. if (pointResult) {
  100356. pointResult.copyFrom(p3);
  100357. }
  100358. }
  100359. }
  100360. return error;
  100361. };
  100362. return QuadraticErrorSimplification;
  100363. }());
  100364. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  100365. })(BABYLON || (BABYLON = {}));
  100366. //# sourceMappingURL=babylon.meshSimplification.js.map
  100367. var BABYLON;
  100368. (function (BABYLON) {
  100369. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  100370. get: function () {
  100371. if (!this._simplificationQueue) {
  100372. this._simplificationQueue = new BABYLON.SimplificationQueue();
  100373. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  100374. if (!component) {
  100375. component = new SimplicationQueueSceneComponent(this);
  100376. this._addComponent(component);
  100377. }
  100378. }
  100379. return this._simplificationQueue;
  100380. },
  100381. set: function (value) {
  100382. this._simplificationQueue = value;
  100383. },
  100384. enumerable: true,
  100385. configurable: true
  100386. });
  100387. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  100388. if (parallelProcessing === void 0) { parallelProcessing = true; }
  100389. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  100390. this.getScene().simplificationQueue.addTask({
  100391. settings: settings,
  100392. parallelProcessing: parallelProcessing,
  100393. mesh: this,
  100394. simplificationType: simplificationType,
  100395. successCallback: successCallback
  100396. });
  100397. return this;
  100398. };
  100399. /**
  100400. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  100401. * created in a scene
  100402. */
  100403. var SimplicationQueueSceneComponent = /** @class */ (function () {
  100404. /**
  100405. * Creates a new instance of the component for the given scene
  100406. * @param scene Defines the scene to register the component in
  100407. */
  100408. function SimplicationQueueSceneComponent(scene) {
  100409. /**
  100410. * The component name helpfull to identify the component in the list of scene components.
  100411. */
  100412. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  100413. this.scene = scene;
  100414. }
  100415. /**
  100416. * Registers the component in a given scene
  100417. */
  100418. SimplicationQueueSceneComponent.prototype.register = function () {
  100419. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  100420. };
  100421. /**
  100422. * Rebuilds the elements related to this component in case of
  100423. * context lost for instance.
  100424. */
  100425. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  100426. // Nothing to do for this component
  100427. };
  100428. /**
  100429. * Disposes the component and the associated ressources
  100430. */
  100431. SimplicationQueueSceneComponent.prototype.dispose = function () {
  100432. // Nothing to do for this component
  100433. };
  100434. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  100435. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  100436. this.scene._simplificationQueue.executeNext();
  100437. }
  100438. };
  100439. return SimplicationQueueSceneComponent;
  100440. }());
  100441. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  100442. })(BABYLON || (BABYLON = {}));
  100443. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  100444. var BABYLON;
  100445. (function (BABYLON) {
  100446. var MeshLODLevel = /** @class */ (function () {
  100447. function MeshLODLevel(distance, mesh) {
  100448. this.distance = distance;
  100449. this.mesh = mesh;
  100450. }
  100451. return MeshLODLevel;
  100452. }());
  100453. BABYLON.MeshLODLevel = MeshLODLevel;
  100454. })(BABYLON || (BABYLON = {}));
  100455. //# sourceMappingURL=babylon.meshLODLevel.js.map
  100456. var BABYLON;
  100457. (function (BABYLON) {
  100458. /**
  100459. * Defines the root class used to create scene optimization to use with SceneOptimizer
  100460. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100461. */
  100462. var SceneOptimization = /** @class */ (function () {
  100463. /**
  100464. * Creates the SceneOptimization object
  100465. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100466. * @param desc defines the description associated with the optimization
  100467. */
  100468. function SceneOptimization(
  100469. /**
  100470. * Defines the priority of this optimization (0 by default which means first in the list)
  100471. */
  100472. priority) {
  100473. if (priority === void 0) { priority = 0; }
  100474. this.priority = priority;
  100475. }
  100476. /**
  100477. * Gets a string describing the action executed by the current optimization
  100478. * @returns description string
  100479. */
  100480. SceneOptimization.prototype.getDescription = function () {
  100481. return "";
  100482. };
  100483. /**
  100484. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100485. * @param scene defines the current scene where to apply this optimization
  100486. * @param optimizer defines the current optimizer
  100487. * @returns true if everything that can be done was applied
  100488. */
  100489. SceneOptimization.prototype.apply = function (scene, optimizer) {
  100490. return true;
  100491. };
  100492. ;
  100493. return SceneOptimization;
  100494. }());
  100495. BABYLON.SceneOptimization = SceneOptimization;
  100496. /**
  100497. * Defines an optimization used to reduce the size of render target textures
  100498. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100499. */
  100500. var TextureOptimization = /** @class */ (function (_super) {
  100501. __extends(TextureOptimization, _super);
  100502. /**
  100503. * Creates the TextureOptimization object
  100504. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100505. * @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
  100506. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100507. */
  100508. function TextureOptimization(
  100509. /**
  100510. * Defines the priority of this optimization (0 by default which means first in the list)
  100511. */
  100512. priority,
  100513. /**
  100514. * 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
  100515. */
  100516. maximumSize,
  100517. /**
  100518. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100519. */
  100520. step) {
  100521. if (priority === void 0) { priority = 0; }
  100522. if (maximumSize === void 0) { maximumSize = 1024; }
  100523. if (step === void 0) { step = 0.5; }
  100524. var _this = _super.call(this, priority) || this;
  100525. _this.priority = priority;
  100526. _this.maximumSize = maximumSize;
  100527. _this.step = step;
  100528. return _this;
  100529. }
  100530. /**
  100531. * Gets a string describing the action executed by the current optimization
  100532. * @returns description string
  100533. */
  100534. TextureOptimization.prototype.getDescription = function () {
  100535. return "Reducing render target texture size to " + this.maximumSize;
  100536. };
  100537. /**
  100538. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100539. * @param scene defines the current scene where to apply this optimization
  100540. * @param optimizer defines the current optimizer
  100541. * @returns true if everything that can be done was applied
  100542. */
  100543. TextureOptimization.prototype.apply = function (scene, optimizer) {
  100544. var allDone = true;
  100545. for (var index = 0; index < scene.textures.length; index++) {
  100546. var texture = scene.textures[index];
  100547. if (!texture.canRescale || texture.getContext) {
  100548. continue;
  100549. }
  100550. var currentSize = texture.getSize();
  100551. var maxDimension = Math.max(currentSize.width, currentSize.height);
  100552. if (maxDimension > this.maximumSize) {
  100553. texture.scale(this.step);
  100554. allDone = false;
  100555. }
  100556. }
  100557. return allDone;
  100558. };
  100559. return TextureOptimization;
  100560. }(SceneOptimization));
  100561. BABYLON.TextureOptimization = TextureOptimization;
  100562. /**
  100563. * Defines an optimization used to increase or decrease the rendering resolution
  100564. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100565. */
  100566. var HardwareScalingOptimization = /** @class */ (function (_super) {
  100567. __extends(HardwareScalingOptimization, _super);
  100568. /**
  100569. * Creates the HardwareScalingOptimization object
  100570. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100571. * @param maximumScale defines the maximum scale to use (2 by default)
  100572. * @param step defines the step to use between two passes (0.5 by default)
  100573. */
  100574. function HardwareScalingOptimization(
  100575. /**
  100576. * Defines the priority of this optimization (0 by default which means first in the list)
  100577. */
  100578. priority,
  100579. /**
  100580. * Defines the maximum scale to use (2 by default)
  100581. */
  100582. maximumScale,
  100583. /**
  100584. * Defines the step to use between two passes (0.5 by default)
  100585. */
  100586. step) {
  100587. if (priority === void 0) { priority = 0; }
  100588. if (maximumScale === void 0) { maximumScale = 2; }
  100589. if (step === void 0) { step = 0.25; }
  100590. var _this = _super.call(this, priority) || this;
  100591. _this.priority = priority;
  100592. _this.maximumScale = maximumScale;
  100593. _this.step = step;
  100594. _this._currentScale = -1;
  100595. _this._directionOffset = 1;
  100596. return _this;
  100597. }
  100598. /**
  100599. * Gets a string describing the action executed by the current optimization
  100600. * @return description string
  100601. */
  100602. HardwareScalingOptimization.prototype.getDescription = function () {
  100603. return "Setting hardware scaling level to " + this._currentScale;
  100604. };
  100605. /**
  100606. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100607. * @param scene defines the current scene where to apply this optimization
  100608. * @param optimizer defines the current optimizer
  100609. * @returns true if everything that can be done was applied
  100610. */
  100611. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  100612. if (this._currentScale === -1) {
  100613. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  100614. if (this._currentScale > this.maximumScale) {
  100615. this._directionOffset = -1;
  100616. }
  100617. }
  100618. this._currentScale += this._directionOffset * this.step;
  100619. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  100620. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  100621. };
  100622. ;
  100623. return HardwareScalingOptimization;
  100624. }(SceneOptimization));
  100625. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  100626. /**
  100627. * Defines an optimization used to remove shadows
  100628. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100629. */
  100630. var ShadowsOptimization = /** @class */ (function (_super) {
  100631. __extends(ShadowsOptimization, _super);
  100632. function ShadowsOptimization() {
  100633. return _super !== null && _super.apply(this, arguments) || this;
  100634. }
  100635. /**
  100636. * Gets a string describing the action executed by the current optimization
  100637. * @return description string
  100638. */
  100639. ShadowsOptimization.prototype.getDescription = function () {
  100640. return "Turning shadows on/off";
  100641. };
  100642. /**
  100643. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100644. * @param scene defines the current scene where to apply this optimization
  100645. * @param optimizer defines the current optimizer
  100646. * @returns true if everything that can be done was applied
  100647. */
  100648. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  100649. scene.shadowsEnabled = optimizer.isInImprovementMode;
  100650. return true;
  100651. };
  100652. ;
  100653. return ShadowsOptimization;
  100654. }(SceneOptimization));
  100655. BABYLON.ShadowsOptimization = ShadowsOptimization;
  100656. /**
  100657. * Defines an optimization used to turn post-processes off
  100658. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100659. */
  100660. var PostProcessesOptimization = /** @class */ (function (_super) {
  100661. __extends(PostProcessesOptimization, _super);
  100662. function PostProcessesOptimization() {
  100663. return _super !== null && _super.apply(this, arguments) || this;
  100664. }
  100665. /**
  100666. * Gets a string describing the action executed by the current optimization
  100667. * @return description string
  100668. */
  100669. PostProcessesOptimization.prototype.getDescription = function () {
  100670. return "Turning post-processes on/off";
  100671. };
  100672. /**
  100673. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100674. * @param scene defines the current scene where to apply this optimization
  100675. * @param optimizer defines the current optimizer
  100676. * @returns true if everything that can be done was applied
  100677. */
  100678. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  100679. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  100680. return true;
  100681. };
  100682. ;
  100683. return PostProcessesOptimization;
  100684. }(SceneOptimization));
  100685. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  100686. /**
  100687. * Defines an optimization used to turn lens flares off
  100688. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100689. */
  100690. var LensFlaresOptimization = /** @class */ (function (_super) {
  100691. __extends(LensFlaresOptimization, _super);
  100692. function LensFlaresOptimization() {
  100693. return _super !== null && _super.apply(this, arguments) || this;
  100694. }
  100695. /**
  100696. * Gets a string describing the action executed by the current optimization
  100697. * @return description string
  100698. */
  100699. LensFlaresOptimization.prototype.getDescription = function () {
  100700. return "Turning lens flares on/off";
  100701. };
  100702. /**
  100703. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100704. * @param scene defines the current scene where to apply this optimization
  100705. * @param optimizer defines the current optimizer
  100706. * @returns true if everything that can be done was applied
  100707. */
  100708. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  100709. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  100710. return true;
  100711. };
  100712. ;
  100713. return LensFlaresOptimization;
  100714. }(SceneOptimization));
  100715. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  100716. /**
  100717. * Defines an optimization based on user defined callback.
  100718. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100719. */
  100720. var CustomOptimization = /** @class */ (function (_super) {
  100721. __extends(CustomOptimization, _super);
  100722. function CustomOptimization() {
  100723. return _super !== null && _super.apply(this, arguments) || this;
  100724. }
  100725. /**
  100726. * Gets a string describing the action executed by the current optimization
  100727. * @returns description string
  100728. */
  100729. CustomOptimization.prototype.getDescription = function () {
  100730. if (this.onGetDescription) {
  100731. return this.onGetDescription();
  100732. }
  100733. return "Running user defined callback";
  100734. };
  100735. /**
  100736. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100737. * @param scene defines the current scene where to apply this optimization
  100738. * @param optimizer defines the current optimizer
  100739. * @returns true if everything that can be done was applied
  100740. */
  100741. CustomOptimization.prototype.apply = function (scene, optimizer) {
  100742. if (this.onApply) {
  100743. return this.onApply(scene, optimizer);
  100744. }
  100745. return true;
  100746. };
  100747. ;
  100748. return CustomOptimization;
  100749. }(SceneOptimization));
  100750. BABYLON.CustomOptimization = CustomOptimization;
  100751. /**
  100752. * Defines an optimization used to turn particles off
  100753. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100754. */
  100755. var ParticlesOptimization = /** @class */ (function (_super) {
  100756. __extends(ParticlesOptimization, _super);
  100757. function ParticlesOptimization() {
  100758. return _super !== null && _super.apply(this, arguments) || this;
  100759. }
  100760. /**
  100761. * Gets a string describing the action executed by the current optimization
  100762. * @return description string
  100763. */
  100764. ParticlesOptimization.prototype.getDescription = function () {
  100765. return "Turning particles on/off";
  100766. };
  100767. /**
  100768. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100769. * @param scene defines the current scene where to apply this optimization
  100770. * @param optimizer defines the current optimizer
  100771. * @returns true if everything that can be done was applied
  100772. */
  100773. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  100774. scene.particlesEnabled = optimizer.isInImprovementMode;
  100775. return true;
  100776. };
  100777. ;
  100778. return ParticlesOptimization;
  100779. }(SceneOptimization));
  100780. BABYLON.ParticlesOptimization = ParticlesOptimization;
  100781. /**
  100782. * Defines an optimization used to turn render targets off
  100783. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100784. */
  100785. var RenderTargetsOptimization = /** @class */ (function (_super) {
  100786. __extends(RenderTargetsOptimization, _super);
  100787. function RenderTargetsOptimization() {
  100788. return _super !== null && _super.apply(this, arguments) || this;
  100789. }
  100790. /**
  100791. * Gets a string describing the action executed by the current optimization
  100792. * @return description string
  100793. */
  100794. RenderTargetsOptimization.prototype.getDescription = function () {
  100795. return "Turning render targets off";
  100796. };
  100797. /**
  100798. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100799. * @param scene defines the current scene where to apply this optimization
  100800. * @param optimizer defines the current optimizer
  100801. * @returns true if everything that can be done was applied
  100802. */
  100803. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  100804. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  100805. return true;
  100806. };
  100807. ;
  100808. return RenderTargetsOptimization;
  100809. }(SceneOptimization));
  100810. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  100811. /**
  100812. * Defines an optimization used to merge meshes with compatible materials
  100813. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100814. */
  100815. var MergeMeshesOptimization = /** @class */ (function (_super) {
  100816. __extends(MergeMeshesOptimization, _super);
  100817. function MergeMeshesOptimization() {
  100818. var _this = _super !== null && _super.apply(this, arguments) || this;
  100819. _this._canBeMerged = function (abstractMesh) {
  100820. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  100821. return false;
  100822. }
  100823. var mesh = abstractMesh;
  100824. if (mesh.isDisposed()) {
  100825. return false;
  100826. }
  100827. if (!mesh.isVisible || !mesh.isEnabled()) {
  100828. return false;
  100829. }
  100830. if (mesh.instances.length > 0) {
  100831. return false;
  100832. }
  100833. if (mesh.skeleton || mesh.hasLODLevels) {
  100834. return false;
  100835. }
  100836. return true;
  100837. };
  100838. return _this;
  100839. }
  100840. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  100841. /**
  100842. * Gets or sets a boolean which defines if optimization octree has to be updated
  100843. */
  100844. get: function () {
  100845. return MergeMeshesOptimization._UpdateSelectionTree;
  100846. },
  100847. /**
  100848. * Gets or sets a boolean which defines if optimization octree has to be updated
  100849. */
  100850. set: function (value) {
  100851. MergeMeshesOptimization._UpdateSelectionTree = value;
  100852. },
  100853. enumerable: true,
  100854. configurable: true
  100855. });
  100856. /**
  100857. * Gets a string describing the action executed by the current optimization
  100858. * @return description string
  100859. */
  100860. MergeMeshesOptimization.prototype.getDescription = function () {
  100861. return "Merging similar meshes together";
  100862. };
  100863. /**
  100864. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100865. * @param scene defines the current scene where to apply this optimization
  100866. * @param optimizer defines the current optimizer
  100867. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  100868. * @returns true if everything that can be done was applied
  100869. */
  100870. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  100871. var globalPool = scene.meshes.slice(0);
  100872. var globalLength = globalPool.length;
  100873. for (var index = 0; index < globalLength; index++) {
  100874. var currentPool = new Array();
  100875. var current = globalPool[index];
  100876. // Checks
  100877. if (!this._canBeMerged(current)) {
  100878. continue;
  100879. }
  100880. currentPool.push(current);
  100881. // Find compatible meshes
  100882. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  100883. var otherMesh = globalPool[subIndex];
  100884. if (!this._canBeMerged(otherMesh)) {
  100885. continue;
  100886. }
  100887. if (otherMesh.material !== current.material) {
  100888. continue;
  100889. }
  100890. if (otherMesh.checkCollisions !== current.checkCollisions) {
  100891. continue;
  100892. }
  100893. currentPool.push(otherMesh);
  100894. globalLength--;
  100895. globalPool.splice(subIndex, 1);
  100896. subIndex--;
  100897. }
  100898. if (currentPool.length < 2) {
  100899. continue;
  100900. }
  100901. // Merge meshes
  100902. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  100903. }
  100904. // Call the octree system optimization if it is defined.
  100905. var sceneAsAny = scene;
  100906. if (sceneAsAny.createOrUpdateSelectionOctree) {
  100907. if (updateSelectionTree != undefined) {
  100908. if (updateSelectionTree) {
  100909. sceneAsAny.createOrUpdateSelectionOctree();
  100910. }
  100911. }
  100912. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  100913. sceneAsAny.createOrUpdateSelectionOctree();
  100914. }
  100915. }
  100916. return true;
  100917. };
  100918. ;
  100919. MergeMeshesOptimization._UpdateSelectionTree = false;
  100920. return MergeMeshesOptimization;
  100921. }(SceneOptimization));
  100922. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  100923. /**
  100924. * Defines a list of options used by SceneOptimizer
  100925. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100926. */
  100927. var SceneOptimizerOptions = /** @class */ (function () {
  100928. /**
  100929. * Creates a new list of options used by SceneOptimizer
  100930. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  100931. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  100932. */
  100933. function SceneOptimizerOptions(
  100934. /**
  100935. * Defines the target frame rate to reach (60 by default)
  100936. */
  100937. targetFrameRate,
  100938. /**
  100939. * Defines the interval between two checkes (2000ms by default)
  100940. */
  100941. trackerDuration) {
  100942. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  100943. if (trackerDuration === void 0) { trackerDuration = 2000; }
  100944. this.targetFrameRate = targetFrameRate;
  100945. this.trackerDuration = trackerDuration;
  100946. /**
  100947. * Gets the list of optimizations to apply
  100948. */
  100949. this.optimizations = new Array();
  100950. }
  100951. /**
  100952. * Add a new optimization
  100953. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  100954. * @returns the current SceneOptimizerOptions
  100955. */
  100956. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  100957. this.optimizations.push(optimization);
  100958. return this;
  100959. };
  100960. /**
  100961. * Add a new custom optimization
  100962. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  100963. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  100964. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100965. * @returns the current SceneOptimizerOptions
  100966. */
  100967. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  100968. if (priority === void 0) { priority = 0; }
  100969. var optimization = new CustomOptimization(priority);
  100970. optimization.onApply = onApply;
  100971. optimization.onGetDescription = onGetDescription;
  100972. this.optimizations.push(optimization);
  100973. return this;
  100974. };
  100975. /**
  100976. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  100977. * @param targetFrameRate defines the target frame rate (60 by default)
  100978. * @returns a SceneOptimizerOptions object
  100979. */
  100980. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  100981. var result = new SceneOptimizerOptions(targetFrameRate);
  100982. var priority = 0;
  100983. result.addOptimization(new MergeMeshesOptimization(priority));
  100984. result.addOptimization(new ShadowsOptimization(priority));
  100985. result.addOptimization(new LensFlaresOptimization(priority));
  100986. // Next priority
  100987. priority++;
  100988. result.addOptimization(new PostProcessesOptimization(priority));
  100989. result.addOptimization(new ParticlesOptimization(priority));
  100990. // Next priority
  100991. priority++;
  100992. result.addOptimization(new TextureOptimization(priority, 1024));
  100993. return result;
  100994. };
  100995. /**
  100996. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  100997. * @param targetFrameRate defines the target frame rate (60 by default)
  100998. * @returns a SceneOptimizerOptions object
  100999. */
  101000. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  101001. var result = new SceneOptimizerOptions(targetFrameRate);
  101002. var priority = 0;
  101003. result.addOptimization(new MergeMeshesOptimization(priority));
  101004. result.addOptimization(new ShadowsOptimization(priority));
  101005. result.addOptimization(new LensFlaresOptimization(priority));
  101006. // Next priority
  101007. priority++;
  101008. result.addOptimization(new PostProcessesOptimization(priority));
  101009. result.addOptimization(new ParticlesOptimization(priority));
  101010. // Next priority
  101011. priority++;
  101012. result.addOptimization(new TextureOptimization(priority, 512));
  101013. // Next priority
  101014. priority++;
  101015. result.addOptimization(new RenderTargetsOptimization(priority));
  101016. // Next priority
  101017. priority++;
  101018. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  101019. return result;
  101020. };
  101021. /**
  101022. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  101023. * @param targetFrameRate defines the target frame rate (60 by default)
  101024. * @returns a SceneOptimizerOptions object
  101025. */
  101026. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  101027. var result = new SceneOptimizerOptions(targetFrameRate);
  101028. var priority = 0;
  101029. result.addOptimization(new MergeMeshesOptimization(priority));
  101030. result.addOptimization(new ShadowsOptimization(priority));
  101031. result.addOptimization(new LensFlaresOptimization(priority));
  101032. // Next priority
  101033. priority++;
  101034. result.addOptimization(new PostProcessesOptimization(priority));
  101035. result.addOptimization(new ParticlesOptimization(priority));
  101036. // Next priority
  101037. priority++;
  101038. result.addOptimization(new TextureOptimization(priority, 256));
  101039. // Next priority
  101040. priority++;
  101041. result.addOptimization(new RenderTargetsOptimization(priority));
  101042. // Next priority
  101043. priority++;
  101044. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  101045. return result;
  101046. };
  101047. return SceneOptimizerOptions;
  101048. }());
  101049. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  101050. /**
  101051. * Class used to run optimizations in order to reach a target frame rate
  101052. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101053. */
  101054. var SceneOptimizer = /** @class */ (function () {
  101055. /**
  101056. * Creates a new SceneOptimizer
  101057. * @param scene defines the scene to work on
  101058. * @param options defines the options to use with the SceneOptimizer
  101059. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  101060. * @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)
  101061. */
  101062. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  101063. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  101064. if (improvementMode === void 0) { improvementMode = false; }
  101065. var _this = this;
  101066. this._isRunning = false;
  101067. this._currentPriorityLevel = 0;
  101068. this._targetFrameRate = 60;
  101069. this._trackerDuration = 2000;
  101070. this._currentFrameRate = 0;
  101071. this._improvementMode = false;
  101072. /**
  101073. * Defines an observable called when the optimizer reaches the target frame rate
  101074. */
  101075. this.onSuccessObservable = new BABYLON.Observable();
  101076. /**
  101077. * Defines an observable called when the optimizer enables an optimization
  101078. */
  101079. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  101080. /**
  101081. * Defines an observable called when the optimizer is not able to reach the target frame rate
  101082. */
  101083. this.onFailureObservable = new BABYLON.Observable();
  101084. if (!options) {
  101085. this._options = new SceneOptimizerOptions();
  101086. }
  101087. else {
  101088. this._options = options;
  101089. }
  101090. if (this._options.targetFrameRate) {
  101091. this._targetFrameRate = this._options.targetFrameRate;
  101092. }
  101093. if (this._options.trackerDuration) {
  101094. this._trackerDuration = this._options.trackerDuration;
  101095. }
  101096. if (autoGeneratePriorities) {
  101097. var priority = 0;
  101098. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  101099. var optim = _a[_i];
  101100. optim.priority = priority++;
  101101. }
  101102. }
  101103. this._improvementMode = improvementMode;
  101104. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101105. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  101106. _this._sceneDisposeObserver = null;
  101107. _this.dispose();
  101108. });
  101109. }
  101110. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  101111. /**
  101112. * Gets a boolean indicating if the optimizer is in improvement mode
  101113. */
  101114. get: function () {
  101115. return this._improvementMode;
  101116. },
  101117. enumerable: true,
  101118. configurable: true
  101119. });
  101120. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  101121. /**
  101122. * Gets the current priority level (0 at start)
  101123. */
  101124. get: function () {
  101125. return this._currentPriorityLevel;
  101126. },
  101127. enumerable: true,
  101128. configurable: true
  101129. });
  101130. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  101131. /**
  101132. * Gets the current frame rate checked by the SceneOptimizer
  101133. */
  101134. get: function () {
  101135. return this._currentFrameRate;
  101136. },
  101137. enumerable: true,
  101138. configurable: true
  101139. });
  101140. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  101141. /**
  101142. * Gets or sets the current target frame rate (60 by default)
  101143. */
  101144. get: function () {
  101145. return this._targetFrameRate;
  101146. },
  101147. /**
  101148. * Gets or sets the current target frame rate (60 by default)
  101149. */
  101150. set: function (value) {
  101151. this._targetFrameRate = value;
  101152. },
  101153. enumerable: true,
  101154. configurable: true
  101155. });
  101156. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  101157. /**
  101158. * Gets or sets the current interval between two checks (every 2000ms by default)
  101159. */
  101160. get: function () {
  101161. return this._trackerDuration;
  101162. },
  101163. /**
  101164. * Gets or sets the current interval between two checks (every 2000ms by default)
  101165. */
  101166. set: function (value) {
  101167. this._trackerDuration = value;
  101168. },
  101169. enumerable: true,
  101170. configurable: true
  101171. });
  101172. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  101173. /**
  101174. * Gets the list of active optimizations
  101175. */
  101176. get: function () {
  101177. return this._options.optimizations;
  101178. },
  101179. enumerable: true,
  101180. configurable: true
  101181. });
  101182. /**
  101183. * Stops the current optimizer
  101184. */
  101185. SceneOptimizer.prototype.stop = function () {
  101186. this._isRunning = false;
  101187. };
  101188. /**
  101189. * Reset the optimizer to initial step (current priority level = 0)
  101190. */
  101191. SceneOptimizer.prototype.reset = function () {
  101192. this._currentPriorityLevel = 0;
  101193. };
  101194. /**
  101195. * Start the optimizer. By default it will try to reach a specific framerate
  101196. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  101197. */
  101198. SceneOptimizer.prototype.start = function () {
  101199. var _this = this;
  101200. if (this._isRunning) {
  101201. return;
  101202. }
  101203. this._isRunning = true;
  101204. // Let's wait for the scene to be ready before running our check
  101205. this._scene.executeWhenReady(function () {
  101206. setTimeout(function () {
  101207. _this._checkCurrentState();
  101208. }, _this._trackerDuration);
  101209. });
  101210. };
  101211. SceneOptimizer.prototype._checkCurrentState = function () {
  101212. var _this = this;
  101213. if (!this._isRunning) {
  101214. return;
  101215. }
  101216. var scene = this._scene;
  101217. var options = this._options;
  101218. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  101219. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  101220. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  101221. this._isRunning = false;
  101222. this.onSuccessObservable.notifyObservers(this);
  101223. return;
  101224. }
  101225. // Apply current level of optimizations
  101226. var allDone = true;
  101227. var noOptimizationApplied = true;
  101228. for (var index = 0; index < options.optimizations.length; index++) {
  101229. var optimization = options.optimizations[index];
  101230. if (optimization.priority === this._currentPriorityLevel) {
  101231. noOptimizationApplied = false;
  101232. allDone = allDone && optimization.apply(scene, this);
  101233. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  101234. }
  101235. }
  101236. // If no optimization was applied, this is a failure :(
  101237. if (noOptimizationApplied) {
  101238. this._isRunning = false;
  101239. this.onFailureObservable.notifyObservers(this);
  101240. return;
  101241. }
  101242. // If all optimizations were done, move to next level
  101243. if (allDone) {
  101244. this._currentPriorityLevel++;
  101245. }
  101246. // Let's the system running for a specific amount of time before checking FPS
  101247. scene.executeWhenReady(function () {
  101248. setTimeout(function () {
  101249. _this._checkCurrentState();
  101250. }, _this._trackerDuration);
  101251. });
  101252. };
  101253. /**
  101254. * Release all resources
  101255. */
  101256. SceneOptimizer.prototype.dispose = function () {
  101257. this.stop();
  101258. this.onSuccessObservable.clear();
  101259. this.onFailureObservable.clear();
  101260. this.onNewOptimizationAppliedObservable.clear();
  101261. if (this._sceneDisposeObserver) {
  101262. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  101263. }
  101264. };
  101265. /**
  101266. * Helper function to create a SceneOptimizer with one single line of code
  101267. * @param scene defines the scene to work on
  101268. * @param options defines the options to use with the SceneOptimizer
  101269. * @param onSuccess defines a callback to call on success
  101270. * @param onFailure defines a callback to call on failure
  101271. * @returns the new SceneOptimizer object
  101272. */
  101273. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  101274. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  101275. if (onSuccess) {
  101276. optimizer.onSuccessObservable.add(function () {
  101277. onSuccess();
  101278. });
  101279. }
  101280. if (onFailure) {
  101281. optimizer.onFailureObservable.add(function () {
  101282. onFailure();
  101283. });
  101284. }
  101285. optimizer.start();
  101286. return optimizer;
  101287. };
  101288. return SceneOptimizer;
  101289. }());
  101290. BABYLON.SceneOptimizer = SceneOptimizer;
  101291. })(BABYLON || (BABYLON = {}));
  101292. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  101293. var BABYLON;
  101294. (function (BABYLON) {
  101295. /**
  101296. * Gets the outline renderer associated with the scene
  101297. * @returns a OutlineRenderer
  101298. */
  101299. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  101300. if (!this._outlineRenderer) {
  101301. this._outlineRenderer = new OutlineRenderer(this);
  101302. }
  101303. return this._outlineRenderer;
  101304. };
  101305. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  101306. get: function () {
  101307. return this._renderOutline;
  101308. },
  101309. set: function (value) {
  101310. if (value) {
  101311. // Lazy Load the component.
  101312. this.getScene().getOutlineRenderer();
  101313. }
  101314. this._renderOutline = value;
  101315. },
  101316. enumerable: true,
  101317. configurable: true
  101318. });
  101319. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  101320. get: function () {
  101321. return this._renderOverlay;
  101322. },
  101323. set: function (value) {
  101324. if (value) {
  101325. // Lazy Load the component.
  101326. this.getScene().getOutlineRenderer();
  101327. }
  101328. this._renderOverlay = value;
  101329. },
  101330. enumerable: true,
  101331. configurable: true
  101332. });
  101333. /**
  101334. * This class is responsible to draw bothe outline/overlay of meshes.
  101335. * It should not be used directly but through the available method on mesh.
  101336. */
  101337. var OutlineRenderer = /** @class */ (function () {
  101338. /**
  101339. * Instantiates a new outline renderer. (There could be only one per scene).
  101340. * @param scene Defines the scene it belongs to
  101341. */
  101342. function OutlineRenderer(scene) {
  101343. /**
  101344. * The name of the component. Each component must have a unique name.
  101345. */
  101346. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  101347. /**
  101348. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  101349. */
  101350. this.zOffset = 1;
  101351. this.scene = scene;
  101352. this._engine = scene.getEngine();
  101353. this.scene._addComponent(this);
  101354. }
  101355. /**
  101356. * Register the component to one instance of a scene.
  101357. */
  101358. OutlineRenderer.prototype.register = function () {
  101359. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  101360. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  101361. };
  101362. /**
  101363. * Rebuilds the elements related to this component in case of
  101364. * context lost for instance.
  101365. */
  101366. OutlineRenderer.prototype.rebuild = function () {
  101367. // Nothing to do here.
  101368. };
  101369. /**
  101370. * Disposes the component and the associated ressources.
  101371. */
  101372. OutlineRenderer.prototype.dispose = function () {
  101373. // Nothing to do here.
  101374. };
  101375. /**
  101376. * Renders the outline in the canvas.
  101377. * @param subMesh Defines the sumesh to render
  101378. * @param batch Defines the batch of meshes in case of instances
  101379. * @param useOverlay Defines if the rendering is for the overlay or the outline
  101380. */
  101381. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  101382. var _this = this;
  101383. if (useOverlay === void 0) { useOverlay = false; }
  101384. var scene = this.scene;
  101385. var engine = scene.getEngine();
  101386. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  101387. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  101388. return;
  101389. }
  101390. var mesh = subMesh.getRenderingMesh();
  101391. var material = subMesh.getMaterial();
  101392. if (!material || !scene.activeCamera) {
  101393. return;
  101394. }
  101395. engine.enableEffect(this._effect);
  101396. // Logarithmic depth
  101397. if (material.useLogarithmicDepth) {
  101398. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  101399. }
  101400. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  101401. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  101402. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  101403. // Bones
  101404. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  101405. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  101406. }
  101407. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  101408. // Alpha test
  101409. if (material && material.needAlphaTesting()) {
  101410. var alphaTexture = material.getAlphaTestTexture();
  101411. if (alphaTexture) {
  101412. this._effect.setTexture("diffuseSampler", alphaTexture);
  101413. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  101414. }
  101415. }
  101416. engine.setZOffset(-this.zOffset);
  101417. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  101418. engine.setZOffset(0);
  101419. };
  101420. /**
  101421. * Returns whether or not the outline renderer is ready for a given submesh.
  101422. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  101423. * @param subMesh Defines the submesh to check readyness for
  101424. * @param useInstances Defines wheter wee are trying to render instances or not
  101425. * @returns true if ready otherwise false
  101426. */
  101427. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  101428. var defines = [];
  101429. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  101430. var mesh = subMesh.getMesh();
  101431. var material = subMesh.getMaterial();
  101432. if (material) {
  101433. // Alpha test
  101434. if (material.needAlphaTesting()) {
  101435. defines.push("#define ALPHATEST");
  101436. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101437. attribs.push(BABYLON.VertexBuffer.UVKind);
  101438. defines.push("#define UV1");
  101439. }
  101440. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  101441. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101442. defines.push("#define UV2");
  101443. }
  101444. }
  101445. //Logarithmic depth
  101446. if (material.useLogarithmicDepth) {
  101447. defines.push("#define LOGARITHMICDEPTH");
  101448. }
  101449. }
  101450. // Bones
  101451. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  101452. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  101453. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  101454. if (mesh.numBoneInfluencers > 4) {
  101455. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  101456. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  101457. }
  101458. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  101459. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  101460. }
  101461. else {
  101462. defines.push("#define NUM_BONE_INFLUENCERS 0");
  101463. }
  101464. // Instances
  101465. if (useInstances) {
  101466. defines.push("#define INSTANCES");
  101467. attribs.push("world0");
  101468. attribs.push("world1");
  101469. attribs.push("world2");
  101470. attribs.push("world3");
  101471. }
  101472. // Get correct effect
  101473. var join = defines.join("\n");
  101474. if (this._cachedDefines !== join) {
  101475. this._cachedDefines = join;
  101476. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  101477. }
  101478. return this._effect.isReady();
  101479. };
  101480. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  101481. // Outline - step 1
  101482. this._savedDepthWrite = this._engine.getDepthWrite();
  101483. if (mesh.renderOutline) {
  101484. this._engine.setDepthWrite(false);
  101485. this.render(subMesh, batch);
  101486. this._engine.setDepthWrite(this._savedDepthWrite);
  101487. }
  101488. };
  101489. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  101490. // Outline - step 2
  101491. if (mesh.renderOutline && this._savedDepthWrite) {
  101492. this._engine.setDepthWrite(true);
  101493. this._engine.setColorWrite(false);
  101494. this.render(subMesh, batch);
  101495. this._engine.setColorWrite(true);
  101496. }
  101497. // Overlay
  101498. if (mesh.renderOverlay) {
  101499. var currentMode = this._engine.getAlphaMode();
  101500. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101501. this.render(subMesh, batch, true);
  101502. this._engine.setAlphaMode(currentMode);
  101503. }
  101504. };
  101505. return OutlineRenderer;
  101506. }());
  101507. BABYLON.OutlineRenderer = OutlineRenderer;
  101508. })(BABYLON || (BABYLON = {}));
  101509. //# sourceMappingURL=babylon.outlineRenderer.js.map
  101510. var BABYLON;
  101511. (function (BABYLON) {
  101512. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  101513. if (this._edgesRenderer) {
  101514. this._edgesRenderer.dispose();
  101515. this._edgesRenderer = null;
  101516. }
  101517. return this;
  101518. };
  101519. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101520. if (epsilon === void 0) { epsilon = 0.95; }
  101521. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101522. this.disableEdgesRendering();
  101523. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101524. return this;
  101525. };
  101526. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  101527. get: function () {
  101528. return this._edgesRenderer;
  101529. },
  101530. enumerable: true,
  101531. configurable: true
  101532. });
  101533. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101534. if (epsilon === void 0) { epsilon = 0.95; }
  101535. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101536. this.disableEdgesRendering();
  101537. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101538. return this;
  101539. };
  101540. /**
  101541. * FaceAdjacencies Helper class to generate edges
  101542. */
  101543. var FaceAdjacencies = /** @class */ (function () {
  101544. function FaceAdjacencies() {
  101545. this.edges = new Array();
  101546. this.edgesConnectedCount = 0;
  101547. }
  101548. return FaceAdjacencies;
  101549. }());
  101550. /**
  101551. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  101552. */
  101553. var EdgesRenderer = /** @class */ (function () {
  101554. /**
  101555. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  101556. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  101557. * @param source Mesh used to create edges
  101558. * @param epsilon sum of angles in adjacency to check for edge
  101559. * @param checkVerticesInsteadOfIndices
  101560. * @param generateEdgesLines - should generate Lines or only prepare resources.
  101561. */
  101562. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  101563. if (epsilon === void 0) { epsilon = 0.95; }
  101564. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101565. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  101566. var _this = this;
  101567. this.edgesWidthScalerForOrthographic = 1000.0;
  101568. this.edgesWidthScalerForPerspective = 50.0;
  101569. this._linesPositions = new Array();
  101570. this._linesNormals = new Array();
  101571. this._linesIndices = new Array();
  101572. this._buffers = {};
  101573. this._checkVerticesInsteadOfIndices = false;
  101574. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  101575. this.isEnabled = true;
  101576. this._source = source;
  101577. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  101578. this._epsilon = epsilon;
  101579. this._prepareRessources();
  101580. if (generateEdgesLines) {
  101581. this._generateEdgesLines();
  101582. }
  101583. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  101584. _this._rebuild();
  101585. });
  101586. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  101587. _this.dispose();
  101588. });
  101589. }
  101590. EdgesRenderer.prototype._prepareRessources = function () {
  101591. if (this._lineShader) {
  101592. return;
  101593. }
  101594. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  101595. attributes: ["position", "normal"],
  101596. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  101597. });
  101598. this._lineShader.disableDepthWrite = true;
  101599. this._lineShader.backFaceCulling = false;
  101600. };
  101601. /** @hidden */
  101602. EdgesRenderer.prototype._rebuild = function () {
  101603. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101604. if (buffer) {
  101605. buffer._rebuild();
  101606. }
  101607. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101608. if (buffer) {
  101609. buffer._rebuild();
  101610. }
  101611. var scene = this._source.getScene();
  101612. var engine = scene.getEngine();
  101613. this._ib = engine.createIndexBuffer(this._linesIndices);
  101614. };
  101615. /**
  101616. * Releases the required resources for the edges renderer
  101617. */
  101618. EdgesRenderer.prototype.dispose = function () {
  101619. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  101620. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  101621. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101622. if (buffer) {
  101623. buffer.dispose();
  101624. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  101625. }
  101626. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101627. if (buffer) {
  101628. buffer.dispose();
  101629. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  101630. }
  101631. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  101632. this._lineShader.dispose();
  101633. };
  101634. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  101635. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  101636. return 0;
  101637. }
  101638. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  101639. return 1;
  101640. }
  101641. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  101642. return 2;
  101643. }
  101644. return -1;
  101645. };
  101646. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  101647. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  101648. return 0;
  101649. }
  101650. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  101651. return 1;
  101652. }
  101653. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  101654. return 2;
  101655. }
  101656. return -1;
  101657. };
  101658. /**
  101659. * Checks if the pair of p0 and p1 is en edge
  101660. * @param faceIndex
  101661. * @param edge
  101662. * @param faceNormals
  101663. * @param p0
  101664. * @param p1
  101665. * @private
  101666. */
  101667. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101668. var needToCreateLine;
  101669. if (edge === undefined) {
  101670. needToCreateLine = true;
  101671. }
  101672. else {
  101673. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  101674. needToCreateLine = dotProduct < this._epsilon;
  101675. }
  101676. if (needToCreateLine) {
  101677. var offset = this._linesPositions.length / 3;
  101678. var normal = p0.subtract(p1);
  101679. normal.normalize();
  101680. // Positions
  101681. this._linesPositions.push(p0.x);
  101682. this._linesPositions.push(p0.y);
  101683. this._linesPositions.push(p0.z);
  101684. this._linesPositions.push(p0.x);
  101685. this._linesPositions.push(p0.y);
  101686. this._linesPositions.push(p0.z);
  101687. this._linesPositions.push(p1.x);
  101688. this._linesPositions.push(p1.y);
  101689. this._linesPositions.push(p1.z);
  101690. this._linesPositions.push(p1.x);
  101691. this._linesPositions.push(p1.y);
  101692. this._linesPositions.push(p1.z);
  101693. // Normals
  101694. this._linesNormals.push(p1.x);
  101695. this._linesNormals.push(p1.y);
  101696. this._linesNormals.push(p1.z);
  101697. this._linesNormals.push(-1);
  101698. this._linesNormals.push(p1.x);
  101699. this._linesNormals.push(p1.y);
  101700. this._linesNormals.push(p1.z);
  101701. this._linesNormals.push(1);
  101702. this._linesNormals.push(p0.x);
  101703. this._linesNormals.push(p0.y);
  101704. this._linesNormals.push(p0.z);
  101705. this._linesNormals.push(-1);
  101706. this._linesNormals.push(p0.x);
  101707. this._linesNormals.push(p0.y);
  101708. this._linesNormals.push(p0.z);
  101709. this._linesNormals.push(1);
  101710. // Indices
  101711. this._linesIndices.push(offset);
  101712. this._linesIndices.push(offset + 1);
  101713. this._linesIndices.push(offset + 2);
  101714. this._linesIndices.push(offset);
  101715. this._linesIndices.push(offset + 2);
  101716. this._linesIndices.push(offset + 3);
  101717. }
  101718. };
  101719. /**
  101720. * Generates lines edges from adjacencjes
  101721. * @private
  101722. */
  101723. EdgesRenderer.prototype._generateEdgesLines = function () {
  101724. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101725. var indices = this._source.getIndices();
  101726. if (!indices || !positions) {
  101727. return;
  101728. }
  101729. // First let's find adjacencies
  101730. var adjacencies = new Array();
  101731. var faceNormals = new Array();
  101732. var index;
  101733. var faceAdjacencies;
  101734. // Prepare faces
  101735. for (index = 0; index < indices.length; index += 3) {
  101736. faceAdjacencies = new FaceAdjacencies();
  101737. var p0Index = indices[index];
  101738. var p1Index = indices[index + 1];
  101739. var p2Index = indices[index + 2];
  101740. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  101741. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  101742. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  101743. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  101744. faceNormal.normalize();
  101745. faceNormals.push(faceNormal);
  101746. adjacencies.push(faceAdjacencies);
  101747. }
  101748. // Scan
  101749. for (index = 0; index < adjacencies.length; index++) {
  101750. faceAdjacencies = adjacencies[index];
  101751. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  101752. var otherFaceAdjacencies = adjacencies[otherIndex];
  101753. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  101754. break;
  101755. }
  101756. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  101757. continue;
  101758. }
  101759. var otherP0 = indices[otherIndex * 3];
  101760. var otherP1 = indices[otherIndex * 3 + 1];
  101761. var otherP2 = indices[otherIndex * 3 + 2];
  101762. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  101763. var otherEdgeIndex = 0;
  101764. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  101765. continue;
  101766. }
  101767. switch (edgeIndex) {
  101768. case 0:
  101769. if (this._checkVerticesInsteadOfIndices) {
  101770. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101771. }
  101772. else {
  101773. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  101774. }
  101775. break;
  101776. case 1:
  101777. if (this._checkVerticesInsteadOfIndices) {
  101778. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101779. }
  101780. else {
  101781. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  101782. }
  101783. break;
  101784. case 2:
  101785. if (this._checkVerticesInsteadOfIndices) {
  101786. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101787. }
  101788. else {
  101789. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  101790. }
  101791. break;
  101792. }
  101793. if (otherEdgeIndex === -1) {
  101794. continue;
  101795. }
  101796. faceAdjacencies.edges[edgeIndex] = otherIndex;
  101797. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  101798. faceAdjacencies.edgesConnectedCount++;
  101799. otherFaceAdjacencies.edgesConnectedCount++;
  101800. if (faceAdjacencies.edgesConnectedCount === 3) {
  101801. break;
  101802. }
  101803. }
  101804. }
  101805. }
  101806. // Create lines
  101807. for (index = 0; index < adjacencies.length; index++) {
  101808. // 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
  101809. var current = adjacencies[index];
  101810. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101811. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  101812. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  101813. }
  101814. // Merge into a single mesh
  101815. var engine = this._source.getScene().getEngine();
  101816. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101817. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101818. this._ib = engine.createIndexBuffer(this._linesIndices);
  101819. this._indicesCount = this._linesIndices.length;
  101820. };
  101821. /**
  101822. * Checks wether or not the edges renderer is ready to render.
  101823. * @return true if ready, otherwise false.
  101824. */
  101825. EdgesRenderer.prototype.isReady = function () {
  101826. return this._lineShader.isReady();
  101827. };
  101828. /**
  101829. * Renders the edges of the attached mesh,
  101830. */
  101831. EdgesRenderer.prototype.render = function () {
  101832. var scene = this._source.getScene();
  101833. if (!this.isReady() || !scene.activeCamera) {
  101834. return;
  101835. }
  101836. var engine = scene.getEngine();
  101837. this._lineShader._preBind();
  101838. if (this._source.edgesColor.a !== 1) {
  101839. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101840. }
  101841. else {
  101842. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  101843. }
  101844. // VBOs
  101845. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  101846. scene.resetCachedMaterial();
  101847. this._lineShader.setColor4("color", this._source.edgesColor);
  101848. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  101849. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  101850. }
  101851. else {
  101852. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  101853. }
  101854. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  101855. this._lineShader.bind(this._source.getWorldMatrix());
  101856. // Draw order
  101857. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  101858. this._lineShader.unbind();
  101859. };
  101860. return EdgesRenderer;
  101861. }());
  101862. BABYLON.EdgesRenderer = EdgesRenderer;
  101863. })(BABYLON || (BABYLON = {}));
  101864. //# sourceMappingURL=babylon.edgesRenderer.js.map
  101865. var BABYLON;
  101866. (function (BABYLON) {
  101867. /**
  101868. * FaceAdjacencies Helper class to generate edges
  101869. */
  101870. var FaceAdjacencies = /** @class */ (function () {
  101871. function FaceAdjacencies() {
  101872. this.edges = new Array();
  101873. this.edgesConnectedCount = 0;
  101874. }
  101875. return FaceAdjacencies;
  101876. }());
  101877. /**
  101878. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  101879. */
  101880. var LineEdgesRenderer = /** @class */ (function (_super) {
  101881. __extends(LineEdgesRenderer, _super);
  101882. /**
  101883. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  101884. * @param source LineMesh used to generate edges
  101885. * @param epsilon not important (specified angle for edge detection)
  101886. * @param checkVerticesInsteadOfIndices not important for LineMesh
  101887. */
  101888. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  101889. if (epsilon === void 0) { epsilon = 0.95; }
  101890. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101891. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  101892. _this._generateEdgesLines();
  101893. return _this;
  101894. }
  101895. /**
  101896. * Always create the edge since its a line so only important things are p0 and p1
  101897. * @param faceIndex not important for LineMesh
  101898. * @param edge not important for LineMesh
  101899. * @param faceNormals not important for LineMesh
  101900. * @param p0 beginnig of line
  101901. * @param p1 end of line
  101902. */
  101903. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101904. var offset = this._linesPositions.length / 3;
  101905. var normal = p0.subtract(p1);
  101906. normal.normalize();
  101907. // Positions
  101908. this._linesPositions.push(p0.x);
  101909. this._linesPositions.push(p0.y);
  101910. this._linesPositions.push(p0.z);
  101911. this._linesPositions.push(p0.x);
  101912. this._linesPositions.push(p0.y);
  101913. this._linesPositions.push(p0.z);
  101914. this._linesPositions.push(p1.x);
  101915. this._linesPositions.push(p1.y);
  101916. this._linesPositions.push(p1.z);
  101917. this._linesPositions.push(p1.x);
  101918. this._linesPositions.push(p1.y);
  101919. this._linesPositions.push(p1.z);
  101920. // Normals
  101921. this._linesNormals.push(p1.x);
  101922. this._linesNormals.push(p1.y);
  101923. this._linesNormals.push(p1.z);
  101924. this._linesNormals.push(-1);
  101925. this._linesNormals.push(p1.x);
  101926. this._linesNormals.push(p1.y);
  101927. this._linesNormals.push(p1.z);
  101928. this._linesNormals.push(1);
  101929. this._linesNormals.push(p0.x);
  101930. this._linesNormals.push(p0.y);
  101931. this._linesNormals.push(p0.z);
  101932. this._linesNormals.push(-1);
  101933. this._linesNormals.push(p0.x);
  101934. this._linesNormals.push(p0.y);
  101935. this._linesNormals.push(p0.z);
  101936. this._linesNormals.push(1);
  101937. // Indices
  101938. this._linesIndices.push(offset);
  101939. this._linesIndices.push(offset + 1);
  101940. this._linesIndices.push(offset + 2);
  101941. this._linesIndices.push(offset);
  101942. this._linesIndices.push(offset + 2);
  101943. this._linesIndices.push(offset + 3);
  101944. };
  101945. /**
  101946. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  101947. */
  101948. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  101949. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101950. var indices = this._source.getIndices();
  101951. if (!indices || !positions) {
  101952. return;
  101953. }
  101954. // First let's find adjacencies
  101955. var adjacencies = new Array();
  101956. var faceNormals = new Array();
  101957. var index;
  101958. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  101959. var currentAdjecancy = new FaceAdjacencies();
  101960. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  101961. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  101962. adjacencies.push(currentAdjecancy);
  101963. }
  101964. // Create lines
  101965. for (index = 0; index < adjacencies.length; index++) {
  101966. // 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
  101967. var current = adjacencies[index];
  101968. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101969. }
  101970. // Merge into a single mesh
  101971. var engine = this._source.getScene().getEngine();
  101972. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101973. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101974. this._ib = engine.createIndexBuffer(this._linesIndices);
  101975. this._indicesCount = this._linesIndices.length;
  101976. };
  101977. return LineEdgesRenderer;
  101978. }(BABYLON.EdgesRenderer));
  101979. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  101980. })(BABYLON || (BABYLON = {}));
  101981. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  101982. var BABYLON;
  101983. (function (BABYLON) {
  101984. // Adds the parser to the scene parsers.
  101985. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  101986. if (parsedData.effectLayers) {
  101987. if (!container.effectLayers) {
  101988. container.effectLayers = new Array();
  101989. }
  101990. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  101991. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  101992. container.effectLayers.push(effectLayer);
  101993. }
  101994. }
  101995. });
  101996. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  101997. var index = this.effectLayers.indexOf(toRemove);
  101998. if (index !== -1) {
  101999. this.effectLayers.splice(index, 1);
  102000. }
  102001. return index;
  102002. };
  102003. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  102004. this.effectLayers.push(newEffectLayer);
  102005. };
  102006. /**
  102007. * Defines the layer scene component responsible to manage any effect layers
  102008. * in a given scene.
  102009. */
  102010. var EffectLayerSceneComponent = /** @class */ (function () {
  102011. /**
  102012. * Creates a new instance of the component for the given scene
  102013. * @param scene Defines the scene to register the component in
  102014. */
  102015. function EffectLayerSceneComponent(scene) {
  102016. /**
  102017. * The component name helpfull to identify the component in the list of scene components.
  102018. */
  102019. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  102020. this._renderEffects = false;
  102021. this._needStencil = false;
  102022. this._previousStencilState = false;
  102023. this.scene = scene;
  102024. this._engine = scene.getEngine();
  102025. scene.effectLayers = new Array();
  102026. }
  102027. /**
  102028. * Registers the component in a given scene
  102029. */
  102030. EffectLayerSceneComponent.prototype.register = function () {
  102031. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  102032. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  102033. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  102034. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  102035. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  102036. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  102037. };
  102038. /**
  102039. * Rebuilds the elements related to this component in case of
  102040. * context lost for instance.
  102041. */
  102042. EffectLayerSceneComponent.prototype.rebuild = function () {
  102043. var layers = this.scene.effectLayers;
  102044. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102045. var effectLayer = layers_1[_i];
  102046. effectLayer._rebuild();
  102047. }
  102048. };
  102049. /**
  102050. * Serializes the component data to the specified json object
  102051. * @param serializationObject The object to serialize to
  102052. */
  102053. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  102054. // Effect layers
  102055. serializationObject.effectLayers = [];
  102056. var layers = this.scene.effectLayers;
  102057. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102058. var effectLayer = layers_2[_i];
  102059. if (effectLayer.serialize) {
  102060. serializationObject.effectLayers.push(effectLayer.serialize());
  102061. }
  102062. }
  102063. };
  102064. /**
  102065. * Adds all the element from the container to the scene
  102066. * @param container the container holding the elements
  102067. */
  102068. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  102069. var _this = this;
  102070. if (!container.effectLayers) {
  102071. return;
  102072. }
  102073. container.effectLayers.forEach(function (o) {
  102074. _this.scene.addEffectLayer(o);
  102075. });
  102076. };
  102077. /**
  102078. * Removes all the elements in the container from the scene
  102079. * @param container contains the elements to remove
  102080. */
  102081. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  102082. var _this = this;
  102083. if (!container.effectLayers) {
  102084. return;
  102085. }
  102086. container.effectLayers.forEach(function (o) {
  102087. _this.scene.removeEffectLayer(o);
  102088. });
  102089. };
  102090. /**
  102091. * Disposes the component and the associated ressources.
  102092. */
  102093. EffectLayerSceneComponent.prototype.dispose = function () {
  102094. var layers = this.scene.effectLayers;
  102095. while (layers.length) {
  102096. layers[0].dispose();
  102097. }
  102098. };
  102099. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  102100. var layers = this.scene.effectLayers;
  102101. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  102102. var layer = layers_3[_i];
  102103. if (!layer.hasMesh(mesh)) {
  102104. continue;
  102105. }
  102106. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  102107. var subMesh = _b[_a];
  102108. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  102109. return false;
  102110. }
  102111. }
  102112. }
  102113. return true;
  102114. };
  102115. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  102116. this._renderEffects = false;
  102117. this._needStencil = false;
  102118. var layers = this.scene.effectLayers;
  102119. if (layers && layers.length > 0) {
  102120. this._previousStencilState = this._engine.getStencilBuffer();
  102121. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  102122. var effectLayer = layers_4[_i];
  102123. if (effectLayer.shouldRender() &&
  102124. (!effectLayer.camera ||
  102125. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  102126. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  102127. this._renderEffects = true;
  102128. this._needStencil = this._needStencil || effectLayer.needStencil();
  102129. var renderTarget = effectLayer._mainTexture;
  102130. if (renderTarget._shouldRender()) {
  102131. this.scene.incrementRenderId();
  102132. renderTarget.render(false, false);
  102133. }
  102134. }
  102135. }
  102136. this.scene.incrementRenderId();
  102137. }
  102138. };
  102139. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  102140. // Activate effect Layer stencil
  102141. if (this._needStencil) {
  102142. this._engine.setStencilBuffer(true);
  102143. }
  102144. };
  102145. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  102146. // Restore effect Layer stencil
  102147. if (this._needStencil) {
  102148. this._engine.setStencilBuffer(this._previousStencilState);
  102149. }
  102150. };
  102151. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  102152. if (this._renderEffects) {
  102153. this._engine.setDepthBuffer(false);
  102154. var layers = this.scene.effectLayers;
  102155. for (var i = 0; i < layers.length; i++) {
  102156. var effectLayer = layers[i];
  102157. if (effectLayer.renderingGroupId === renderingGroupId) {
  102158. if (effectLayer.shouldRender()) {
  102159. effectLayer.render();
  102160. }
  102161. }
  102162. }
  102163. this._engine.setDepthBuffer(true);
  102164. }
  102165. };
  102166. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  102167. if (this._renderEffects) {
  102168. this._draw(-1);
  102169. }
  102170. };
  102171. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  102172. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  102173. this._draw(index);
  102174. }
  102175. };
  102176. return EffectLayerSceneComponent;
  102177. }());
  102178. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  102179. })(BABYLON || (BABYLON = {}));
  102180. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  102181. var __assign = (this && this.__assign) || function () {
  102182. __assign = Object.assign || function(t) {
  102183. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102184. s = arguments[i];
  102185. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102186. t[p] = s[p];
  102187. }
  102188. return t;
  102189. };
  102190. return __assign.apply(this, arguments);
  102191. };
  102192. var BABYLON;
  102193. (function (BABYLON) {
  102194. /**
  102195. * The effect layer Helps adding post process effect blended with the main pass.
  102196. *
  102197. * This can be for instance use to generate glow or higlight effects on the scene.
  102198. *
  102199. * The effect layer class can not be used directly and is intented to inherited from to be
  102200. * customized per effects.
  102201. */
  102202. var EffectLayer = /** @class */ (function () {
  102203. /**
  102204. * Instantiates a new effect Layer and references it in the scene.
  102205. * @param name The name of the layer
  102206. * @param scene The scene to use the layer in
  102207. */
  102208. function EffectLayer(
  102209. /** The Friendly of the effect in the scene */
  102210. name, scene) {
  102211. this._vertexBuffers = {};
  102212. this._maxSize = 0;
  102213. this._mainTextureDesiredSize = { width: 0, height: 0 };
  102214. this._shouldRender = true;
  102215. this._postProcesses = [];
  102216. this._textures = [];
  102217. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  102218. /**
  102219. * The clear color of the texture used to generate the glow map.
  102220. */
  102221. this.neutralColor = new BABYLON.Color4();
  102222. /**
  102223. * Specifies wether the highlight layer is enabled or not.
  102224. */
  102225. this.isEnabled = true;
  102226. /**
  102227. * An event triggered when the effect layer has been disposed.
  102228. */
  102229. this.onDisposeObservable = new BABYLON.Observable();
  102230. /**
  102231. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  102232. */
  102233. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  102234. /**
  102235. * An event triggered when the generated texture is being merged in the scene.
  102236. */
  102237. this.onBeforeComposeObservable = new BABYLON.Observable();
  102238. /**
  102239. * An event triggered when the generated texture has been merged in the scene.
  102240. */
  102241. this.onAfterComposeObservable = new BABYLON.Observable();
  102242. /**
  102243. * An event triggered when the efffect layer changes its size.
  102244. */
  102245. this.onSizeChangedObservable = new BABYLON.Observable();
  102246. this.name = name;
  102247. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102248. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  102249. if (!component) {
  102250. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  102251. this._scene._addComponent(component);
  102252. }
  102253. this._engine = this._scene.getEngine();
  102254. this._maxSize = this._engine.getCaps().maxTextureSize;
  102255. this._scene.effectLayers.push(this);
  102256. // Generate Buffers
  102257. this._generateIndexBuffer();
  102258. this._genrateVertexBuffer();
  102259. }
  102260. Object.defineProperty(EffectLayer.prototype, "camera", {
  102261. /**
  102262. * Gets the camera attached to the layer.
  102263. */
  102264. get: function () {
  102265. return this._effectLayerOptions.camera;
  102266. },
  102267. enumerable: true,
  102268. configurable: true
  102269. });
  102270. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  102271. /**
  102272. * Gets the rendering group id the layer should render in.
  102273. */
  102274. get: function () {
  102275. return this._effectLayerOptions.renderingGroupId;
  102276. },
  102277. enumerable: true,
  102278. configurable: true
  102279. });
  102280. /**
  102281. * Initializes the effect layer with the required options.
  102282. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  102283. */
  102284. EffectLayer.prototype._init = function (options) {
  102285. // Adapt options
  102286. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  102287. this._setMainTextureSize();
  102288. this._createMainTexture();
  102289. this._createTextureAndPostProcesses();
  102290. this._mergeEffect = this._createMergeEffect();
  102291. };
  102292. /**
  102293. * Generates the index buffer of the full screen quad blending to the main canvas.
  102294. */
  102295. EffectLayer.prototype._generateIndexBuffer = function () {
  102296. // Indices
  102297. var indices = [];
  102298. indices.push(0);
  102299. indices.push(1);
  102300. indices.push(2);
  102301. indices.push(0);
  102302. indices.push(2);
  102303. indices.push(3);
  102304. this._indexBuffer = this._engine.createIndexBuffer(indices);
  102305. };
  102306. /**
  102307. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  102308. */
  102309. EffectLayer.prototype._genrateVertexBuffer = function () {
  102310. // VBO
  102311. var vertices = [];
  102312. vertices.push(1, 1);
  102313. vertices.push(-1, 1);
  102314. vertices.push(-1, -1);
  102315. vertices.push(1, -1);
  102316. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  102317. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  102318. };
  102319. /**
  102320. * Sets the main texture desired size which is the closest power of two
  102321. * of the engine canvas size.
  102322. */
  102323. EffectLayer.prototype._setMainTextureSize = function () {
  102324. if (this._effectLayerOptions.mainTextureFixedSize) {
  102325. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  102326. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  102327. }
  102328. else {
  102329. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  102330. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  102331. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  102332. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  102333. }
  102334. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  102335. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  102336. };
  102337. /**
  102338. * Creates the main texture for the effect layer.
  102339. */
  102340. EffectLayer.prototype._createMainTexture = function () {
  102341. var _this = this;
  102342. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  102343. width: this._mainTextureDesiredSize.width,
  102344. height: this._mainTextureDesiredSize.height
  102345. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  102346. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  102347. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102348. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102349. this._mainTexture.anisotropicFilteringLevel = 1;
  102350. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102351. this._mainTexture.renderParticles = false;
  102352. this._mainTexture.renderList = null;
  102353. this._mainTexture.ignoreCameraViewport = true;
  102354. // Custom render function
  102355. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  102356. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  102357. var index;
  102358. var engine = _this._scene.getEngine();
  102359. if (depthOnlySubMeshes.length) {
  102360. engine.setColorWrite(false);
  102361. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  102362. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  102363. }
  102364. engine.setColorWrite(true);
  102365. }
  102366. for (index = 0; index < opaqueSubMeshes.length; index++) {
  102367. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  102368. }
  102369. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  102370. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  102371. }
  102372. for (index = 0; index < transparentSubMeshes.length; index++) {
  102373. _this._renderSubMesh(transparentSubMeshes.data[index]);
  102374. }
  102375. };
  102376. this._mainTexture.onClearObservable.add(function (engine) {
  102377. engine.clear(_this.neutralColor, true, true, true);
  102378. });
  102379. };
  102380. /**
  102381. * Checks for the readiness of the element composing the layer.
  102382. * @param subMesh the mesh to check for
  102383. * @param useInstances specify wether or not to use instances to render the mesh
  102384. * @param emissiveTexture the associated emissive texture used to generate the glow
  102385. * @return true if ready otherwise, false
  102386. */
  102387. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  102388. var material = subMesh.getMaterial();
  102389. if (!material) {
  102390. return false;
  102391. }
  102392. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  102393. return false;
  102394. }
  102395. var defines = [];
  102396. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102397. var mesh = subMesh.getMesh();
  102398. var uv1 = false;
  102399. var uv2 = false;
  102400. // Alpha test
  102401. if (material && material.needAlphaTesting()) {
  102402. var alphaTexture = material.getAlphaTestTexture();
  102403. if (alphaTexture) {
  102404. defines.push("#define ALPHATEST");
  102405. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  102406. alphaTexture.coordinatesIndex === 1) {
  102407. defines.push("#define DIFFUSEUV2");
  102408. uv2 = true;
  102409. }
  102410. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  102411. defines.push("#define DIFFUSEUV1");
  102412. uv1 = true;
  102413. }
  102414. }
  102415. }
  102416. // Emissive
  102417. if (emissiveTexture) {
  102418. defines.push("#define EMISSIVE");
  102419. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  102420. emissiveTexture.coordinatesIndex === 1) {
  102421. defines.push("#define EMISSIVEUV2");
  102422. uv2 = true;
  102423. }
  102424. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  102425. defines.push("#define EMISSIVEUV1");
  102426. uv1 = true;
  102427. }
  102428. }
  102429. if (uv1) {
  102430. attribs.push(BABYLON.VertexBuffer.UVKind);
  102431. defines.push("#define UV1");
  102432. }
  102433. if (uv2) {
  102434. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102435. defines.push("#define UV2");
  102436. }
  102437. // Bones
  102438. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  102439. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  102440. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  102441. if (mesh.numBoneInfluencers > 4) {
  102442. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  102443. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  102444. }
  102445. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  102446. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  102447. }
  102448. else {
  102449. defines.push("#define NUM_BONE_INFLUENCERS 0");
  102450. }
  102451. // Morph targets
  102452. var manager = mesh.morphTargetManager;
  102453. var morphInfluencers = 0;
  102454. if (manager) {
  102455. if (manager.numInfluencers > 0) {
  102456. defines.push("#define MORPHTARGETS");
  102457. morphInfluencers = manager.numInfluencers;
  102458. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  102459. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  102460. }
  102461. }
  102462. // Instances
  102463. if (useInstances) {
  102464. defines.push("#define INSTANCES");
  102465. attribs.push("world0");
  102466. attribs.push("world1");
  102467. attribs.push("world2");
  102468. attribs.push("world3");
  102469. }
  102470. // Get correct effect
  102471. var join = defines.join("\n");
  102472. if (this._cachedDefines !== join) {
  102473. this._cachedDefines = join;
  102474. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  102475. }
  102476. return this._effectLayerMapGenerationEffect.isReady();
  102477. };
  102478. /**
  102479. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  102480. */
  102481. EffectLayer.prototype.render = function () {
  102482. var currentEffect = this._mergeEffect;
  102483. // Check
  102484. if (!currentEffect.isReady())
  102485. return;
  102486. for (var i = 0; i < this._postProcesses.length; i++) {
  102487. if (!this._postProcesses[i].isReady()) {
  102488. return;
  102489. }
  102490. }
  102491. var engine = this._scene.getEngine();
  102492. this.onBeforeComposeObservable.notifyObservers(this);
  102493. // Render
  102494. engine.enableEffect(currentEffect);
  102495. engine.setState(false);
  102496. // VBOs
  102497. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  102498. // Cache
  102499. var previousAlphaMode = engine.getAlphaMode();
  102500. // Go Blend.
  102501. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  102502. // Blends the map on the main canvas.
  102503. this._internalRender(currentEffect);
  102504. // Restore Alpha
  102505. engine.setAlphaMode(previousAlphaMode);
  102506. this.onAfterComposeObservable.notifyObservers(this);
  102507. // Handle size changes.
  102508. var size = this._mainTexture.getSize();
  102509. this._setMainTextureSize();
  102510. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  102511. // Recreate RTT and post processes on size change.
  102512. this.onSizeChangedObservable.notifyObservers(this);
  102513. this._disposeTextureAndPostProcesses();
  102514. this._createMainTexture();
  102515. this._createTextureAndPostProcesses();
  102516. }
  102517. };
  102518. /**
  102519. * Determine if a given mesh will be used in the current effect.
  102520. * @param mesh mesh to test
  102521. * @returns true if the mesh will be used
  102522. */
  102523. EffectLayer.prototype.hasMesh = function (mesh) {
  102524. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  102525. return true;
  102526. }
  102527. return false;
  102528. };
  102529. /**
  102530. * Returns true if the layer contains information to display, otherwise false.
  102531. * @returns true if the glow layer should be rendered
  102532. */
  102533. EffectLayer.prototype.shouldRender = function () {
  102534. return this.isEnabled && this._shouldRender;
  102535. };
  102536. /**
  102537. * Returns true if the mesh should render, otherwise false.
  102538. * @param mesh The mesh to render
  102539. * @returns true if it should render otherwise false
  102540. */
  102541. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  102542. return true;
  102543. };
  102544. /**
  102545. * Returns true if the mesh should render, otherwise false.
  102546. * @param mesh The mesh to render
  102547. * @returns true if it should render otherwise false
  102548. */
  102549. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  102550. return true;
  102551. };
  102552. /**
  102553. * Renders the submesh passed in parameter to the generation map.
  102554. */
  102555. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  102556. var _this = this;
  102557. if (!this.shouldRender()) {
  102558. return;
  102559. }
  102560. var material = subMesh.getMaterial();
  102561. var mesh = subMesh.getRenderingMesh();
  102562. var scene = this._scene;
  102563. var engine = scene.getEngine();
  102564. if (!material) {
  102565. return;
  102566. }
  102567. // Do not block in blend mode.
  102568. if (material.needAlphaBlendingForMesh(mesh)) {
  102569. return;
  102570. }
  102571. // Culling
  102572. engine.setState(material.backFaceCulling);
  102573. // Managing instances
  102574. var batch = mesh._getInstancesRenderList(subMesh._id);
  102575. if (batch.mustReturn) {
  102576. return;
  102577. }
  102578. // Early Exit per mesh
  102579. if (!this._shouldRenderMesh(mesh)) {
  102580. return;
  102581. }
  102582. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  102583. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  102584. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  102585. engine.enableEffect(this._effectLayerMapGenerationEffect);
  102586. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  102587. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  102588. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  102589. // Alpha test
  102590. if (material && material.needAlphaTesting()) {
  102591. var alphaTexture = material.getAlphaTestTexture();
  102592. if (alphaTexture) {
  102593. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  102594. var textureMatrix = alphaTexture.getTextureMatrix();
  102595. if (textureMatrix) {
  102596. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  102597. }
  102598. }
  102599. }
  102600. // Glow emissive only
  102601. if (this._emissiveTextureAndColor.texture) {
  102602. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  102603. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  102604. }
  102605. // Bones
  102606. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  102607. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  102608. }
  102609. // Morph targets
  102610. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  102611. // Draw
  102612. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  102613. }
  102614. else {
  102615. // Need to reset refresh rate of the main map
  102616. this._mainTexture.resetRefreshCounter();
  102617. }
  102618. };
  102619. /**
  102620. * Rebuild the required buffers.
  102621. * @hidden Internal use only.
  102622. */
  102623. EffectLayer.prototype._rebuild = function () {
  102624. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102625. if (vb) {
  102626. vb._rebuild();
  102627. }
  102628. this._generateIndexBuffer();
  102629. };
  102630. /**
  102631. * Dispose only the render target textures and post process.
  102632. */
  102633. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  102634. this._mainTexture.dispose();
  102635. for (var i = 0; i < this._postProcesses.length; i++) {
  102636. if (this._postProcesses[i]) {
  102637. this._postProcesses[i].dispose();
  102638. }
  102639. }
  102640. this._postProcesses = [];
  102641. for (var i = 0; i < this._textures.length; i++) {
  102642. if (this._textures[i]) {
  102643. this._textures[i].dispose();
  102644. }
  102645. }
  102646. this._textures = [];
  102647. };
  102648. /**
  102649. * Dispose the highlight layer and free resources.
  102650. */
  102651. EffectLayer.prototype.dispose = function () {
  102652. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102653. if (vertexBuffer) {
  102654. vertexBuffer.dispose();
  102655. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102656. }
  102657. if (this._indexBuffer) {
  102658. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102659. this._indexBuffer = null;
  102660. }
  102661. // Clean textures and post processes
  102662. this._disposeTextureAndPostProcesses();
  102663. // Remove from scene
  102664. var index = this._scene.effectLayers.indexOf(this, 0);
  102665. if (index > -1) {
  102666. this._scene.effectLayers.splice(index, 1);
  102667. }
  102668. // Callback
  102669. this.onDisposeObservable.notifyObservers(this);
  102670. this.onDisposeObservable.clear();
  102671. this.onBeforeRenderMainTextureObservable.clear();
  102672. this.onBeforeComposeObservable.clear();
  102673. this.onAfterComposeObservable.clear();
  102674. this.onSizeChangedObservable.clear();
  102675. };
  102676. /**
  102677. * Gets the class name of the effect layer
  102678. * @returns the string with the class name of the effect layer
  102679. */
  102680. EffectLayer.prototype.getClassName = function () {
  102681. return "EffectLayer";
  102682. };
  102683. /**
  102684. * Creates an effect layer from parsed effect layer data
  102685. * @param parsedEffectLayer defines effect layer data
  102686. * @param scene defines the current scene
  102687. * @param rootUrl defines the root URL containing the effect layer information
  102688. * @returns a parsed effect Layer
  102689. */
  102690. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  102691. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  102692. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  102693. };
  102694. __decorate([
  102695. BABYLON.serialize()
  102696. ], EffectLayer.prototype, "name", void 0);
  102697. __decorate([
  102698. BABYLON.serializeAsColor4()
  102699. ], EffectLayer.prototype, "neutralColor", void 0);
  102700. __decorate([
  102701. BABYLON.serialize()
  102702. ], EffectLayer.prototype, "isEnabled", void 0);
  102703. __decorate([
  102704. BABYLON.serializeAsCameraReference()
  102705. ], EffectLayer.prototype, "camera", null);
  102706. __decorate([
  102707. BABYLON.serialize()
  102708. ], EffectLayer.prototype, "renderingGroupId", null);
  102709. return EffectLayer;
  102710. }());
  102711. BABYLON.EffectLayer = EffectLayer;
  102712. })(BABYLON || (BABYLON = {}));
  102713. //# sourceMappingURL=babylon.effectLayer.js.map
  102714. var BABYLON;
  102715. (function (BABYLON) {
  102716. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  102717. for (var index = 0; index < this.effectLayers.length; index++) {
  102718. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  102719. return this.effectLayers[index];
  102720. }
  102721. }
  102722. return null;
  102723. };
  102724. /**
  102725. * Special Glow Blur post process only blurring the alpha channel
  102726. * It enforces keeping the most luminous color in the color channel.
  102727. */
  102728. var GlowBlurPostProcess = /** @class */ (function (_super) {
  102729. __extends(GlowBlurPostProcess, _super);
  102730. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  102731. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  102732. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  102733. _this.direction = direction;
  102734. _this.kernel = kernel;
  102735. _this.onApplyObservable.add(function (effect) {
  102736. effect.setFloat2("screenSize", _this.width, _this.height);
  102737. effect.setVector2("direction", _this.direction);
  102738. effect.setFloat("blurWidth", _this.kernel);
  102739. });
  102740. return _this;
  102741. }
  102742. return GlowBlurPostProcess;
  102743. }(BABYLON.PostProcess));
  102744. /**
  102745. * The highlight layer Helps adding a glow effect around a mesh.
  102746. *
  102747. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102748. * glowy meshes to your scene.
  102749. *
  102750. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  102751. */
  102752. var HighlightLayer = /** @class */ (function (_super) {
  102753. __extends(HighlightLayer, _super);
  102754. /**
  102755. * Instantiates a new highlight Layer and references it to the scene..
  102756. * @param name The name of the layer
  102757. * @param scene The scene to use the layer in
  102758. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  102759. */
  102760. function HighlightLayer(name, scene, options) {
  102761. var _this = _super.call(this, name, scene) || this;
  102762. _this.name = name;
  102763. /**
  102764. * Specifies whether or not the inner glow is ACTIVE in the layer.
  102765. */
  102766. _this.innerGlow = true;
  102767. /**
  102768. * Specifies whether or not the outer glow is ACTIVE in the layer.
  102769. */
  102770. _this.outerGlow = true;
  102771. /**
  102772. * An event triggered when the highlight layer is being blurred.
  102773. */
  102774. _this.onBeforeBlurObservable = new BABYLON.Observable();
  102775. /**
  102776. * An event triggered when the highlight layer has been blurred.
  102777. */
  102778. _this.onAfterBlurObservable = new BABYLON.Observable();
  102779. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  102780. _this._meshes = {};
  102781. _this._excludedMeshes = {};
  102782. _this.neutralColor = HighlightLayer.NeutralColor;
  102783. // Warn on stencil
  102784. if (!_this._engine.isStencilEnable) {
  102785. 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 }");
  102786. }
  102787. // Adapt options
  102788. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  102789. // Initialize the layer
  102790. _this._init({
  102791. alphaBlendingMode: _this._options.alphaBlendingMode,
  102792. camera: _this._options.camera,
  102793. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102794. mainTextureRatio: _this._options.mainTextureRatio,
  102795. renderingGroupId: _this._options.renderingGroupId
  102796. });
  102797. // Do not render as long as no meshes have been added
  102798. _this._shouldRender = false;
  102799. return _this;
  102800. }
  102801. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  102802. /**
  102803. * Gets the horizontal size of the blur.
  102804. */
  102805. get: function () {
  102806. return this._horizontalBlurPostprocess.kernel;
  102807. },
  102808. /**
  102809. * Specifies the horizontal size of the blur.
  102810. */
  102811. set: function (value) {
  102812. this._horizontalBlurPostprocess.kernel = value;
  102813. },
  102814. enumerable: true,
  102815. configurable: true
  102816. });
  102817. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  102818. /**
  102819. * Gets the vertical size of the blur.
  102820. */
  102821. get: function () {
  102822. return this._verticalBlurPostprocess.kernel;
  102823. },
  102824. /**
  102825. * Specifies the vertical size of the blur.
  102826. */
  102827. set: function (value) {
  102828. this._verticalBlurPostprocess.kernel = value;
  102829. },
  102830. enumerable: true,
  102831. configurable: true
  102832. });
  102833. /**
  102834. * Get the effect name of the layer.
  102835. * @return The effect name
  102836. */
  102837. HighlightLayer.prototype.getEffectName = function () {
  102838. return HighlightLayer.EffectName;
  102839. };
  102840. /**
  102841. * Create the merge effect. This is the shader use to blit the information back
  102842. * to the main canvas at the end of the scene rendering.
  102843. */
  102844. HighlightLayer.prototype._createMergeEffect = function () {
  102845. // Effect
  102846. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  102847. };
  102848. /**
  102849. * Creates the render target textures and post processes used in the highlight layer.
  102850. */
  102851. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  102852. var _this = this;
  102853. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  102854. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  102855. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102856. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102857. var textureType = 0;
  102858. if (this._engine.getCaps().textureHalfFloatRender) {
  102859. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102860. }
  102861. else {
  102862. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102863. }
  102864. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  102865. width: blurTextureWidth,
  102866. height: blurTextureHeight
  102867. }, this._scene, false, true, textureType);
  102868. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102869. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102870. this._blurTexture.anisotropicFilteringLevel = 16;
  102871. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  102872. this._blurTexture.renderParticles = false;
  102873. this._blurTexture.ignoreCameraViewport = true;
  102874. this._textures = [this._blurTexture];
  102875. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  102876. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102877. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  102878. effect.setTexture("textureSampler", _this._mainTexture);
  102879. });
  102880. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102881. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102882. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102883. });
  102884. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102885. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  102886. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102887. });
  102888. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102889. }
  102890. else {
  102891. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  102892. width: blurTextureWidth,
  102893. height: blurTextureHeight
  102894. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102895. this._horizontalBlurPostprocess.width = blurTextureWidth;
  102896. this._horizontalBlurPostprocess.height = blurTextureHeight;
  102897. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102898. effect.setTexture("textureSampler", _this._mainTexture);
  102899. });
  102900. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  102901. width: blurTextureWidth,
  102902. height: blurTextureHeight
  102903. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102904. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102905. }
  102906. this._mainTexture.onAfterUnbindObservable.add(function () {
  102907. _this.onBeforeBlurObservable.notifyObservers(_this);
  102908. var internalTexture = _this._blurTexture.getInternalTexture();
  102909. if (internalTexture) {
  102910. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  102911. }
  102912. _this.onAfterBlurObservable.notifyObservers(_this);
  102913. });
  102914. // Prevent autoClear.
  102915. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102916. };
  102917. /**
  102918. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102919. */
  102920. HighlightLayer.prototype.needStencil = function () {
  102921. return true;
  102922. };
  102923. /**
  102924. * Checks for the readiness of the element composing the layer.
  102925. * @param subMesh the mesh to check for
  102926. * @param useInstances specify wether or not to use instances to render the mesh
  102927. * @param emissiveTexture the associated emissive texture used to generate the glow
  102928. * @return true if ready otherwise, false
  102929. */
  102930. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  102931. var material = subMesh.getMaterial();
  102932. var mesh = subMesh.getRenderingMesh();
  102933. if (!material || !mesh || !this._meshes) {
  102934. return false;
  102935. }
  102936. var emissiveTexture = null;
  102937. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102938. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102939. emissiveTexture = material.emissiveTexture;
  102940. }
  102941. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102942. };
  102943. /**
  102944. * Implementation specific of rendering the generating effect on the main canvas.
  102945. * @param effect The effect used to render through
  102946. */
  102947. HighlightLayer.prototype._internalRender = function (effect) {
  102948. // Texture
  102949. effect.setTexture("textureSampler", this._blurTexture);
  102950. // Cache
  102951. var engine = this._engine;
  102952. var previousStencilBuffer = engine.getStencilBuffer();
  102953. var previousStencilFunction = engine.getStencilFunction();
  102954. var previousStencilMask = engine.getStencilMask();
  102955. var previousStencilOperationPass = engine.getStencilOperationPass();
  102956. var previousStencilOperationFail = engine.getStencilOperationFail();
  102957. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  102958. var previousStencilReference = engine.getStencilFunctionReference();
  102959. // Stencil operations
  102960. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  102961. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  102962. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  102963. // Draw order
  102964. engine.setStencilMask(0x00);
  102965. engine.setStencilBuffer(true);
  102966. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  102967. // 2 passes inner outer
  102968. if (this.outerGlow) {
  102969. effect.setFloat("offset", 0);
  102970. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  102971. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102972. }
  102973. if (this.innerGlow) {
  102974. effect.setFloat("offset", 1);
  102975. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  102976. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102977. }
  102978. // Restore Cache
  102979. engine.setStencilFunction(previousStencilFunction);
  102980. engine.setStencilMask(previousStencilMask);
  102981. engine.setStencilBuffer(previousStencilBuffer);
  102982. engine.setStencilOperationPass(previousStencilOperationPass);
  102983. engine.setStencilOperationFail(previousStencilOperationFail);
  102984. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  102985. engine.setStencilFunctionReference(previousStencilReference);
  102986. };
  102987. /**
  102988. * Returns true if the layer contains information to display, otherwise false.
  102989. */
  102990. HighlightLayer.prototype.shouldRender = function () {
  102991. if (_super.prototype.shouldRender.call(this)) {
  102992. return this._meshes ? true : false;
  102993. }
  102994. return false;
  102995. };
  102996. /**
  102997. * Returns true if the mesh should render, otherwise false.
  102998. * @param mesh The mesh to render
  102999. * @returns true if it should render otherwise false
  103000. */
  103001. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  103002. // Excluded Mesh
  103003. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  103004. return false;
  103005. }
  103006. ;
  103007. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103008. return false;
  103009. }
  103010. return true;
  103011. };
  103012. /**
  103013. * Sets the required values for both the emissive texture and and the main color.
  103014. */
  103015. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  103016. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  103017. if (highlightLayerMesh) {
  103018. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  103019. }
  103020. else {
  103021. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  103022. }
  103023. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  103024. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  103025. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  103026. }
  103027. else {
  103028. this._emissiveTextureAndColor.texture = null;
  103029. }
  103030. };
  103031. /**
  103032. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  103033. * @param mesh The mesh to exclude from the highlight layer
  103034. */
  103035. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  103036. if (!this._excludedMeshes) {
  103037. return;
  103038. }
  103039. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  103040. if (!meshExcluded) {
  103041. this._excludedMeshes[mesh.uniqueId] = {
  103042. mesh: mesh,
  103043. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  103044. mesh.getEngine().setStencilBuffer(false);
  103045. }),
  103046. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  103047. mesh.getEngine().setStencilBuffer(true);
  103048. }),
  103049. };
  103050. }
  103051. };
  103052. /**
  103053. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  103054. * @param mesh The mesh to highlight
  103055. */
  103056. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  103057. if (!this._excludedMeshes) {
  103058. return;
  103059. }
  103060. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  103061. if (meshExcluded) {
  103062. if (meshExcluded.beforeRender) {
  103063. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  103064. }
  103065. if (meshExcluded.afterRender) {
  103066. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  103067. }
  103068. }
  103069. this._excludedMeshes[mesh.uniqueId] = null;
  103070. };
  103071. /**
  103072. * Determine if a given mesh will be highlighted by the current HighlightLayer
  103073. * @param mesh mesh to test
  103074. * @returns true if the mesh will be highlighted by the current HighlightLayer
  103075. */
  103076. HighlightLayer.prototype.hasMesh = function (mesh) {
  103077. if (!this._meshes) {
  103078. return false;
  103079. }
  103080. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103081. return false;
  103082. }
  103083. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  103084. };
  103085. /**
  103086. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  103087. * @param mesh The mesh to highlight
  103088. * @param color The color of the highlight
  103089. * @param glowEmissiveOnly Extract the glow from the emissive texture
  103090. */
  103091. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  103092. var _this = this;
  103093. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  103094. if (!this._meshes) {
  103095. return;
  103096. }
  103097. var meshHighlight = this._meshes[mesh.uniqueId];
  103098. if (meshHighlight) {
  103099. meshHighlight.color = color;
  103100. }
  103101. else {
  103102. this._meshes[mesh.uniqueId] = {
  103103. mesh: mesh,
  103104. color: color,
  103105. // Lambda required for capture due to Observable this context
  103106. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  103107. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  103108. _this._defaultStencilReference(mesh);
  103109. }
  103110. else {
  103111. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  103112. }
  103113. }),
  103114. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  103115. glowEmissiveOnly: glowEmissiveOnly
  103116. };
  103117. mesh.onDisposeObservable.add(function () {
  103118. _this._disposeMesh(mesh);
  103119. });
  103120. }
  103121. this._shouldRender = true;
  103122. };
  103123. /**
  103124. * Remove a mesh from the highlight layer in order to make it stop glowing.
  103125. * @param mesh The mesh to highlight
  103126. */
  103127. HighlightLayer.prototype.removeMesh = function (mesh) {
  103128. if (!this._meshes) {
  103129. return;
  103130. }
  103131. var meshHighlight = this._meshes[mesh.uniqueId];
  103132. if (meshHighlight) {
  103133. if (meshHighlight.observerHighlight) {
  103134. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  103135. }
  103136. if (meshHighlight.observerDefault) {
  103137. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  103138. }
  103139. delete this._meshes[mesh.uniqueId];
  103140. }
  103141. this._shouldRender = false;
  103142. for (var meshHighlightToCheck in this._meshes) {
  103143. if (this._meshes[meshHighlightToCheck]) {
  103144. this._shouldRender = true;
  103145. break;
  103146. }
  103147. }
  103148. };
  103149. /**
  103150. * Force the stencil to the normal expected value for none glowing parts
  103151. */
  103152. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  103153. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  103154. };
  103155. /**
  103156. * Free any resources and references associated to a mesh.
  103157. * Internal use
  103158. * @param mesh The mesh to free.
  103159. * @hidden
  103160. */
  103161. HighlightLayer.prototype._disposeMesh = function (mesh) {
  103162. this.removeMesh(mesh);
  103163. this.removeExcludedMesh(mesh);
  103164. };
  103165. /**
  103166. * Dispose the highlight layer and free resources.
  103167. */
  103168. HighlightLayer.prototype.dispose = function () {
  103169. if (this._meshes) {
  103170. // Clean mesh references
  103171. for (var id in this._meshes) {
  103172. var meshHighlight = this._meshes[id];
  103173. if (meshHighlight && meshHighlight.mesh) {
  103174. if (meshHighlight.observerHighlight) {
  103175. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  103176. }
  103177. if (meshHighlight.observerDefault) {
  103178. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  103179. }
  103180. }
  103181. }
  103182. this._meshes = null;
  103183. }
  103184. if (this._excludedMeshes) {
  103185. for (var id in this._excludedMeshes) {
  103186. var meshHighlight = this._excludedMeshes[id];
  103187. if (meshHighlight) {
  103188. if (meshHighlight.beforeRender) {
  103189. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  103190. }
  103191. if (meshHighlight.afterRender) {
  103192. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  103193. }
  103194. }
  103195. }
  103196. this._excludedMeshes = null;
  103197. }
  103198. _super.prototype.dispose.call(this);
  103199. };
  103200. /**
  103201. * Gets the class name of the effect layer
  103202. * @returns the string with the class name of the effect layer
  103203. */
  103204. HighlightLayer.prototype.getClassName = function () {
  103205. return "HighlightLayer";
  103206. };
  103207. /**
  103208. * Serializes this Highlight layer
  103209. * @returns a serialized Highlight layer object
  103210. */
  103211. HighlightLayer.prototype.serialize = function () {
  103212. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103213. serializationObject.customType = "BABYLON.HighlightLayer";
  103214. // Highlighted meshes
  103215. serializationObject.meshes = [];
  103216. if (this._meshes) {
  103217. for (var m in this._meshes) {
  103218. var mesh = this._meshes[m];
  103219. if (mesh) {
  103220. serializationObject.meshes.push({
  103221. glowEmissiveOnly: mesh.glowEmissiveOnly,
  103222. color: mesh.color.asArray(),
  103223. meshId: mesh.mesh.id
  103224. });
  103225. }
  103226. }
  103227. }
  103228. // Excluded meshes
  103229. serializationObject.excludedMeshes = [];
  103230. if (this._excludedMeshes) {
  103231. for (var e in this._excludedMeshes) {
  103232. var excludedMesh = this._excludedMeshes[e];
  103233. if (excludedMesh) {
  103234. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  103235. }
  103236. }
  103237. }
  103238. return serializationObject;
  103239. };
  103240. /**
  103241. * Creates a Highlight layer from parsed Highlight layer data
  103242. * @param parsedHightlightLayer defines the Highlight layer data
  103243. * @param scene defines the current scene
  103244. * @param rootUrl defines the root URL containing the Highlight layer information
  103245. * @returns a parsed Highlight layer
  103246. */
  103247. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  103248. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  103249. var index;
  103250. // Excluded meshes
  103251. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  103252. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  103253. if (mesh) {
  103254. hl.addExcludedMesh(mesh);
  103255. }
  103256. }
  103257. // Included meshes
  103258. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  103259. var highlightedMesh = parsedHightlightLayer.meshes[index];
  103260. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  103261. if (mesh) {
  103262. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  103263. }
  103264. }
  103265. return hl;
  103266. };
  103267. /**
  103268. * Effect Name of the highlight layer.
  103269. */
  103270. HighlightLayer.EffectName = "HighlightLayer";
  103271. /**
  103272. * The neutral color used during the preparation of the glow effect.
  103273. * This is black by default as the blend operation is a blend operation.
  103274. */
  103275. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  103276. /**
  103277. * Stencil value used for glowing meshes.
  103278. */
  103279. HighlightLayer.GlowingMeshStencilReference = 0x02;
  103280. /**
  103281. * Stencil value used for the other meshes in the scene.
  103282. */
  103283. HighlightLayer.NormalMeshStencilReference = 0x01;
  103284. __decorate([
  103285. BABYLON.serialize()
  103286. ], HighlightLayer.prototype, "innerGlow", void 0);
  103287. __decorate([
  103288. BABYLON.serialize()
  103289. ], HighlightLayer.prototype, "outerGlow", void 0);
  103290. __decorate([
  103291. BABYLON.serialize()
  103292. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  103293. __decorate([
  103294. BABYLON.serialize()
  103295. ], HighlightLayer.prototype, "blurVerticalSize", null);
  103296. __decorate([
  103297. BABYLON.serialize("options")
  103298. ], HighlightLayer.prototype, "_options", void 0);
  103299. return HighlightLayer;
  103300. }(BABYLON.EffectLayer));
  103301. BABYLON.HighlightLayer = HighlightLayer;
  103302. })(BABYLON || (BABYLON = {}));
  103303. //# sourceMappingURL=babylon.highlightLayer.js.map
  103304. var BABYLON;
  103305. (function (BABYLON) {
  103306. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  103307. for (var index = 0; index < this.effectLayers.length; index++) {
  103308. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  103309. return this.effectLayers[index];
  103310. }
  103311. }
  103312. return null;
  103313. };
  103314. /**
  103315. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  103316. *
  103317. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  103318. * glowy meshes to your scene.
  103319. *
  103320. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  103321. */
  103322. var GlowLayer = /** @class */ (function (_super) {
  103323. __extends(GlowLayer, _super);
  103324. /**
  103325. * Instantiates a new glow Layer and references it to the scene.
  103326. * @param name The name of the layer
  103327. * @param scene The scene to use the layer in
  103328. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  103329. */
  103330. function GlowLayer(name, scene, options) {
  103331. var _this = _super.call(this, name, scene) || this;
  103332. _this._intensity = 1.0;
  103333. _this._includedOnlyMeshes = [];
  103334. _this._excludedMeshes = [];
  103335. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  103336. // Adapt options
  103337. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  103338. // Initialize the layer
  103339. _this._init({
  103340. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  103341. camera: _this._options.camera,
  103342. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  103343. mainTextureRatio: _this._options.mainTextureRatio,
  103344. renderingGroupId: _this._options.renderingGroupId
  103345. });
  103346. return _this;
  103347. }
  103348. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  103349. /**
  103350. * Gets the kernel size of the blur.
  103351. */
  103352. get: function () {
  103353. return this._horizontalBlurPostprocess1.kernel;
  103354. },
  103355. /**
  103356. * Sets the kernel size of the blur.
  103357. */
  103358. set: function (value) {
  103359. this._horizontalBlurPostprocess1.kernel = value;
  103360. this._verticalBlurPostprocess1.kernel = value;
  103361. this._horizontalBlurPostprocess2.kernel = value;
  103362. this._verticalBlurPostprocess2.kernel = value;
  103363. },
  103364. enumerable: true,
  103365. configurable: true
  103366. });
  103367. Object.defineProperty(GlowLayer.prototype, "intensity", {
  103368. /**
  103369. * Gets the glow intensity.
  103370. */
  103371. get: function () {
  103372. return this._intensity;
  103373. },
  103374. /**
  103375. * Sets the glow intensity.
  103376. */
  103377. set: function (value) {
  103378. this._intensity = value;
  103379. },
  103380. enumerable: true,
  103381. configurable: true
  103382. });
  103383. /**
  103384. * Get the effect name of the layer.
  103385. * @return The effect name
  103386. */
  103387. GlowLayer.prototype.getEffectName = function () {
  103388. return GlowLayer.EffectName;
  103389. };
  103390. /**
  103391. * Create the merge effect. This is the shader use to blit the information back
  103392. * to the main canvas at the end of the scene rendering.
  103393. */
  103394. GlowLayer.prototype._createMergeEffect = function () {
  103395. // Effect
  103396. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  103397. };
  103398. /**
  103399. * Creates the render target textures and post processes used in the glow layer.
  103400. */
  103401. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  103402. var _this = this;
  103403. var blurTextureWidth = this._mainTextureDesiredSize.width;
  103404. var blurTextureHeight = this._mainTextureDesiredSize.height;
  103405. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  103406. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  103407. var textureType = 0;
  103408. if (this._engine.getCaps().textureHalfFloatRender) {
  103409. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  103410. }
  103411. else {
  103412. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  103413. }
  103414. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  103415. width: blurTextureWidth,
  103416. height: blurTextureHeight
  103417. }, this._scene, false, true, textureType);
  103418. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103419. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103420. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103421. this._blurTexture1.renderParticles = false;
  103422. this._blurTexture1.ignoreCameraViewport = true;
  103423. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  103424. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  103425. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  103426. width: blurTextureWidth2,
  103427. height: blurTextureHeight2
  103428. }, this._scene, false, true, textureType);
  103429. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103430. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103431. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103432. this._blurTexture2.renderParticles = false;
  103433. this._blurTexture2.ignoreCameraViewport = true;
  103434. this._textures = [this._blurTexture1, this._blurTexture2];
  103435. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  103436. width: blurTextureWidth,
  103437. height: blurTextureHeight
  103438. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103439. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  103440. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  103441. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  103442. effect.setTexture("textureSampler", _this._mainTexture);
  103443. });
  103444. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  103445. width: blurTextureWidth,
  103446. height: blurTextureHeight
  103447. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103448. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  103449. width: blurTextureWidth2,
  103450. height: blurTextureHeight2
  103451. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103452. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  103453. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  103454. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  103455. effect.setTexture("textureSampler", _this._blurTexture1);
  103456. });
  103457. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  103458. width: blurTextureWidth2,
  103459. height: blurTextureHeight2
  103460. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103461. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  103462. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  103463. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  103464. this._mainTexture.samples = this._options.mainTextureSamples;
  103465. this._mainTexture.onAfterUnbindObservable.add(function () {
  103466. var internalTexture = _this._blurTexture1.getInternalTexture();
  103467. if (internalTexture) {
  103468. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  103469. internalTexture = _this._blurTexture2.getInternalTexture();
  103470. if (internalTexture) {
  103471. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  103472. }
  103473. }
  103474. });
  103475. // Prevent autoClear.
  103476. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  103477. };
  103478. /**
  103479. * Checks for the readiness of the element composing the layer.
  103480. * @param subMesh the mesh to check for
  103481. * @param useInstances specify wether or not to use instances to render the mesh
  103482. * @param emissiveTexture the associated emissive texture used to generate the glow
  103483. * @return true if ready otherwise, false
  103484. */
  103485. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  103486. var material = subMesh.getMaterial();
  103487. var mesh = subMesh.getRenderingMesh();
  103488. if (!material || !mesh) {
  103489. return false;
  103490. }
  103491. var emissiveTexture = material.emissiveTexture;
  103492. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  103493. };
  103494. /**
  103495. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  103496. */
  103497. GlowLayer.prototype.needStencil = function () {
  103498. return false;
  103499. };
  103500. /**
  103501. * Implementation specific of rendering the generating effect on the main canvas.
  103502. * @param effect The effect used to render through
  103503. */
  103504. GlowLayer.prototype._internalRender = function (effect) {
  103505. // Texture
  103506. effect.setTexture("textureSampler", this._blurTexture1);
  103507. effect.setTexture("textureSampler2", this._blurTexture2);
  103508. effect.setFloat("offset", this._intensity);
  103509. // Cache
  103510. var engine = this._engine;
  103511. var previousStencilBuffer = engine.getStencilBuffer();
  103512. // Draw order
  103513. engine.setStencilBuffer(false);
  103514. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103515. // Draw order
  103516. engine.setStencilBuffer(previousStencilBuffer);
  103517. };
  103518. /**
  103519. * Sets the required values for both the emissive texture and and the main color.
  103520. */
  103521. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  103522. var textureLevel = 1.0;
  103523. if (this.customEmissiveTextureSelector) {
  103524. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  103525. }
  103526. else {
  103527. if (material) {
  103528. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  103529. if (this._emissiveTextureAndColor.texture) {
  103530. textureLevel = this._emissiveTextureAndColor.texture.level;
  103531. }
  103532. }
  103533. else {
  103534. this._emissiveTextureAndColor.texture = null;
  103535. }
  103536. }
  103537. if (this.customEmissiveColorSelector) {
  103538. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  103539. }
  103540. else {
  103541. if (material.emissiveColor) {
  103542. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  103543. }
  103544. else {
  103545. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  103546. }
  103547. }
  103548. };
  103549. /**
  103550. * Returns true if the mesh should render, otherwise false.
  103551. * @param mesh The mesh to render
  103552. * @returns true if it should render otherwise false
  103553. */
  103554. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  103555. return this.hasMesh(mesh);
  103556. };
  103557. /**
  103558. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  103559. * @param mesh The mesh to exclude from the glow layer
  103560. */
  103561. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  103562. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  103563. this._excludedMeshes.push(mesh.uniqueId);
  103564. }
  103565. };
  103566. /**
  103567. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  103568. * @param mesh The mesh to remove
  103569. */
  103570. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  103571. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  103572. if (index !== -1) {
  103573. this._excludedMeshes.splice(index, 1);
  103574. }
  103575. };
  103576. /**
  103577. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  103578. * @param mesh The mesh to include in the glow layer
  103579. */
  103580. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  103581. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  103582. this._includedOnlyMeshes.push(mesh.uniqueId);
  103583. }
  103584. };
  103585. /**
  103586. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  103587. * @param mesh The mesh to remove
  103588. */
  103589. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  103590. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  103591. if (index !== -1) {
  103592. this._includedOnlyMeshes.splice(index, 1);
  103593. }
  103594. };
  103595. /**
  103596. * Determine if a given mesh will be used in the glow layer
  103597. * @param mesh The mesh to test
  103598. * @returns true if the mesh will be highlighted by the current glow layer
  103599. */
  103600. GlowLayer.prototype.hasMesh = function (mesh) {
  103601. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103602. return false;
  103603. }
  103604. // Included Mesh
  103605. if (this._includedOnlyMeshes.length) {
  103606. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  103607. }
  103608. ;
  103609. // Excluded Mesh
  103610. if (this._excludedMeshes.length) {
  103611. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  103612. }
  103613. ;
  103614. return true;
  103615. };
  103616. /**
  103617. * Free any resources and references associated to a mesh.
  103618. * Internal use
  103619. * @param mesh The mesh to free.
  103620. * @hidden
  103621. */
  103622. GlowLayer.prototype._disposeMesh = function (mesh) {
  103623. this.removeIncludedOnlyMesh(mesh);
  103624. this.removeExcludedMesh(mesh);
  103625. };
  103626. /**
  103627. * Gets the class name of the effect layer
  103628. * @returns the string with the class name of the effect layer
  103629. */
  103630. GlowLayer.prototype.getClassName = function () {
  103631. return "GlowLayer";
  103632. };
  103633. /**
  103634. * Serializes this glow layer
  103635. * @returns a serialized glow layer object
  103636. */
  103637. GlowLayer.prototype.serialize = function () {
  103638. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103639. serializationObject.customType = "BABYLON.GlowLayer";
  103640. var index;
  103641. // Included meshes
  103642. serializationObject.includedMeshes = [];
  103643. if (this._includedOnlyMeshes.length) {
  103644. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  103645. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  103646. if (mesh) {
  103647. serializationObject.includedMeshes.push(mesh.id);
  103648. }
  103649. }
  103650. }
  103651. // Excluded meshes
  103652. serializationObject.excludedMeshes = [];
  103653. if (this._excludedMeshes.length) {
  103654. for (index = 0; index < this._excludedMeshes.length; index++) {
  103655. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  103656. if (mesh) {
  103657. serializationObject.excludedMeshes.push(mesh.id);
  103658. }
  103659. }
  103660. }
  103661. return serializationObject;
  103662. };
  103663. /**
  103664. * Creates a Glow Layer from parsed glow layer data
  103665. * @param parsedGlowLayer defines glow layer data
  103666. * @param scene defines the current scene
  103667. * @param rootUrl defines the root URL containing the glow layer information
  103668. * @returns a parsed Glow Layer
  103669. */
  103670. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  103671. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  103672. var index;
  103673. // Excluded meshes
  103674. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  103675. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  103676. if (mesh) {
  103677. gl.addExcludedMesh(mesh);
  103678. }
  103679. }
  103680. // Included meshes
  103681. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  103682. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  103683. if (mesh) {
  103684. gl.addIncludedOnlyMesh(mesh);
  103685. }
  103686. }
  103687. return gl;
  103688. };
  103689. /**
  103690. * Effect Name of the layer.
  103691. */
  103692. GlowLayer.EffectName = "GlowLayer";
  103693. /**
  103694. * The default blur kernel size used for the glow.
  103695. */
  103696. GlowLayer.DefaultBlurKernelSize = 32;
  103697. /**
  103698. * The default texture size ratio used for the glow.
  103699. */
  103700. GlowLayer.DefaultTextureRatio = 0.5;
  103701. __decorate([
  103702. BABYLON.serialize()
  103703. ], GlowLayer.prototype, "blurKernelSize", null);
  103704. __decorate([
  103705. BABYLON.serialize()
  103706. ], GlowLayer.prototype, "intensity", null);
  103707. __decorate([
  103708. BABYLON.serialize("options")
  103709. ], GlowLayer.prototype, "_options", void 0);
  103710. return GlowLayer;
  103711. }(BABYLON.EffectLayer));
  103712. BABYLON.GlowLayer = GlowLayer;
  103713. })(BABYLON || (BABYLON = {}));
  103714. //# sourceMappingURL=babylon.glowLayer.js.map
  103715. var BABYLON;
  103716. (function (BABYLON) {
  103717. /**
  103718. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  103719. */
  103720. var AssetTaskState;
  103721. (function (AssetTaskState) {
  103722. /**
  103723. * Initialization
  103724. */
  103725. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  103726. /**
  103727. * Running
  103728. */
  103729. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  103730. /**
  103731. * Done
  103732. */
  103733. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  103734. /**
  103735. * Error
  103736. */
  103737. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  103738. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  103739. /**
  103740. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  103741. */
  103742. var AbstractAssetTask = /** @class */ (function () {
  103743. /**
  103744. * Creates a new {BABYLON.AssetsManager}
  103745. * @param name defines the name of the task
  103746. */
  103747. function AbstractAssetTask(
  103748. /**
  103749. * Task name
  103750. */ name) {
  103751. this.name = name;
  103752. this._isCompleted = false;
  103753. this._taskState = AssetTaskState.INIT;
  103754. }
  103755. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  103756. /**
  103757. * Get if the task is completed
  103758. */
  103759. get: function () {
  103760. return this._isCompleted;
  103761. },
  103762. enumerable: true,
  103763. configurable: true
  103764. });
  103765. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  103766. /**
  103767. * Gets the current state of the task
  103768. */
  103769. get: function () {
  103770. return this._taskState;
  103771. },
  103772. enumerable: true,
  103773. configurable: true
  103774. });
  103775. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  103776. /**
  103777. * Gets the current error object (if task is in error)
  103778. */
  103779. get: function () {
  103780. return this._errorObject;
  103781. },
  103782. enumerable: true,
  103783. configurable: true
  103784. });
  103785. /**
  103786. * Internal only
  103787. * @hidden
  103788. */
  103789. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  103790. if (this._errorObject) {
  103791. return;
  103792. }
  103793. this._errorObject = {
  103794. message: message,
  103795. exception: exception
  103796. };
  103797. };
  103798. /**
  103799. * Execute the current task
  103800. * @param scene defines the scene where you want your assets to be loaded
  103801. * @param onSuccess is a callback called when the task is successfully executed
  103802. * @param onError is a callback called if an error occurs
  103803. */
  103804. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103805. var _this = this;
  103806. this._taskState = AssetTaskState.RUNNING;
  103807. this.runTask(scene, function () {
  103808. _this.onDoneCallback(onSuccess, onError);
  103809. }, function (msg, exception) {
  103810. _this.onErrorCallback(onError, msg, exception);
  103811. });
  103812. };
  103813. /**
  103814. * Execute the current task
  103815. * @param scene defines the scene where you want your assets to be loaded
  103816. * @param onSuccess is a callback called when the task is successfully executed
  103817. * @param onError is a callback called if an error occurs
  103818. */
  103819. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103820. throw new Error("runTask is not implemented");
  103821. };
  103822. /**
  103823. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  103824. * This can be used with failed tasks that have the reason for failure fixed.
  103825. */
  103826. AbstractAssetTask.prototype.reset = function () {
  103827. this._taskState = AssetTaskState.INIT;
  103828. };
  103829. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  103830. this._taskState = AssetTaskState.ERROR;
  103831. this._errorObject = {
  103832. message: message,
  103833. exception: exception
  103834. };
  103835. if (this.onError) {
  103836. this.onError(this, message, exception);
  103837. }
  103838. onError();
  103839. };
  103840. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  103841. try {
  103842. this._taskState = AssetTaskState.DONE;
  103843. this._isCompleted = true;
  103844. if (this.onSuccess) {
  103845. this.onSuccess(this);
  103846. }
  103847. onSuccess();
  103848. }
  103849. catch (e) {
  103850. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  103851. }
  103852. };
  103853. return AbstractAssetTask;
  103854. }());
  103855. BABYLON.AbstractAssetTask = AbstractAssetTask;
  103856. /**
  103857. * Class used to share progress information about assets loading
  103858. */
  103859. var AssetsProgressEvent = /** @class */ (function () {
  103860. /**
  103861. * Creates a {BABYLON.AssetsProgressEvent}
  103862. * @param remainingCount defines the number of remaining tasks to process
  103863. * @param totalCount defines the total number of tasks
  103864. * @param task defines the task that was just processed
  103865. */
  103866. function AssetsProgressEvent(remainingCount, totalCount, task) {
  103867. this.remainingCount = remainingCount;
  103868. this.totalCount = totalCount;
  103869. this.task = task;
  103870. }
  103871. return AssetsProgressEvent;
  103872. }());
  103873. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  103874. /**
  103875. * Define a task used by {BABYLON.AssetsManager} to load meshes
  103876. */
  103877. var MeshAssetTask = /** @class */ (function (_super) {
  103878. __extends(MeshAssetTask, _super);
  103879. /**
  103880. * Creates a new {BABYLON.MeshAssetTask}
  103881. * @param name defines the name of the task
  103882. * @param meshesNames defines the list of mesh's names you want to load
  103883. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  103884. * @param sceneFilename defines the filename of the scene to load from
  103885. */
  103886. function MeshAssetTask(
  103887. /**
  103888. * Defines the name of the task
  103889. */
  103890. name,
  103891. /**
  103892. * Defines the list of mesh's names you want to load
  103893. */
  103894. meshesNames,
  103895. /**
  103896. * Defines the root url to use as a base to load your meshes and associated resources
  103897. */
  103898. rootUrl,
  103899. /**
  103900. * Defines the filename of the scene to load from
  103901. */
  103902. sceneFilename) {
  103903. var _this = _super.call(this, name) || this;
  103904. _this.name = name;
  103905. _this.meshesNames = meshesNames;
  103906. _this.rootUrl = rootUrl;
  103907. _this.sceneFilename = sceneFilename;
  103908. return _this;
  103909. }
  103910. /**
  103911. * Execute the current task
  103912. * @param scene defines the scene where you want your assets to be loaded
  103913. * @param onSuccess is a callback called when the task is successfully executed
  103914. * @param onError is a callback called if an error occurs
  103915. */
  103916. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103917. var _this = this;
  103918. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  103919. _this.loadedMeshes = meshes;
  103920. _this.loadedParticleSystems = particleSystems;
  103921. _this.loadedSkeletons = skeletons;
  103922. onSuccess();
  103923. }, null, function (scene, message, exception) {
  103924. onError(message, exception);
  103925. });
  103926. };
  103927. return MeshAssetTask;
  103928. }(AbstractAssetTask));
  103929. BABYLON.MeshAssetTask = MeshAssetTask;
  103930. /**
  103931. * Define a task used by {BABYLON.AssetsManager} to load text content
  103932. */
  103933. var TextFileAssetTask = /** @class */ (function (_super) {
  103934. __extends(TextFileAssetTask, _super);
  103935. /**
  103936. * Creates a new TextFileAssetTask object
  103937. * @param name defines the name of the task
  103938. * @param url defines the location of the file to load
  103939. */
  103940. function TextFileAssetTask(
  103941. /**
  103942. * Defines the name of the task
  103943. */
  103944. name,
  103945. /**
  103946. * Defines the location of the file to load
  103947. */
  103948. url) {
  103949. var _this = _super.call(this, name) || this;
  103950. _this.name = name;
  103951. _this.url = url;
  103952. return _this;
  103953. }
  103954. /**
  103955. * Execute the current task
  103956. * @param scene defines the scene where you want your assets to be loaded
  103957. * @param onSuccess is a callback called when the task is successfully executed
  103958. * @param onError is a callback called if an error occurs
  103959. */
  103960. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103961. var _this = this;
  103962. scene._loadFile(this.url, function (data) {
  103963. _this.text = data;
  103964. onSuccess();
  103965. }, undefined, false, false, function (request, exception) {
  103966. if (request) {
  103967. onError(request.status + " " + request.statusText, exception);
  103968. }
  103969. });
  103970. };
  103971. return TextFileAssetTask;
  103972. }(AbstractAssetTask));
  103973. BABYLON.TextFileAssetTask = TextFileAssetTask;
  103974. /**
  103975. * Define a task used by {BABYLON.AssetsManager} to load binary data
  103976. */
  103977. var BinaryFileAssetTask = /** @class */ (function (_super) {
  103978. __extends(BinaryFileAssetTask, _super);
  103979. /**
  103980. * Creates a new BinaryFileAssetTask object
  103981. * @param name defines the name of the new task
  103982. * @param url defines the location of the file to load
  103983. */
  103984. function BinaryFileAssetTask(
  103985. /**
  103986. * Defines the name of the task
  103987. */
  103988. name,
  103989. /**
  103990. * Defines the location of the file to load
  103991. */
  103992. url) {
  103993. var _this = _super.call(this, name) || this;
  103994. _this.name = name;
  103995. _this.url = url;
  103996. return _this;
  103997. }
  103998. /**
  103999. * Execute the current task
  104000. * @param scene defines the scene where you want your assets to be loaded
  104001. * @param onSuccess is a callback called when the task is successfully executed
  104002. * @param onError is a callback called if an error occurs
  104003. */
  104004. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104005. var _this = this;
  104006. scene._loadFile(this.url, function (data) {
  104007. _this.data = data;
  104008. onSuccess();
  104009. }, undefined, true, true, function (request, exception) {
  104010. if (request) {
  104011. onError(request.status + " " + request.statusText, exception);
  104012. }
  104013. });
  104014. };
  104015. return BinaryFileAssetTask;
  104016. }(AbstractAssetTask));
  104017. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  104018. /**
  104019. * Define a task used by {BABYLON.AssetsManager} to load images
  104020. */
  104021. var ImageAssetTask = /** @class */ (function (_super) {
  104022. __extends(ImageAssetTask, _super);
  104023. /**
  104024. * Creates a new ImageAssetTask
  104025. * @param name defines the name of the task
  104026. * @param url defines the location of the image to load
  104027. */
  104028. function ImageAssetTask(
  104029. /**
  104030. * Defines the name of the task
  104031. */
  104032. name,
  104033. /**
  104034. * Defines the location of the image to load
  104035. */
  104036. url) {
  104037. var _this = _super.call(this, name) || this;
  104038. _this.name = name;
  104039. _this.url = url;
  104040. return _this;
  104041. }
  104042. /**
  104043. * Execute the current task
  104044. * @param scene defines the scene where you want your assets to be loaded
  104045. * @param onSuccess is a callback called when the task is successfully executed
  104046. * @param onError is a callback called if an error occurs
  104047. */
  104048. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104049. var _this = this;
  104050. var img = new Image();
  104051. BABYLON.Tools.SetCorsBehavior(this.url, img);
  104052. img.onload = function () {
  104053. _this.image = img;
  104054. onSuccess();
  104055. };
  104056. img.onerror = function (err) {
  104057. onError("Error loading image", err);
  104058. };
  104059. img.src = this.url;
  104060. };
  104061. return ImageAssetTask;
  104062. }(AbstractAssetTask));
  104063. BABYLON.ImageAssetTask = ImageAssetTask;
  104064. /**
  104065. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  104066. */
  104067. var TextureAssetTask = /** @class */ (function (_super) {
  104068. __extends(TextureAssetTask, _super);
  104069. /**
  104070. * Creates a new TextureAssetTask object
  104071. * @param name defines the name of the task
  104072. * @param url defines the location of the file to load
  104073. * @param noMipmap defines if mipmap should not be generated (default is false)
  104074. * @param invertY defines if texture must be inverted on Y axis (default is false)
  104075. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  104076. */
  104077. function TextureAssetTask(
  104078. /**
  104079. * Defines the name of the task
  104080. */
  104081. name,
  104082. /**
  104083. * Defines the location of the file to load
  104084. */
  104085. url,
  104086. /**
  104087. * Defines if mipmap should not be generated (default is false)
  104088. */
  104089. noMipmap,
  104090. /**
  104091. * Defines if texture must be inverted on Y axis (default is false)
  104092. */
  104093. invertY,
  104094. /**
  104095. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  104096. */
  104097. samplingMode) {
  104098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104099. var _this = _super.call(this, name) || this;
  104100. _this.name = name;
  104101. _this.url = url;
  104102. _this.noMipmap = noMipmap;
  104103. _this.invertY = invertY;
  104104. _this.samplingMode = samplingMode;
  104105. return _this;
  104106. }
  104107. /**
  104108. * Execute the current task
  104109. * @param scene defines the scene where you want your assets to be loaded
  104110. * @param onSuccess is a callback called when the task is successfully executed
  104111. * @param onError is a callback called if an error occurs
  104112. */
  104113. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104114. var onload = function () {
  104115. onSuccess();
  104116. };
  104117. var onerror = function (message, exception) {
  104118. onError(message, exception);
  104119. };
  104120. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  104121. };
  104122. return TextureAssetTask;
  104123. }(AbstractAssetTask));
  104124. BABYLON.TextureAssetTask = TextureAssetTask;
  104125. /**
  104126. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  104127. */
  104128. var CubeTextureAssetTask = /** @class */ (function (_super) {
  104129. __extends(CubeTextureAssetTask, _super);
  104130. /**
  104131. * Creates a new CubeTextureAssetTask
  104132. * @param name defines the name of the task
  104133. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  104134. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  104135. * @param noMipmap defines if mipmaps should not be generated (default is false)
  104136. * @param files defines the explicit list of files (undefined by default)
  104137. */
  104138. function CubeTextureAssetTask(
  104139. /**
  104140. * Defines the name of the task
  104141. */
  104142. name,
  104143. /**
  104144. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  104145. */
  104146. url,
  104147. /**
  104148. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  104149. */
  104150. extensions,
  104151. /**
  104152. * Defines if mipmaps should not be generated (default is false)
  104153. */
  104154. noMipmap,
  104155. /**
  104156. * Defines the explicit list of files (undefined by default)
  104157. */
  104158. files) {
  104159. var _this = _super.call(this, name) || this;
  104160. _this.name = name;
  104161. _this.url = url;
  104162. _this.extensions = extensions;
  104163. _this.noMipmap = noMipmap;
  104164. _this.files = files;
  104165. return _this;
  104166. }
  104167. /**
  104168. * Execute the current task
  104169. * @param scene defines the scene where you want your assets to be loaded
  104170. * @param onSuccess is a callback called when the task is successfully executed
  104171. * @param onError is a callback called if an error occurs
  104172. */
  104173. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104174. var onload = function () {
  104175. onSuccess();
  104176. };
  104177. var onerror = function (message, exception) {
  104178. onError(message, exception);
  104179. };
  104180. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  104181. };
  104182. return CubeTextureAssetTask;
  104183. }(AbstractAssetTask));
  104184. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  104185. /**
  104186. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  104187. */
  104188. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  104189. __extends(HDRCubeTextureAssetTask, _super);
  104190. /**
  104191. * Creates a new HDRCubeTextureAssetTask object
  104192. * @param name defines the name of the task
  104193. * @param url defines the location of the file to load
  104194. * @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.
  104195. * @param noMipmap defines if mipmaps should not be generated (default is false)
  104196. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  104197. * @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)
  104198. * @param reserved Internal use only
  104199. */
  104200. function HDRCubeTextureAssetTask(
  104201. /**
  104202. * Defines the name of the task
  104203. */
  104204. name,
  104205. /**
  104206. * Defines the location of the file to load
  104207. */
  104208. url,
  104209. /**
  104210. * Defines the desired size (the more it increases the longer the generation will be)
  104211. */
  104212. size,
  104213. /**
  104214. * Defines if mipmaps should not be generated (default is false)
  104215. */
  104216. noMipmap,
  104217. /**
  104218. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  104219. */
  104220. generateHarmonics,
  104221. /**
  104222. * 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)
  104223. */
  104224. gammaSpace,
  104225. /**
  104226. * Internal Use Only
  104227. */
  104228. reserved) {
  104229. if (noMipmap === void 0) { noMipmap = false; }
  104230. if (generateHarmonics === void 0) { generateHarmonics = true; }
  104231. if (gammaSpace === void 0) { gammaSpace = false; }
  104232. if (reserved === void 0) { reserved = false; }
  104233. var _this = _super.call(this, name) || this;
  104234. _this.name = name;
  104235. _this.url = url;
  104236. _this.size = size;
  104237. _this.noMipmap = noMipmap;
  104238. _this.generateHarmonics = generateHarmonics;
  104239. _this.gammaSpace = gammaSpace;
  104240. _this.reserved = reserved;
  104241. return _this;
  104242. }
  104243. /**
  104244. * Execute the current task
  104245. * @param scene defines the scene where you want your assets to be loaded
  104246. * @param onSuccess is a callback called when the task is successfully executed
  104247. * @param onError is a callback called if an error occurs
  104248. */
  104249. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  104250. var onload = function () {
  104251. onSuccess();
  104252. };
  104253. var onerror = function (message, exception) {
  104254. onError(message, exception);
  104255. };
  104256. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  104257. };
  104258. return HDRCubeTextureAssetTask;
  104259. }(AbstractAssetTask));
  104260. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  104261. /**
  104262. * This class can be used to easily import assets into a scene
  104263. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  104264. */
  104265. var AssetsManager = /** @class */ (function () {
  104266. /**
  104267. * Creates a new AssetsManager
  104268. * @param scene defines the scene to work on
  104269. */
  104270. function AssetsManager(scene) {
  104271. this._isLoading = false;
  104272. this._tasks = new Array();
  104273. this._waitingTasksCount = 0;
  104274. this._totalTasksCount = 0;
  104275. /**
  104276. * Observable called when all tasks are processed
  104277. */
  104278. this.onTaskSuccessObservable = new BABYLON.Observable();
  104279. /**
  104280. * Observable called when a task had an error
  104281. */
  104282. this.onTaskErrorObservable = new BABYLON.Observable();
  104283. /**
  104284. * Observable called when a task is successful
  104285. */
  104286. this.onTasksDoneObservable = new BABYLON.Observable();
  104287. /**
  104288. * Observable called when a task is done (whatever the result is)
  104289. */
  104290. this.onProgressObservable = new BABYLON.Observable();
  104291. /**
  104292. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  104293. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  104294. */
  104295. this.useDefaultLoadingScreen = true;
  104296. this._scene = scene;
  104297. }
  104298. /**
  104299. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  104300. * @param taskName defines the name of the new task
  104301. * @param meshesNames defines the name of meshes to load
  104302. * @param rootUrl defines the root url to use to locate files
  104303. * @param sceneFilename defines the filename of the scene file
  104304. * @returns a new {BABYLON.MeshAssetTask} object
  104305. */
  104306. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  104307. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  104308. this._tasks.push(task);
  104309. return task;
  104310. };
  104311. /**
  104312. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  104313. * @param taskName defines the name of the new task
  104314. * @param url defines the url of the file to load
  104315. * @returns a new {BABYLON.TextFileAssetTask} object
  104316. */
  104317. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  104318. var task = new TextFileAssetTask(taskName, url);
  104319. this._tasks.push(task);
  104320. return task;
  104321. };
  104322. /**
  104323. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  104324. * @param taskName defines the name of the new task
  104325. * @param url defines the url of the file to load
  104326. * @returns a new {BABYLON.BinaryFileAssetTask} object
  104327. */
  104328. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  104329. var task = new BinaryFileAssetTask(taskName, url);
  104330. this._tasks.push(task);
  104331. return task;
  104332. };
  104333. /**
  104334. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  104335. * @param taskName defines the name of the new task
  104336. * @param url defines the url of the file to load
  104337. * @returns a new {BABYLON.ImageAssetTask} object
  104338. */
  104339. AssetsManager.prototype.addImageTask = function (taskName, url) {
  104340. var task = new ImageAssetTask(taskName, url);
  104341. this._tasks.push(task);
  104342. return task;
  104343. };
  104344. /**
  104345. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  104346. * @param taskName defines the name of the new task
  104347. * @param url defines the url of the file to load
  104348. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104349. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  104350. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  104351. * @returns a new {BABYLON.TextureAssetTask} object
  104352. */
  104353. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  104354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104355. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  104356. this._tasks.push(task);
  104357. return task;
  104358. };
  104359. /**
  104360. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  104361. * @param taskName defines the name of the new task
  104362. * @param url defines the url of the file to load
  104363. * @param extensions defines the extension to use to load the cube map (can be null)
  104364. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104365. * @param files defines the list of files to load (can be null)
  104366. * @returns a new {BABYLON.CubeTextureAssetTask} object
  104367. */
  104368. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  104369. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  104370. this._tasks.push(task);
  104371. return task;
  104372. };
  104373. /**
  104374. *
  104375. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  104376. * @param taskName defines the name of the new task
  104377. * @param url defines the url of the file to load
  104378. * @param size defines the size you want for the cubemap (can be null)
  104379. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104380. * @param generateHarmonics defines if you want to automatically generate (true by default)
  104381. * @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)
  104382. * @param reserved Internal use only
  104383. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  104384. */
  104385. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  104386. if (noMipmap === void 0) { noMipmap = false; }
  104387. if (generateHarmonics === void 0) { generateHarmonics = true; }
  104388. if (gammaSpace === void 0) { gammaSpace = false; }
  104389. if (reserved === void 0) { reserved = false; }
  104390. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  104391. this._tasks.push(task);
  104392. return task;
  104393. };
  104394. /**
  104395. * Remove a task from the assets manager.
  104396. * @param task the task to remove
  104397. */
  104398. AssetsManager.prototype.removeTask = function (task) {
  104399. var index = this._tasks.indexOf(task);
  104400. if (index > -1) {
  104401. this._tasks.splice(index, 1);
  104402. }
  104403. };
  104404. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  104405. this._waitingTasksCount--;
  104406. try {
  104407. if (this.onProgress) {
  104408. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  104409. }
  104410. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  104411. }
  104412. catch (e) {
  104413. BABYLON.Tools.Error("Error running progress callbacks.");
  104414. console.log(e);
  104415. }
  104416. if (this._waitingTasksCount === 0) {
  104417. try {
  104418. if (this.onFinish) {
  104419. this.onFinish(this._tasks);
  104420. }
  104421. // Let's remove successfull tasks
  104422. var currentTasks = this._tasks.slice();
  104423. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  104424. var task = currentTasks_1[_i];
  104425. if (task.taskState === AssetTaskState.DONE) {
  104426. var index = this._tasks.indexOf(task);
  104427. if (index > -1) {
  104428. this._tasks.splice(index, 1);
  104429. }
  104430. }
  104431. }
  104432. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104433. }
  104434. catch (e) {
  104435. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  104436. console.log(e);
  104437. }
  104438. this._isLoading = false;
  104439. this._scene.getEngine().hideLoadingUI();
  104440. }
  104441. };
  104442. AssetsManager.prototype._runTask = function (task) {
  104443. var _this = this;
  104444. var done = function () {
  104445. try {
  104446. if (_this.onTaskSuccess) {
  104447. _this.onTaskSuccess(task);
  104448. }
  104449. _this.onTaskSuccessObservable.notifyObservers(task);
  104450. _this._decreaseWaitingTasksCount(task);
  104451. }
  104452. catch (e) {
  104453. error("Error executing task success callbacks", e);
  104454. }
  104455. };
  104456. var error = function (message, exception) {
  104457. task._setErrorObject(message, exception);
  104458. if (_this.onTaskError) {
  104459. _this.onTaskError(task);
  104460. }
  104461. _this.onTaskErrorObservable.notifyObservers(task);
  104462. _this._decreaseWaitingTasksCount(task);
  104463. };
  104464. task.run(this._scene, done, error);
  104465. };
  104466. /**
  104467. * Reset the {BABYLON.AssetsManager} and remove all tasks
  104468. * @return the current instance of the {BABYLON.AssetsManager}
  104469. */
  104470. AssetsManager.prototype.reset = function () {
  104471. this._isLoading = false;
  104472. this._tasks = new Array();
  104473. return this;
  104474. };
  104475. /**
  104476. * Start the loading process
  104477. * @return the current instance of the {BABYLON.AssetsManager}
  104478. */
  104479. AssetsManager.prototype.load = function () {
  104480. if (this._isLoading) {
  104481. return this;
  104482. }
  104483. this._isLoading = true;
  104484. this._waitingTasksCount = this._tasks.length;
  104485. this._totalTasksCount = this._tasks.length;
  104486. if (this._waitingTasksCount === 0) {
  104487. this._isLoading = false;
  104488. if (this.onFinish) {
  104489. this.onFinish(this._tasks);
  104490. }
  104491. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104492. return this;
  104493. }
  104494. if (this.useDefaultLoadingScreen) {
  104495. this._scene.getEngine().displayLoadingUI();
  104496. }
  104497. for (var index = 0; index < this._tasks.length; index++) {
  104498. var task = this._tasks[index];
  104499. if (task.taskState === AssetTaskState.INIT) {
  104500. this._runTask(task);
  104501. }
  104502. }
  104503. return this;
  104504. };
  104505. return AssetsManager;
  104506. }());
  104507. BABYLON.AssetsManager = AssetsManager;
  104508. })(BABYLON || (BABYLON = {}));
  104509. //# sourceMappingURL=babylon.assetsManager.js.map
  104510. var BABYLON;
  104511. (function (BABYLON) {
  104512. var serializedGeometries = [];
  104513. var serializeGeometry = function (geometry, serializationGeometries) {
  104514. if (serializedGeometries[geometry.id]) {
  104515. return;
  104516. }
  104517. if (geometry.doNotSerialize) {
  104518. return;
  104519. }
  104520. if (geometry instanceof BABYLON.BoxGeometry) {
  104521. serializationGeometries.boxes.push(geometry.serialize());
  104522. }
  104523. else if (geometry instanceof BABYLON.SphereGeometry) {
  104524. serializationGeometries.spheres.push(geometry.serialize());
  104525. }
  104526. else if (geometry instanceof BABYLON.CylinderGeometry) {
  104527. serializationGeometries.cylinders.push(geometry.serialize());
  104528. }
  104529. else if (geometry instanceof BABYLON.TorusGeometry) {
  104530. serializationGeometries.toruses.push(geometry.serialize());
  104531. }
  104532. else if (geometry instanceof BABYLON.GroundGeometry) {
  104533. serializationGeometries.grounds.push(geometry.serialize());
  104534. }
  104535. else if (geometry instanceof BABYLON.Plane) {
  104536. serializationGeometries.planes.push(geometry.serialize());
  104537. }
  104538. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  104539. serializationGeometries.torusKnots.push(geometry.serialize());
  104540. }
  104541. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  104542. throw new Error("Unknown primitive type");
  104543. }
  104544. else {
  104545. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  104546. }
  104547. serializedGeometries[geometry.id] = true;
  104548. };
  104549. var serializeMesh = function (mesh, serializationScene) {
  104550. var serializationObject = {};
  104551. // Geometry
  104552. var geometry = mesh._geometry;
  104553. if (geometry) {
  104554. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  104555. // 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
  104556. serializeGeometry(geometry, serializationScene.geometries);
  104557. }
  104558. }
  104559. // Custom
  104560. if (mesh.serialize) {
  104561. mesh.serialize(serializationObject);
  104562. }
  104563. return serializationObject;
  104564. };
  104565. var finalizeSingleMesh = function (mesh, serializationObject) {
  104566. //only works if the mesh is already loaded
  104567. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104568. //serialize material
  104569. if (mesh.material) {
  104570. if (mesh.material instanceof BABYLON.MultiMaterial) {
  104571. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  104572. serializationObject.materials = serializationObject.materials || [];
  104573. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104574. serializationObject.multiMaterials.push(mesh.material.serialize());
  104575. var _loop_1 = function (submaterial) {
  104576. if (submaterial) {
  104577. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  104578. serializationObject.materials.push(submaterial.serialize());
  104579. }
  104580. }
  104581. };
  104582. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  104583. var submaterial = _a[_i];
  104584. _loop_1(submaterial);
  104585. }
  104586. }
  104587. }
  104588. else {
  104589. serializationObject.materials = serializationObject.materials || [];
  104590. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104591. serializationObject.materials.push(mesh.material.serialize());
  104592. }
  104593. }
  104594. }
  104595. //serialize geometry
  104596. var geometry = mesh._geometry;
  104597. if (geometry) {
  104598. if (!serializationObject.geometries) {
  104599. serializationObject.geometries = {};
  104600. serializationObject.geometries.boxes = [];
  104601. serializationObject.geometries.spheres = [];
  104602. serializationObject.geometries.cylinders = [];
  104603. serializationObject.geometries.toruses = [];
  104604. serializationObject.geometries.grounds = [];
  104605. serializationObject.geometries.planes = [];
  104606. serializationObject.geometries.torusKnots = [];
  104607. serializationObject.geometries.vertexData = [];
  104608. }
  104609. serializeGeometry(geometry, serializationObject.geometries);
  104610. }
  104611. // Skeletons
  104612. if (mesh.skeleton) {
  104613. serializationObject.skeletons = serializationObject.skeletons || [];
  104614. serializationObject.skeletons.push(mesh.skeleton.serialize());
  104615. }
  104616. //serialize the actual mesh
  104617. serializationObject.meshes = serializationObject.meshes || [];
  104618. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104619. }
  104620. };
  104621. var SceneSerializer = /** @class */ (function () {
  104622. function SceneSerializer() {
  104623. }
  104624. SceneSerializer.ClearCache = function () {
  104625. serializedGeometries = [];
  104626. };
  104627. SceneSerializer.Serialize = function (scene) {
  104628. var serializationObject = {};
  104629. SceneSerializer.ClearCache();
  104630. // Scene
  104631. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  104632. serializationObject.autoClear = scene.autoClear;
  104633. serializationObject.clearColor = scene.clearColor.asArray();
  104634. serializationObject.ambientColor = scene.ambientColor.asArray();
  104635. serializationObject.gravity = scene.gravity.asArray();
  104636. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  104637. serializationObject.workerCollisions = scene.workerCollisions;
  104638. // Fog
  104639. if (scene.fogMode && scene.fogMode !== 0) {
  104640. serializationObject.fogMode = scene.fogMode;
  104641. serializationObject.fogColor = scene.fogColor.asArray();
  104642. serializationObject.fogStart = scene.fogStart;
  104643. serializationObject.fogEnd = scene.fogEnd;
  104644. serializationObject.fogDensity = scene.fogDensity;
  104645. }
  104646. //Physics
  104647. if (scene.isPhysicsEnabled()) {
  104648. var physicEngine = scene.getPhysicsEngine();
  104649. if (physicEngine) {
  104650. serializationObject.physicsEnabled = true;
  104651. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  104652. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  104653. }
  104654. }
  104655. // Metadata
  104656. if (scene.metadata) {
  104657. serializationObject.metadata = scene.metadata;
  104658. }
  104659. // Morph targets
  104660. serializationObject.morphTargetManagers = [];
  104661. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  104662. var abstractMesh = _a[_i];
  104663. var manager = abstractMesh.morphTargetManager;
  104664. if (manager) {
  104665. serializationObject.morphTargetManagers.push(manager.serialize());
  104666. }
  104667. }
  104668. // Lights
  104669. serializationObject.lights = [];
  104670. var index;
  104671. var light;
  104672. for (index = 0; index < scene.lights.length; index++) {
  104673. light = scene.lights[index];
  104674. if (!light.doNotSerialize) {
  104675. serializationObject.lights.push(light.serialize());
  104676. }
  104677. }
  104678. // Cameras
  104679. serializationObject.cameras = [];
  104680. for (index = 0; index < scene.cameras.length; index++) {
  104681. var camera = scene.cameras[index];
  104682. if (!camera.doNotSerialize) {
  104683. serializationObject.cameras.push(camera.serialize());
  104684. }
  104685. }
  104686. if (scene.activeCamera) {
  104687. serializationObject.activeCameraID = scene.activeCamera.id;
  104688. }
  104689. // Animations
  104690. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  104691. // Materials
  104692. serializationObject.materials = [];
  104693. serializationObject.multiMaterials = [];
  104694. var material;
  104695. for (index = 0; index < scene.materials.length; index++) {
  104696. material = scene.materials[index];
  104697. if (!material.doNotSerialize) {
  104698. serializationObject.materials.push(material.serialize());
  104699. }
  104700. }
  104701. // MultiMaterials
  104702. serializationObject.multiMaterials = [];
  104703. for (index = 0; index < scene.multiMaterials.length; index++) {
  104704. var multiMaterial = scene.multiMaterials[index];
  104705. serializationObject.multiMaterials.push(multiMaterial.serialize());
  104706. }
  104707. // Environment texture
  104708. if (scene.environmentTexture) {
  104709. serializationObject.environmentTexture = scene.environmentTexture.name;
  104710. }
  104711. // Skeletons
  104712. serializationObject.skeletons = [];
  104713. for (index = 0; index < scene.skeletons.length; index++) {
  104714. var skeleton = scene.skeletons[index];
  104715. if (!skeleton.doNotSerialize) {
  104716. serializationObject.skeletons.push(skeleton.serialize());
  104717. }
  104718. }
  104719. // Transform nodes
  104720. serializationObject.transformNodes = [];
  104721. for (index = 0; index < scene.transformNodes.length; index++) {
  104722. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  104723. }
  104724. // Geometries
  104725. serializationObject.geometries = {};
  104726. serializationObject.geometries.boxes = [];
  104727. serializationObject.geometries.spheres = [];
  104728. serializationObject.geometries.cylinders = [];
  104729. serializationObject.geometries.toruses = [];
  104730. serializationObject.geometries.grounds = [];
  104731. serializationObject.geometries.planes = [];
  104732. serializationObject.geometries.torusKnots = [];
  104733. serializationObject.geometries.vertexData = [];
  104734. serializedGeometries = [];
  104735. var geometries = scene.getGeometries();
  104736. for (index = 0; index < geometries.length; index++) {
  104737. var geometry = geometries[index];
  104738. if (geometry.isReady()) {
  104739. serializeGeometry(geometry, serializationObject.geometries);
  104740. }
  104741. }
  104742. // Meshes
  104743. serializationObject.meshes = [];
  104744. for (index = 0; index < scene.meshes.length; index++) {
  104745. var abstractMesh = scene.meshes[index];
  104746. if (abstractMesh instanceof BABYLON.Mesh) {
  104747. var mesh = abstractMesh;
  104748. if (!mesh.doNotSerialize) {
  104749. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104750. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104751. }
  104752. }
  104753. }
  104754. }
  104755. // Particles Systems
  104756. serializationObject.particleSystems = [];
  104757. for (index = 0; index < scene.particleSystems.length; index++) {
  104758. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  104759. }
  104760. // Action Manager
  104761. if (scene.actionManager) {
  104762. serializationObject.actions = scene.actionManager.serialize("scene");
  104763. }
  104764. // Components
  104765. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  104766. var component = _c[_b];
  104767. component.serialize(serializationObject);
  104768. }
  104769. return serializationObject;
  104770. };
  104771. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  104772. if (withParents === void 0) { withParents = false; }
  104773. if (withChildren === void 0) { withChildren = false; }
  104774. var serializationObject = {};
  104775. SceneSerializer.ClearCache();
  104776. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  104777. if (withParents || withChildren) {
  104778. //deliberate for loop! not for each, appended should be processed as well.
  104779. for (var i = 0; i < toSerialize.length; ++i) {
  104780. if (withChildren) {
  104781. toSerialize[i].getDescendants().forEach(function (node) {
  104782. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  104783. toSerialize.push(node);
  104784. }
  104785. });
  104786. }
  104787. //make sure the array doesn't contain the object already
  104788. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  104789. toSerialize.push(toSerialize[i].parent);
  104790. }
  104791. }
  104792. }
  104793. toSerialize.forEach(function (mesh) {
  104794. finalizeSingleMesh(mesh, serializationObject);
  104795. });
  104796. return serializationObject;
  104797. };
  104798. return SceneSerializer;
  104799. }());
  104800. BABYLON.SceneSerializer = SceneSerializer;
  104801. })(BABYLON || (BABYLON = {}));
  104802. //# sourceMappingURL=babylon.sceneSerializer.js.map
  104803. var BABYLON;
  104804. (function (BABYLON) {
  104805. /**
  104806. * Class used to generate realtime reflection / refraction cube textures
  104807. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  104808. */
  104809. var ReflectionProbe = /** @class */ (function () {
  104810. /**
  104811. * Creates a new reflection probe
  104812. * @param name defines the name of the probe
  104813. * @param size defines the texture resolution (for each face)
  104814. * @param scene defines the hosting scene
  104815. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  104816. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  104817. */
  104818. function ReflectionProbe(
  104819. /** defines the name of the probe */
  104820. name, size, scene, generateMipMaps, useFloat) {
  104821. if (generateMipMaps === void 0) { generateMipMaps = true; }
  104822. if (useFloat === void 0) { useFloat = false; }
  104823. var _this = this;
  104824. this.name = name;
  104825. this._viewMatrix = BABYLON.Matrix.Identity();
  104826. this._target = BABYLON.Vector3.Zero();
  104827. this._add = BABYLON.Vector3.Zero();
  104828. this._invertYAxis = false;
  104829. /** Gets or sets probe position (center of the cube map) */
  104830. this.position = BABYLON.Vector3.Zero();
  104831. this._scene = scene;
  104832. // Create the scene field if not exist.
  104833. if (!this._scene.reflectionProbes) {
  104834. this._scene.reflectionProbes = new Array();
  104835. }
  104836. this._scene.reflectionProbes.push(this);
  104837. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  104838. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  104839. switch (faceIndex) {
  104840. case 0:
  104841. _this._add.copyFromFloats(1, 0, 0);
  104842. break;
  104843. case 1:
  104844. _this._add.copyFromFloats(-1, 0, 0);
  104845. break;
  104846. case 2:
  104847. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  104848. break;
  104849. case 3:
  104850. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  104851. break;
  104852. case 4:
  104853. _this._add.copyFromFloats(0, 0, 1);
  104854. break;
  104855. case 5:
  104856. _this._add.copyFromFloats(0, 0, -1);
  104857. break;
  104858. }
  104859. if (_this._attachedMesh) {
  104860. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  104861. }
  104862. _this.position.addToRef(_this._add, _this._target);
  104863. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  104864. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  104865. scene._forcedViewPosition = _this.position;
  104866. });
  104867. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  104868. scene._forcedViewPosition = null;
  104869. scene.updateTransformMatrix(true);
  104870. });
  104871. if (scene.activeCamera) {
  104872. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  104873. }
  104874. }
  104875. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  104876. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  104877. get: function () {
  104878. return this._renderTargetTexture.samples;
  104879. },
  104880. set: function (value) {
  104881. this._renderTargetTexture.samples = value;
  104882. },
  104883. enumerable: true,
  104884. configurable: true
  104885. });
  104886. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  104887. /** Gets or sets the refresh rate to use (on every frame by default) */
  104888. get: function () {
  104889. return this._renderTargetTexture.refreshRate;
  104890. },
  104891. set: function (value) {
  104892. this._renderTargetTexture.refreshRate = value;
  104893. },
  104894. enumerable: true,
  104895. configurable: true
  104896. });
  104897. /**
  104898. * Gets the hosting scene
  104899. * @returns a Scene
  104900. */
  104901. ReflectionProbe.prototype.getScene = function () {
  104902. return this._scene;
  104903. };
  104904. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  104905. /** Gets the internal CubeTexture used to render to */
  104906. get: function () {
  104907. return this._renderTargetTexture;
  104908. },
  104909. enumerable: true,
  104910. configurable: true
  104911. });
  104912. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  104913. /** Gets the list of meshes to render */
  104914. get: function () {
  104915. return this._renderTargetTexture.renderList;
  104916. },
  104917. enumerable: true,
  104918. configurable: true
  104919. });
  104920. /**
  104921. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  104922. * @param mesh defines the mesh to attach to
  104923. */
  104924. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  104925. this._attachedMesh = mesh;
  104926. };
  104927. /**
  104928. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  104929. * @param renderingGroupId The rendering group id corresponding to its index
  104930. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  104931. */
  104932. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  104933. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  104934. };
  104935. /**
  104936. * Clean all associated resources
  104937. */
  104938. ReflectionProbe.prototype.dispose = function () {
  104939. var index = this._scene.reflectionProbes.indexOf(this);
  104940. if (index !== -1) {
  104941. // Remove from the scene if found
  104942. this._scene.reflectionProbes.splice(index, 1);
  104943. }
  104944. if (this._renderTargetTexture) {
  104945. this._renderTargetTexture.dispose();
  104946. this._renderTargetTexture = null;
  104947. }
  104948. };
  104949. return ReflectionProbe;
  104950. }());
  104951. BABYLON.ReflectionProbe = ReflectionProbe;
  104952. })(BABYLON || (BABYLON = {}));
  104953. //# sourceMappingURL=babylon.reflectionProbe.js.map
  104954. var BABYLON;
  104955. (function (BABYLON) {
  104956. /**
  104957. * Defines the layer scene component responsible to manage any layers
  104958. * in a given scene.
  104959. */
  104960. var LayerSceneComponent = /** @class */ (function () {
  104961. /**
  104962. * Creates a new instance of the component for the given scene
  104963. * @param scene Defines the scene to register the component in
  104964. */
  104965. function LayerSceneComponent(scene) {
  104966. /**
  104967. * The component name helpfull to identify the component in the list of scene components.
  104968. */
  104969. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  104970. this.scene = scene;
  104971. this._engine = scene.getEngine();
  104972. scene.layers = new Array();
  104973. }
  104974. /**
  104975. * Registers the component in a given scene
  104976. */
  104977. LayerSceneComponent.prototype.register = function () {
  104978. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  104979. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  104980. };
  104981. /**
  104982. * Rebuilds the elements related to this component in case of
  104983. * context lost for instance.
  104984. */
  104985. LayerSceneComponent.prototype.rebuild = function () {
  104986. var layers = this.scene.layers;
  104987. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104988. var layer = layers_1[_i];
  104989. layer._rebuild();
  104990. }
  104991. };
  104992. /**
  104993. * Disposes the component and the associated ressources.
  104994. */
  104995. LayerSceneComponent.prototype.dispose = function () {
  104996. var layers = this.scene.layers;
  104997. while (layers.length) {
  104998. layers[0].dispose();
  104999. }
  105000. };
  105001. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  105002. var layers = this.scene.layers;
  105003. if (layers.length) {
  105004. this._engine.setDepthBuffer(false);
  105005. var cameraLayerMask = camera.layerMask;
  105006. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  105007. var layer = layers_2[_i];
  105008. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  105009. layer.render();
  105010. }
  105011. }
  105012. this._engine.setDepthBuffer(true);
  105013. }
  105014. };
  105015. LayerSceneComponent.prototype._drawBackground = function (camera) {
  105016. this._draw(camera, true);
  105017. };
  105018. LayerSceneComponent.prototype._drawForeground = function (camera) {
  105019. this._draw(camera, false);
  105020. };
  105021. return LayerSceneComponent;
  105022. }());
  105023. BABYLON.LayerSceneComponent = LayerSceneComponent;
  105024. })(BABYLON || (BABYLON = {}));
  105025. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  105026. var BABYLON;
  105027. (function (BABYLON) {
  105028. var Layer = /** @class */ (function () {
  105029. function Layer(name, imgUrl, scene, isBackground, color) {
  105030. this.name = name;
  105031. this.scale = new BABYLON.Vector2(1, 1);
  105032. this.offset = new BABYLON.Vector2(0, 0);
  105033. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  105034. this.layerMask = 0x0FFFFFFF;
  105035. this._vertexBuffers = {};
  105036. // Events
  105037. /**
  105038. * An event triggered when the layer is disposed.
  105039. */
  105040. this.onDisposeObservable = new BABYLON.Observable();
  105041. /**
  105042. * An event triggered before rendering the scene
  105043. */
  105044. this.onBeforeRenderObservable = new BABYLON.Observable();
  105045. /**
  105046. * An event triggered after rendering the scene
  105047. */
  105048. this.onAfterRenderObservable = new BABYLON.Observable();
  105049. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  105050. this.isBackground = isBackground === undefined ? true : isBackground;
  105051. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  105052. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  105053. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  105054. if (!layerComponent) {
  105055. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  105056. this._scene._addComponent(layerComponent);
  105057. }
  105058. this._scene.layers.push(this);
  105059. var engine = this._scene.getEngine();
  105060. // VBO
  105061. var vertices = [];
  105062. vertices.push(1, 1);
  105063. vertices.push(-1, 1);
  105064. vertices.push(-1, -1);
  105065. vertices.push(1, -1);
  105066. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105067. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105068. this._createIndexBuffer();
  105069. // Effects
  105070. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  105071. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  105072. }
  105073. Object.defineProperty(Layer.prototype, "onDispose", {
  105074. set: function (callback) {
  105075. if (this._onDisposeObserver) {
  105076. this.onDisposeObservable.remove(this._onDisposeObserver);
  105077. }
  105078. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105079. },
  105080. enumerable: true,
  105081. configurable: true
  105082. });
  105083. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  105084. set: function (callback) {
  105085. if (this._onBeforeRenderObserver) {
  105086. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  105087. }
  105088. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  105089. },
  105090. enumerable: true,
  105091. configurable: true
  105092. });
  105093. Object.defineProperty(Layer.prototype, "onAfterRender", {
  105094. set: function (callback) {
  105095. if (this._onAfterRenderObserver) {
  105096. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  105097. }
  105098. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  105099. },
  105100. enumerable: true,
  105101. configurable: true
  105102. });
  105103. Layer.prototype._createIndexBuffer = function () {
  105104. var engine = this._scene.getEngine();
  105105. // Indices
  105106. var indices = [];
  105107. indices.push(0);
  105108. indices.push(1);
  105109. indices.push(2);
  105110. indices.push(0);
  105111. indices.push(2);
  105112. indices.push(3);
  105113. this._indexBuffer = engine.createIndexBuffer(indices);
  105114. };
  105115. /** @hidden */
  105116. Layer.prototype._rebuild = function () {
  105117. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105118. if (vb) {
  105119. vb._rebuild();
  105120. }
  105121. this._createIndexBuffer();
  105122. };
  105123. Layer.prototype.render = function () {
  105124. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  105125. // Check
  105126. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  105127. return;
  105128. var engine = this._scene.getEngine();
  105129. this.onBeforeRenderObservable.notifyObservers(this);
  105130. // Render
  105131. engine.enableEffect(currentEffect);
  105132. engine.setState(false);
  105133. // Texture
  105134. currentEffect.setTexture("textureSampler", this.texture);
  105135. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  105136. // Color
  105137. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  105138. // Scale / offset
  105139. currentEffect.setVector2("offset", this.offset);
  105140. currentEffect.setVector2("scale", this.scale);
  105141. // VBOs
  105142. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  105143. // Draw order
  105144. if (!this.alphaTest) {
  105145. engine.setAlphaMode(this.alphaBlendingMode);
  105146. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105147. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  105148. }
  105149. else {
  105150. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105151. }
  105152. this.onAfterRenderObservable.notifyObservers(this);
  105153. };
  105154. Layer.prototype.dispose = function () {
  105155. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105156. if (vertexBuffer) {
  105157. vertexBuffer.dispose();
  105158. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  105159. }
  105160. if (this._indexBuffer) {
  105161. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  105162. this._indexBuffer = null;
  105163. }
  105164. if (this.texture) {
  105165. this.texture.dispose();
  105166. this.texture = null;
  105167. }
  105168. // Remove from scene
  105169. var index = this._scene.layers.indexOf(this);
  105170. this._scene.layers.splice(index, 1);
  105171. // Callback
  105172. this.onDisposeObservable.notifyObservers(this);
  105173. this.onDisposeObservable.clear();
  105174. this.onAfterRenderObservable.clear();
  105175. this.onBeforeRenderObservable.clear();
  105176. };
  105177. return Layer;
  105178. }());
  105179. BABYLON.Layer = Layer;
  105180. })(BABYLON || (BABYLON = {}));
  105181. //# sourceMappingURL=babylon.layer.js.map
  105182. var BABYLON;
  105183. (function (BABYLON) {
  105184. var TextureTools = /** @class */ (function () {
  105185. function TextureTools() {
  105186. }
  105187. /**
  105188. * Uses the GPU to create a copy texture rescaled at a given size
  105189. * @param texture Texture to copy from
  105190. * @param width Desired width
  105191. * @param height Desired height
  105192. * @return Generated texture
  105193. */
  105194. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  105195. if (useBilinearMode === void 0) { useBilinearMode = true; }
  105196. var scene = texture.getScene();
  105197. var engine = scene.getEngine();
  105198. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  105199. rtt.wrapU = texture.wrapU;
  105200. rtt.wrapV = texture.wrapV;
  105201. rtt.uOffset = texture.uOffset;
  105202. rtt.vOffset = texture.vOffset;
  105203. rtt.uScale = texture.uScale;
  105204. rtt.vScale = texture.vScale;
  105205. rtt.uAng = texture.uAng;
  105206. rtt.vAng = texture.vAng;
  105207. rtt.wAng = texture.wAng;
  105208. rtt.coordinatesIndex = texture.coordinatesIndex;
  105209. rtt.level = texture.level;
  105210. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  105211. rtt._texture.isReady = false;
  105212. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105213. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105214. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105215. passPostProcess.getEffect().executeWhenCompiled(function () {
  105216. passPostProcess.onApply = function (effect) {
  105217. effect.setTexture("textureSampler", texture);
  105218. };
  105219. var internalTexture = rtt.getInternalTexture();
  105220. if (internalTexture) {
  105221. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  105222. engine.unBindFramebuffer(internalTexture);
  105223. rtt.disposeFramebufferObjects();
  105224. passPostProcess.dispose();
  105225. internalTexture.isReady = true;
  105226. }
  105227. });
  105228. return rtt;
  105229. };
  105230. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  105231. if (!scene._environmentBRDFTexture) {
  105232. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105233. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105234. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105235. scene._environmentBRDFTexture = texture;
  105236. }
  105237. return scene._environmentBRDFTexture;
  105238. };
  105239. 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=";
  105240. return TextureTools;
  105241. }());
  105242. BABYLON.TextureTools = TextureTools;
  105243. })(BABYLON || (BABYLON = {}));
  105244. //# sourceMappingURL=babylon.textureTools.js.map
  105245. var BABYLON;
  105246. (function (BABYLON) {
  105247. var FramingBehavior = /** @class */ (function () {
  105248. function FramingBehavior() {
  105249. this._mode = FramingBehavior.FitFrustumSidesMode;
  105250. this._radiusScale = 1.0;
  105251. this._positionScale = 0.5;
  105252. this._defaultElevation = 0.3;
  105253. this._elevationReturnTime = 1500;
  105254. this._elevationReturnWaitTime = 1000;
  105255. this._zoomStopsAnimation = false;
  105256. this._framingTime = 1500;
  105257. this._isPointerDown = false;
  105258. this._lastInteractionTime = -Infinity;
  105259. // Framing control
  105260. this._animatables = new Array();
  105261. this._betaIsAnimating = false;
  105262. }
  105263. Object.defineProperty(FramingBehavior.prototype, "name", {
  105264. get: function () {
  105265. return "Framing";
  105266. },
  105267. enumerable: true,
  105268. configurable: true
  105269. });
  105270. Object.defineProperty(FramingBehavior.prototype, "mode", {
  105271. /**
  105272. * Gets current mode used by the behavior.
  105273. */
  105274. get: function () {
  105275. return this._mode;
  105276. },
  105277. /**
  105278. * Sets the current mode used by the behavior
  105279. */
  105280. set: function (mode) {
  105281. this._mode = mode;
  105282. },
  105283. enumerable: true,
  105284. configurable: true
  105285. });
  105286. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  105287. /**
  105288. * Gets the scale applied to the radius
  105289. */
  105290. get: function () {
  105291. return this._radiusScale;
  105292. },
  105293. /**
  105294. * Sets the scale applied to the radius (1 by default)
  105295. */
  105296. set: function (radius) {
  105297. this._radiusScale = radius;
  105298. },
  105299. enumerable: true,
  105300. configurable: true
  105301. });
  105302. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  105303. /**
  105304. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  105305. */
  105306. get: function () {
  105307. return this._positionScale;
  105308. },
  105309. /**
  105310. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  105311. */
  105312. set: function (scale) {
  105313. this._positionScale = scale;
  105314. },
  105315. enumerable: true,
  105316. configurable: true
  105317. });
  105318. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  105319. /**
  105320. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  105321. * behaviour is triggered, in radians.
  105322. */
  105323. get: function () {
  105324. return this._defaultElevation;
  105325. },
  105326. /**
  105327. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  105328. * behaviour is triggered, in radians.
  105329. */
  105330. set: function (elevation) {
  105331. this._defaultElevation = elevation;
  105332. },
  105333. enumerable: true,
  105334. configurable: true
  105335. });
  105336. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  105337. /**
  105338. * Gets the time (in milliseconds) taken to return to the default beta position.
  105339. * Negative value indicates camera should not return to default.
  105340. */
  105341. get: function () {
  105342. return this._elevationReturnTime;
  105343. },
  105344. /**
  105345. * Sets the time (in milliseconds) taken to return to the default beta position.
  105346. * Negative value indicates camera should not return to default.
  105347. */
  105348. set: function (speed) {
  105349. this._elevationReturnTime = speed;
  105350. },
  105351. enumerable: true,
  105352. configurable: true
  105353. });
  105354. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  105355. /**
  105356. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  105357. */
  105358. get: function () {
  105359. return this._elevationReturnWaitTime;
  105360. },
  105361. /**
  105362. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  105363. */
  105364. set: function (time) {
  105365. this._elevationReturnWaitTime = time;
  105366. },
  105367. enumerable: true,
  105368. configurable: true
  105369. });
  105370. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  105371. /**
  105372. * Gets the flag that indicates if user zooming should stop animation.
  105373. */
  105374. get: function () {
  105375. return this._zoomStopsAnimation;
  105376. },
  105377. /**
  105378. * Sets the flag that indicates if user zooming should stop animation.
  105379. */
  105380. set: function (flag) {
  105381. this._zoomStopsAnimation = flag;
  105382. },
  105383. enumerable: true,
  105384. configurable: true
  105385. });
  105386. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  105387. /**
  105388. * Gets the transition time when framing the mesh, in milliseconds
  105389. */
  105390. get: function () {
  105391. return this._framingTime;
  105392. },
  105393. /**
  105394. * Sets the transition time when framing the mesh, in milliseconds
  105395. */
  105396. set: function (time) {
  105397. this._framingTime = time;
  105398. },
  105399. enumerable: true,
  105400. configurable: true
  105401. });
  105402. FramingBehavior.prototype.init = function () {
  105403. // Do notihng
  105404. };
  105405. FramingBehavior.prototype.attach = function (camera) {
  105406. var _this = this;
  105407. this._attachedCamera = camera;
  105408. var scene = this._attachedCamera.getScene();
  105409. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  105410. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105411. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105412. _this._isPointerDown = true;
  105413. return;
  105414. }
  105415. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105416. _this._isPointerDown = false;
  105417. }
  105418. });
  105419. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105420. if (mesh) {
  105421. _this.zoomOnMesh(mesh);
  105422. }
  105423. });
  105424. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105425. // Stop the animation if there is user interaction and the animation should stop for this interaction
  105426. _this._applyUserInteraction();
  105427. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  105428. // back to the default position after a given timeout
  105429. _this._maintainCameraAboveGround();
  105430. });
  105431. };
  105432. FramingBehavior.prototype.detach = function () {
  105433. if (!this._attachedCamera) {
  105434. return;
  105435. }
  105436. var scene = this._attachedCamera.getScene();
  105437. if (this._onPrePointerObservableObserver) {
  105438. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  105439. }
  105440. if (this._onAfterCheckInputsObserver) {
  105441. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105442. }
  105443. if (this._onMeshTargetChangedObserver) {
  105444. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105445. }
  105446. this._attachedCamera = null;
  105447. };
  105448. /**
  105449. * Targets the given mesh and updates zoom level accordingly.
  105450. * @param mesh The mesh to target.
  105451. * @param radius Optional. If a cached radius position already exists, overrides default.
  105452. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105453. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105454. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105455. */
  105456. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  105457. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105458. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105459. mesh.computeWorldMatrix(true);
  105460. var boundingBox = mesh.getBoundingInfo().boundingBox;
  105461. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  105462. };
  105463. /**
  105464. * Targets the given mesh with its children and updates zoom level accordingly.
  105465. * @param mesh The mesh to target.
  105466. * @param radius Optional. If a cached radius position already exists, overrides default.
  105467. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105468. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105469. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105470. */
  105471. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  105472. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105473. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105474. mesh.computeWorldMatrix(true);
  105475. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  105476. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  105477. };
  105478. /**
  105479. * Targets the given meshes with their children and updates zoom level accordingly.
  105480. * @param meshes The mesh to target.
  105481. * @param radius Optional. If a cached radius position already exists, overrides default.
  105482. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105483. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105484. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105485. */
  105486. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  105487. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105488. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105489. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  105490. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  105491. for (var i = 0; i < meshes.length; i++) {
  105492. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  105493. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  105494. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  105495. }
  105496. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  105497. };
  105498. /**
  105499. * Targets the given mesh and updates zoom level accordingly.
  105500. * @param mesh The mesh to target.
  105501. * @param radius Optional. If a cached radius position already exists, overrides default.
  105502. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105503. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105504. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105505. */
  105506. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  105507. var _this = this;
  105508. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105509. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105510. var zoomTarget;
  105511. if (!this._attachedCamera) {
  105512. return;
  105513. }
  105514. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  105515. var bottom = minimumWorld.y;
  105516. var top = maximumWorld.y;
  105517. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  105518. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  105519. if (focusOnOriginXZ) {
  105520. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  105521. }
  105522. else {
  105523. var centerWorld = minimumWorld.add(radiusWorld);
  105524. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  105525. }
  105526. if (!this._vectorTransition) {
  105527. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  105528. }
  105529. this._betaIsAnimating = true;
  105530. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  105531. if (animatable) {
  105532. this._animatables.push(animatable);
  105533. }
  105534. // sets the radius and lower radius bounds
  105535. // Small delta ensures camera is not always at lower zoom limit.
  105536. var radius = 0;
  105537. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  105538. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105539. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  105540. radius = position;
  105541. }
  105542. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105543. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105544. if (this._attachedCamera.lowerRadiusLimit === null) {
  105545. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  105546. }
  105547. }
  105548. // Set sensibilities
  105549. var extend = maximumWorld.subtract(minimumWorld).length();
  105550. this._attachedCamera.panningSensibility = 5000 / extend;
  105551. this._attachedCamera.wheelPrecision = 100 / radius;
  105552. // transition to new radius
  105553. if (!this._radiusTransition) {
  105554. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105555. }
  105556. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  105557. _this.stopAllAnimations();
  105558. if (onAnimationEnd) {
  105559. onAnimationEnd();
  105560. }
  105561. if (_this._attachedCamera) {
  105562. _this._attachedCamera.storeState();
  105563. }
  105564. });
  105565. if (animatable) {
  105566. this._animatables.push(animatable);
  105567. }
  105568. };
  105569. /**
  105570. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  105571. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  105572. * frustum width.
  105573. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  105574. * to fully enclose the mesh in the viewing frustum.
  105575. */
  105576. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  105577. var size = maximumWorld.subtract(minimumWorld);
  105578. var boxVectorGlobalDiagonal = size.length();
  105579. var frustumSlope = this._getFrustumSlope();
  105580. // Formula for setting distance
  105581. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  105582. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  105583. // Horizon distance
  105584. var radius = radiusWithoutFraming * this._radiusScale;
  105585. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  105586. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  105587. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  105588. var camera = this._attachedCamera;
  105589. if (!camera) {
  105590. return 0;
  105591. }
  105592. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105593. // Don't exceed the requested limit
  105594. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  105595. }
  105596. // Don't exceed the upper radius limit
  105597. if (camera.upperRadiusLimit) {
  105598. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  105599. }
  105600. return distance;
  105601. };
  105602. /**
  105603. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  105604. * is automatically returned to its default position (expected to be above ground plane).
  105605. */
  105606. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  105607. var _this = this;
  105608. if (this._elevationReturnTime < 0) {
  105609. return;
  105610. }
  105611. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  105612. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  105613. var limitBeta = Math.PI * 0.5;
  105614. // Bring the camera back up if below the ground plane
  105615. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  105616. this._betaIsAnimating = true;
  105617. //Transition to new position
  105618. this.stopAllAnimations();
  105619. if (!this._betaTransition) {
  105620. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105621. }
  105622. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  105623. _this._clearAnimationLocks();
  105624. _this.stopAllAnimations();
  105625. });
  105626. if (animatabe) {
  105627. this._animatables.push(animatabe);
  105628. }
  105629. }
  105630. };
  105631. /**
  105632. * Returns the frustum slope based on the canvas ratio and camera FOV
  105633. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  105634. */
  105635. FramingBehavior.prototype._getFrustumSlope = function () {
  105636. // Calculate the viewport ratio
  105637. // Aspect Ratio is Height/Width.
  105638. var camera = this._attachedCamera;
  105639. if (!camera) {
  105640. return BABYLON.Vector2.Zero();
  105641. }
  105642. var engine = camera.getScene().getEngine();
  105643. var aspectRatio = engine.getAspectRatio(camera);
  105644. // Camera FOV is the vertical field of view (top-bottom) in radians.
  105645. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  105646. var frustumSlopeY = Math.tan(camera.fov / 2);
  105647. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  105648. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  105649. // along the forward vector.
  105650. var frustumSlopeX = frustumSlopeY * aspectRatio;
  105651. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  105652. };
  105653. /**
  105654. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  105655. */
  105656. FramingBehavior.prototype._clearAnimationLocks = function () {
  105657. this._betaIsAnimating = false;
  105658. };
  105659. /**
  105660. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105661. */
  105662. FramingBehavior.prototype._applyUserInteraction = function () {
  105663. if (this.isUserIsMoving) {
  105664. this._lastInteractionTime = BABYLON.Tools.Now;
  105665. this.stopAllAnimations();
  105666. this._clearAnimationLocks();
  105667. }
  105668. };
  105669. /**
  105670. * Stops and removes all animations that have been applied to the camera
  105671. */
  105672. FramingBehavior.prototype.stopAllAnimations = function () {
  105673. if (this._attachedCamera) {
  105674. this._attachedCamera.animations = [];
  105675. }
  105676. while (this._animatables.length) {
  105677. if (this._animatables[0]) {
  105678. this._animatables[0].onAnimationEnd = null;
  105679. this._animatables[0].stop();
  105680. }
  105681. this._animatables.shift();
  105682. }
  105683. };
  105684. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  105685. /**
  105686. * Gets a value indicating if the user is moving the camera
  105687. */
  105688. get: function () {
  105689. if (!this._attachedCamera) {
  105690. return false;
  105691. }
  105692. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105693. this._attachedCamera.inertialBetaOffset !== 0 ||
  105694. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105695. this._attachedCamera.inertialPanningX !== 0 ||
  105696. this._attachedCamera.inertialPanningY !== 0 ||
  105697. this._isPointerDown;
  105698. },
  105699. enumerable: true,
  105700. configurable: true
  105701. });
  105702. /**
  105703. * The easing function used by animations
  105704. */
  105705. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  105706. /**
  105707. * The easing mode used by animations
  105708. */
  105709. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  105710. // Statics
  105711. /**
  105712. * The camera can move all the way towards the mesh.
  105713. */
  105714. FramingBehavior.IgnoreBoundsSizeMode = 0;
  105715. /**
  105716. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  105717. */
  105718. FramingBehavior.FitFrustumSidesMode = 1;
  105719. return FramingBehavior;
  105720. }());
  105721. BABYLON.FramingBehavior = FramingBehavior;
  105722. })(BABYLON || (BABYLON = {}));
  105723. //# sourceMappingURL=babylon.framingBehavior.js.map
  105724. var BABYLON;
  105725. (function (BABYLON) {
  105726. /**
  105727. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  105728. */
  105729. var BouncingBehavior = /** @class */ (function () {
  105730. function BouncingBehavior() {
  105731. /**
  105732. * The duration of the animation, in milliseconds
  105733. */
  105734. this.transitionDuration = 450;
  105735. /**
  105736. * Length of the distance animated by the transition when lower radius is reached
  105737. */
  105738. this.lowerRadiusTransitionRange = 2;
  105739. /**
  105740. * Length of the distance animated by the transition when upper radius is reached
  105741. */
  105742. this.upperRadiusTransitionRange = -2;
  105743. this._autoTransitionRange = false;
  105744. // Animations
  105745. this._radiusIsAnimating = false;
  105746. this._radiusBounceTransition = null;
  105747. this._animatables = new Array();
  105748. }
  105749. Object.defineProperty(BouncingBehavior.prototype, "name", {
  105750. get: function () {
  105751. return "Bouncing";
  105752. },
  105753. enumerable: true,
  105754. configurable: true
  105755. });
  105756. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  105757. /**
  105758. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105759. */
  105760. get: function () {
  105761. return this._autoTransitionRange;
  105762. },
  105763. /**
  105764. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105765. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  105766. */
  105767. set: function (value) {
  105768. var _this = this;
  105769. if (this._autoTransitionRange === value) {
  105770. return;
  105771. }
  105772. this._autoTransitionRange = value;
  105773. var camera = this._attachedCamera;
  105774. if (!camera) {
  105775. return;
  105776. }
  105777. if (value) {
  105778. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105779. if (!mesh) {
  105780. return;
  105781. }
  105782. mesh.computeWorldMatrix(true);
  105783. var diagonal = mesh.getBoundingInfo().diagonalLength;
  105784. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  105785. _this.upperRadiusTransitionRange = diagonal * 0.05;
  105786. });
  105787. }
  105788. else if (this._onMeshTargetChangedObserver) {
  105789. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105790. }
  105791. },
  105792. enumerable: true,
  105793. configurable: true
  105794. });
  105795. BouncingBehavior.prototype.init = function () {
  105796. // Do notihng
  105797. };
  105798. BouncingBehavior.prototype.attach = function (camera) {
  105799. var _this = this;
  105800. this._attachedCamera = camera;
  105801. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105802. if (!_this._attachedCamera) {
  105803. return;
  105804. }
  105805. // Add the bounce animation to the lower radius limit
  105806. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  105807. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  105808. }
  105809. // Add the bounce animation to the upper radius limit
  105810. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  105811. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  105812. }
  105813. });
  105814. };
  105815. BouncingBehavior.prototype.detach = function () {
  105816. if (!this._attachedCamera) {
  105817. return;
  105818. }
  105819. if (this._onAfterCheckInputsObserver) {
  105820. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105821. }
  105822. if (this._onMeshTargetChangedObserver) {
  105823. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105824. }
  105825. this._attachedCamera = null;
  105826. };
  105827. /**
  105828. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  105829. * @param radiusLimit The limit to check against.
  105830. * @return Bool to indicate if at limit.
  105831. */
  105832. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  105833. if (!this._attachedCamera) {
  105834. return false;
  105835. }
  105836. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  105837. return true;
  105838. }
  105839. return false;
  105840. };
  105841. /**
  105842. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  105843. * @param radiusDelta The delta by which to animate to. Can be negative.
  105844. */
  105845. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  105846. var _this = this;
  105847. if (!this._attachedCamera) {
  105848. return;
  105849. }
  105850. if (!this._radiusBounceTransition) {
  105851. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  105852. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  105853. }
  105854. // Prevent zoom until bounce has completed
  105855. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  105856. this._attachedCamera.wheelPrecision = Infinity;
  105857. this._attachedCamera.inertialRadiusOffset = 0;
  105858. // Animate to the radius limit
  105859. this.stopAllAnimations();
  105860. this._radiusIsAnimating = true;
  105861. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  105862. if (animatable) {
  105863. this._animatables.push(animatable);
  105864. }
  105865. };
  105866. /**
  105867. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  105868. */
  105869. BouncingBehavior.prototype._clearAnimationLocks = function () {
  105870. this._radiusIsAnimating = false;
  105871. if (this._attachedCamera) {
  105872. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  105873. }
  105874. };
  105875. /**
  105876. * Stops and removes all animations that have been applied to the camera
  105877. */
  105878. BouncingBehavior.prototype.stopAllAnimations = function () {
  105879. if (this._attachedCamera) {
  105880. this._attachedCamera.animations = [];
  105881. }
  105882. while (this._animatables.length) {
  105883. this._animatables[0].onAnimationEnd = null;
  105884. this._animatables[0].stop();
  105885. this._animatables.shift();
  105886. }
  105887. };
  105888. /**
  105889. * The easing function used by animations
  105890. */
  105891. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  105892. /**
  105893. * The easing mode used by animations
  105894. */
  105895. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  105896. return BouncingBehavior;
  105897. }());
  105898. BABYLON.BouncingBehavior = BouncingBehavior;
  105899. })(BABYLON || (BABYLON = {}));
  105900. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  105901. var BABYLON;
  105902. (function (BABYLON) {
  105903. var AutoRotationBehavior = /** @class */ (function () {
  105904. function AutoRotationBehavior() {
  105905. this._zoomStopsAnimation = false;
  105906. this._idleRotationSpeed = 0.05;
  105907. this._idleRotationWaitTime = 2000;
  105908. this._idleRotationSpinupTime = 2000;
  105909. this._isPointerDown = false;
  105910. this._lastFrameTime = null;
  105911. this._lastInteractionTime = -Infinity;
  105912. this._cameraRotationSpeed = 0;
  105913. this._lastFrameRadius = 0;
  105914. }
  105915. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  105916. get: function () {
  105917. return "AutoRotation";
  105918. },
  105919. enumerable: true,
  105920. configurable: true
  105921. });
  105922. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  105923. /**
  105924. * Gets the flag that indicates if user zooming should stop animation.
  105925. */
  105926. get: function () {
  105927. return this._zoomStopsAnimation;
  105928. },
  105929. /**
  105930. * Sets the flag that indicates if user zooming should stop animation.
  105931. */
  105932. set: function (flag) {
  105933. this._zoomStopsAnimation = flag;
  105934. },
  105935. enumerable: true,
  105936. configurable: true
  105937. });
  105938. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  105939. /**
  105940. * Gets the default speed at which the camera rotates around the model.
  105941. */
  105942. get: function () {
  105943. return this._idleRotationSpeed;
  105944. },
  105945. /**
  105946. * Sets the default speed at which the camera rotates around the model.
  105947. */
  105948. set: function (speed) {
  105949. this._idleRotationSpeed = speed;
  105950. },
  105951. enumerable: true,
  105952. configurable: true
  105953. });
  105954. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  105955. /**
  105956. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  105957. */
  105958. get: function () {
  105959. return this._idleRotationWaitTime;
  105960. },
  105961. /**
  105962. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  105963. */
  105964. set: function (time) {
  105965. this._idleRotationWaitTime = time;
  105966. },
  105967. enumerable: true,
  105968. configurable: true
  105969. });
  105970. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  105971. /**
  105972. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105973. */
  105974. get: function () {
  105975. return this._idleRotationSpinupTime;
  105976. },
  105977. /**
  105978. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105979. */
  105980. set: function (time) {
  105981. this._idleRotationSpinupTime = time;
  105982. },
  105983. enumerable: true,
  105984. configurable: true
  105985. });
  105986. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  105987. /**
  105988. * Gets a value indicating if the camera is currently rotating because of this behavior
  105989. */
  105990. get: function () {
  105991. return Math.abs(this._cameraRotationSpeed) > 0;
  105992. },
  105993. enumerable: true,
  105994. configurable: true
  105995. });
  105996. AutoRotationBehavior.prototype.init = function () {
  105997. // Do notihng
  105998. };
  105999. AutoRotationBehavior.prototype.attach = function (camera) {
  106000. var _this = this;
  106001. this._attachedCamera = camera;
  106002. var scene = this._attachedCamera.getScene();
  106003. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  106004. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  106005. _this._isPointerDown = true;
  106006. return;
  106007. }
  106008. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  106009. _this._isPointerDown = false;
  106010. }
  106011. });
  106012. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  106013. var now = BABYLON.Tools.Now;
  106014. var dt = 0;
  106015. if (_this._lastFrameTime != null) {
  106016. dt = now - _this._lastFrameTime;
  106017. }
  106018. _this._lastFrameTime = now;
  106019. // Stop the animation if there is user interaction and the animation should stop for this interaction
  106020. _this._applyUserInteraction();
  106021. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  106022. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  106023. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  106024. // Step camera rotation by rotation speed
  106025. if (_this._attachedCamera) {
  106026. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  106027. }
  106028. });
  106029. };
  106030. AutoRotationBehavior.prototype.detach = function () {
  106031. if (!this._attachedCamera) {
  106032. return;
  106033. }
  106034. var scene = this._attachedCamera.getScene();
  106035. if (this._onPrePointerObservableObserver) {
  106036. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  106037. }
  106038. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  106039. this._attachedCamera = null;
  106040. };
  106041. /**
  106042. * Returns true if user is scrolling.
  106043. * @return true if user is scrolling.
  106044. */
  106045. AutoRotationBehavior.prototype._userIsZooming = function () {
  106046. if (!this._attachedCamera) {
  106047. return false;
  106048. }
  106049. return this._attachedCamera.inertialRadiusOffset !== 0;
  106050. };
  106051. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  106052. if (!this._attachedCamera) {
  106053. return false;
  106054. }
  106055. var zoomHasHitLimit = false;
  106056. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  106057. zoomHasHitLimit = true;
  106058. }
  106059. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  106060. this._lastFrameRadius = this._attachedCamera.radius;
  106061. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  106062. };
  106063. /**
  106064. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  106065. */
  106066. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  106067. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  106068. this._lastInteractionTime = BABYLON.Tools.Now;
  106069. }
  106070. };
  106071. // Tools
  106072. AutoRotationBehavior.prototype._userIsMoving = function () {
  106073. if (!this._attachedCamera) {
  106074. return false;
  106075. }
  106076. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  106077. this._attachedCamera.inertialBetaOffset !== 0 ||
  106078. this._attachedCamera.inertialRadiusOffset !== 0 ||
  106079. this._attachedCamera.inertialPanningX !== 0 ||
  106080. this._attachedCamera.inertialPanningY !== 0 ||
  106081. this._isPointerDown;
  106082. };
  106083. return AutoRotationBehavior;
  106084. }());
  106085. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  106086. })(BABYLON || (BABYLON = {}));
  106087. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  106088. var BABYLON;
  106089. (function (BABYLON) {
  106090. var NullEngineOptions = /** @class */ (function () {
  106091. function NullEngineOptions() {
  106092. this.renderWidth = 512;
  106093. this.renderHeight = 256;
  106094. this.textureSize = 512;
  106095. this.deterministicLockstep = false;
  106096. this.lockstepMaxSteps = 4;
  106097. }
  106098. return NullEngineOptions;
  106099. }());
  106100. BABYLON.NullEngineOptions = NullEngineOptions;
  106101. /**
  106102. * The null engine class provides support for headless version of babylon.js.
  106103. * This can be used in server side scenario or for testing purposes
  106104. */
  106105. var NullEngine = /** @class */ (function (_super) {
  106106. __extends(NullEngine, _super);
  106107. function NullEngine(options) {
  106108. if (options === void 0) { options = new NullEngineOptions(); }
  106109. var _this = _super.call(this, null) || this;
  106110. if (options.deterministicLockstep === undefined) {
  106111. options.deterministicLockstep = false;
  106112. }
  106113. if (options.lockstepMaxSteps === undefined) {
  106114. options.lockstepMaxSteps = 4;
  106115. }
  106116. _this._options = options;
  106117. // Init caps
  106118. // We consider we are on a webgl1 capable device
  106119. _this._caps = new BABYLON.EngineCapabilities();
  106120. _this._caps.maxTexturesImageUnits = 16;
  106121. _this._caps.maxVertexTextureImageUnits = 16;
  106122. _this._caps.maxTextureSize = 512;
  106123. _this._caps.maxCubemapTextureSize = 512;
  106124. _this._caps.maxRenderTextureSize = 512;
  106125. _this._caps.maxVertexAttribs = 16;
  106126. _this._caps.maxVaryingVectors = 16;
  106127. _this._caps.maxFragmentUniformVectors = 16;
  106128. _this._caps.maxVertexUniformVectors = 16;
  106129. // Extensions
  106130. _this._caps.standardDerivatives = false;
  106131. _this._caps.astc = null;
  106132. _this._caps.s3tc = null;
  106133. _this._caps.pvrtc = null;
  106134. _this._caps.etc1 = null;
  106135. _this._caps.etc2 = null;
  106136. _this._caps.textureAnisotropicFilterExtension = null;
  106137. _this._caps.maxAnisotropy = 0;
  106138. _this._caps.uintIndices = false;
  106139. _this._caps.fragmentDepthSupported = false;
  106140. _this._caps.highPrecisionShaderSupported = true;
  106141. _this._caps.colorBufferFloat = false;
  106142. _this._caps.textureFloat = false;
  106143. _this._caps.textureFloatLinearFiltering = false;
  106144. _this._caps.textureFloatRender = false;
  106145. _this._caps.textureHalfFloat = false;
  106146. _this._caps.textureHalfFloatLinearFiltering = false;
  106147. _this._caps.textureHalfFloatRender = false;
  106148. _this._caps.textureLOD = false;
  106149. _this._caps.drawBuffersExtension = false;
  106150. _this._caps.depthTextureExtension = false;
  106151. _this._caps.vertexArrayObject = false;
  106152. _this._caps.instancedArrays = false;
  106153. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  106154. // Wrappers
  106155. if (typeof URL === "undefined") {
  106156. URL = {
  106157. createObjectURL: function () { },
  106158. revokeObjectURL: function () { }
  106159. };
  106160. }
  106161. if (typeof Blob === "undefined") {
  106162. Blob = function () { };
  106163. }
  106164. return _this;
  106165. }
  106166. NullEngine.prototype.isDeterministicLockStep = function () {
  106167. return this._options.deterministicLockstep;
  106168. };
  106169. NullEngine.prototype.getLockstepMaxSteps = function () {
  106170. return this._options.lockstepMaxSteps;
  106171. };
  106172. NullEngine.prototype.getHardwareScalingLevel = function () {
  106173. return 1.0;
  106174. };
  106175. NullEngine.prototype.createVertexBuffer = function (vertices) {
  106176. return {
  106177. capacity: 0,
  106178. references: 1,
  106179. is32Bits: false
  106180. };
  106181. };
  106182. NullEngine.prototype.createIndexBuffer = function (indices) {
  106183. return {
  106184. capacity: 0,
  106185. references: 1,
  106186. is32Bits: false
  106187. };
  106188. };
  106189. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  106190. if (stencil === void 0) { stencil = false; }
  106191. };
  106192. NullEngine.prototype.getRenderWidth = function (useScreen) {
  106193. if (useScreen === void 0) { useScreen = false; }
  106194. if (!useScreen && this._currentRenderTarget) {
  106195. return this._currentRenderTarget.width;
  106196. }
  106197. return this._options.renderWidth;
  106198. };
  106199. NullEngine.prototype.getRenderHeight = function (useScreen) {
  106200. if (useScreen === void 0) { useScreen = false; }
  106201. if (!useScreen && this._currentRenderTarget) {
  106202. return this._currentRenderTarget.height;
  106203. }
  106204. return this._options.renderHeight;
  106205. };
  106206. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  106207. this._cachedViewport = viewport;
  106208. };
  106209. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  106210. return {
  106211. transformFeedback: null,
  106212. __SPECTOR_rebuildProgram: null
  106213. };
  106214. };
  106215. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  106216. return [];
  106217. };
  106218. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  106219. return [];
  106220. };
  106221. NullEngine.prototype.bindSamplers = function (effect) {
  106222. this._currentEffect = null;
  106223. };
  106224. NullEngine.prototype.enableEffect = function (effect) {
  106225. this._currentEffect = effect;
  106226. if (effect.onBind) {
  106227. effect.onBind(effect);
  106228. }
  106229. if (effect._onBindObservable) {
  106230. effect._onBindObservable.notifyObservers(effect);
  106231. }
  106232. };
  106233. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  106234. if (zOffset === void 0) { zOffset = 0; }
  106235. if (reverseSide === void 0) { reverseSide = false; }
  106236. };
  106237. NullEngine.prototype.setIntArray = function (uniform, array) {
  106238. };
  106239. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  106240. };
  106241. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  106242. };
  106243. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  106244. };
  106245. NullEngine.prototype.setFloatArray = function (uniform, array) {
  106246. };
  106247. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  106248. };
  106249. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  106250. };
  106251. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  106252. };
  106253. NullEngine.prototype.setArray = function (uniform, array) {
  106254. };
  106255. NullEngine.prototype.setArray2 = function (uniform, array) {
  106256. };
  106257. NullEngine.prototype.setArray3 = function (uniform, array) {
  106258. };
  106259. NullEngine.prototype.setArray4 = function (uniform, array) {
  106260. };
  106261. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  106262. };
  106263. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  106264. };
  106265. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  106266. };
  106267. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  106268. };
  106269. NullEngine.prototype.setFloat = function (uniform, value) {
  106270. };
  106271. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  106272. };
  106273. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  106274. };
  106275. NullEngine.prototype.setBool = function (uniform, bool) {
  106276. };
  106277. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  106278. };
  106279. NullEngine.prototype.setColor3 = function (uniform, color3) {
  106280. };
  106281. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  106282. };
  106283. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  106284. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  106285. if (this._alphaMode === mode) {
  106286. return;
  106287. }
  106288. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  106289. if (!noDepthWriteChange) {
  106290. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  106291. }
  106292. this._alphaMode = mode;
  106293. };
  106294. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  106295. };
  106296. NullEngine.prototype.wipeCaches = function (bruteForce) {
  106297. if (this.preventCacheWipeBetweenFrames) {
  106298. return;
  106299. }
  106300. this.resetTextureCache();
  106301. this._currentEffect = null;
  106302. if (bruteForce) {
  106303. this._currentProgram = null;
  106304. this._stencilState.reset();
  106305. this._depthCullingState.reset();
  106306. this._alphaState.reset();
  106307. }
  106308. this._cachedVertexBuffers = null;
  106309. this._cachedIndexBuffer = null;
  106310. this._cachedEffectForVertexBuffers = null;
  106311. };
  106312. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  106313. };
  106314. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  106315. };
  106316. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  106317. };
  106318. /** @hidden */
  106319. NullEngine.prototype._createTexture = function () {
  106320. return {};
  106321. };
  106322. /** @hidden */
  106323. NullEngine.prototype._releaseTexture = function (texture) {
  106324. };
  106325. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  106326. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106327. if (onLoad === void 0) { onLoad = null; }
  106328. if (onError === void 0) { onError = null; }
  106329. if (buffer === void 0) { buffer = null; }
  106330. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  106331. var url = String(urlArg);
  106332. texture.url = url;
  106333. texture.generateMipMaps = !noMipmap;
  106334. texture.samplingMode = samplingMode;
  106335. texture.invertY = invertY;
  106336. texture.baseWidth = this._options.textureSize;
  106337. texture.baseHeight = this._options.textureSize;
  106338. texture.width = this._options.textureSize;
  106339. texture.height = this._options.textureSize;
  106340. if (format) {
  106341. texture.format = format;
  106342. }
  106343. texture.isReady = true;
  106344. if (onLoad) {
  106345. onLoad();
  106346. }
  106347. this._internalTexturesCache.push(texture);
  106348. return texture;
  106349. };
  106350. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  106351. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  106352. if (options !== undefined && typeof options === "object") {
  106353. fullOptions.generateMipMaps = options.generateMipMaps;
  106354. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  106355. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  106356. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  106357. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  106358. }
  106359. else {
  106360. fullOptions.generateMipMaps = options;
  106361. fullOptions.generateDepthBuffer = true;
  106362. fullOptions.generateStencilBuffer = false;
  106363. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106364. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  106365. }
  106366. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  106367. var width = size.width || size;
  106368. var height = size.height || size;
  106369. texture._depthStencilBuffer = {};
  106370. texture._framebuffer = {};
  106371. texture.baseWidth = width;
  106372. texture.baseHeight = height;
  106373. texture.width = width;
  106374. texture.height = height;
  106375. texture.isReady = true;
  106376. texture.samples = 1;
  106377. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  106378. texture.samplingMode = fullOptions.samplingMode;
  106379. texture.type = fullOptions.type;
  106380. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  106381. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  106382. this._internalTexturesCache.push(texture);
  106383. return texture;
  106384. };
  106385. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  106386. texture.samplingMode = samplingMode;
  106387. };
  106388. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  106389. if (this._currentRenderTarget) {
  106390. this.unBindFramebuffer(this._currentRenderTarget);
  106391. }
  106392. this._currentRenderTarget = texture;
  106393. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  106394. if (this._cachedViewport && !forceFullscreenViewport) {
  106395. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  106396. }
  106397. };
  106398. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  106399. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  106400. this._currentRenderTarget = null;
  106401. if (onBeforeUnbind) {
  106402. if (texture._MSAAFramebuffer) {
  106403. this._currentFramebuffer = texture._framebuffer;
  106404. }
  106405. onBeforeUnbind();
  106406. }
  106407. this._currentFramebuffer = null;
  106408. };
  106409. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  106410. var vbo = {
  106411. capacity: 1,
  106412. references: 1,
  106413. is32Bits: false
  106414. };
  106415. return vbo;
  106416. };
  106417. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  106418. if (premulAlpha === void 0) { premulAlpha = false; }
  106419. };
  106420. /**
  106421. * @hidden
  106422. * Get the current error code of the webGL context
  106423. * @returns the error code
  106424. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  106425. */
  106426. NullEngine.prototype.getError = function () {
  106427. return 0;
  106428. };
  106429. /** @hidden */
  106430. NullEngine.prototype._getUnpackAlignement = function () {
  106431. return 1;
  106432. };
  106433. /** @hidden */
  106434. NullEngine.prototype._unpackFlipY = function (value) {
  106435. };
  106436. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  106437. if (offset === void 0) { offset = 0; }
  106438. };
  106439. /**
  106440. * Updates a dynamic vertex buffer.
  106441. * @param vertexBuffer the vertex buffer to update
  106442. * @param data the data used to update the vertex buffer
  106443. * @param byteOffset the byte offset of the data (optional)
  106444. * @param byteLength the byte length of the data (optional)
  106445. */
  106446. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  106447. };
  106448. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  106449. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  106450. this._boundTexturesCache[this._activeChannel] = texture;
  106451. return true;
  106452. }
  106453. return false;
  106454. };
  106455. /** @hidden */
  106456. NullEngine.prototype._bindTexture = function (channel, texture) {
  106457. if (channel < 0) {
  106458. return;
  106459. }
  106460. this._bindTextureDirectly(0, texture);
  106461. };
  106462. /** @hidden */
  106463. NullEngine.prototype._releaseBuffer = function (buffer) {
  106464. buffer.references--;
  106465. if (buffer.references === 0) {
  106466. return true;
  106467. }
  106468. return false;
  106469. };
  106470. NullEngine.prototype.releaseEffects = function () {
  106471. };
  106472. NullEngine.prototype.displayLoadingUI = function () {
  106473. };
  106474. NullEngine.prototype.hideLoadingUI = function () {
  106475. };
  106476. /** @hidden */
  106477. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  106478. if (faceIndex === void 0) { faceIndex = 0; }
  106479. if (lod === void 0) { lod = 0; }
  106480. };
  106481. /** @hidden */
  106482. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  106483. if (faceIndex === void 0) { faceIndex = 0; }
  106484. if (lod === void 0) { lod = 0; }
  106485. };
  106486. /** @hidden */
  106487. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  106488. if (faceIndex === void 0) { faceIndex = 0; }
  106489. if (lod === void 0) { lod = 0; }
  106490. };
  106491. /** @hidden */
  106492. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  106493. if (faceIndex === void 0) { faceIndex = 0; }
  106494. if (lod === void 0) { lod = 0; }
  106495. };
  106496. return NullEngine;
  106497. }(BABYLON.Engine));
  106498. BABYLON.NullEngine = NullEngine;
  106499. })(BABYLON || (BABYLON = {}));
  106500. //# sourceMappingURL=babylon.nullEngine.js.map
  106501. var BABYLON;
  106502. (function (BABYLON) {
  106503. /**
  106504. * This class can be used to get instrumentation data from a Babylon engine
  106505. */
  106506. var EngineInstrumentation = /** @class */ (function () {
  106507. function EngineInstrumentation(engine) {
  106508. this.engine = engine;
  106509. this._captureGPUFrameTime = false;
  106510. this._gpuFrameTime = new BABYLON.PerfCounter();
  106511. this._captureShaderCompilationTime = false;
  106512. this._shaderCompilationTime = new BABYLON.PerfCounter();
  106513. // Observers
  106514. this._onBeginFrameObserver = null;
  106515. this._onEndFrameObserver = null;
  106516. this._onBeforeShaderCompilationObserver = null;
  106517. this._onAfterShaderCompilationObserver = null;
  106518. }
  106519. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  106520. // Properties
  106521. /**
  106522. * Gets the perf counter used for GPU frame time
  106523. */
  106524. get: function () {
  106525. return this._gpuFrameTime;
  106526. },
  106527. enumerable: true,
  106528. configurable: true
  106529. });
  106530. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  106531. /**
  106532. * Gets the GPU frame time capture status
  106533. */
  106534. get: function () {
  106535. return this._captureGPUFrameTime;
  106536. },
  106537. /**
  106538. * Enable or disable the GPU frame time capture
  106539. */
  106540. set: function (value) {
  106541. var _this = this;
  106542. if (value === this._captureGPUFrameTime) {
  106543. return;
  106544. }
  106545. this._captureGPUFrameTime = value;
  106546. if (value) {
  106547. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  106548. if (!_this._gpuFrameTimeToken) {
  106549. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  106550. }
  106551. });
  106552. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  106553. if (!_this._gpuFrameTimeToken) {
  106554. return;
  106555. }
  106556. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  106557. if (time > -1) {
  106558. _this._gpuFrameTimeToken = null;
  106559. _this._gpuFrameTime.fetchNewFrame();
  106560. _this._gpuFrameTime.addCount(time, true);
  106561. }
  106562. });
  106563. }
  106564. else {
  106565. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106566. this._onBeginFrameObserver = null;
  106567. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106568. this._onEndFrameObserver = null;
  106569. }
  106570. },
  106571. enumerable: true,
  106572. configurable: true
  106573. });
  106574. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  106575. /**
  106576. * Gets the perf counter used for shader compilation time
  106577. */
  106578. get: function () {
  106579. return this._shaderCompilationTime;
  106580. },
  106581. enumerable: true,
  106582. configurable: true
  106583. });
  106584. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  106585. /**
  106586. * Gets the shader compilation time capture status
  106587. */
  106588. get: function () {
  106589. return this._captureShaderCompilationTime;
  106590. },
  106591. /**
  106592. * Enable or disable the shader compilation time capture
  106593. */
  106594. set: function (value) {
  106595. var _this = this;
  106596. if (value === this._captureShaderCompilationTime) {
  106597. return;
  106598. }
  106599. this._captureShaderCompilationTime = value;
  106600. if (value) {
  106601. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  106602. _this._shaderCompilationTime.fetchNewFrame();
  106603. _this._shaderCompilationTime.beginMonitoring();
  106604. });
  106605. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  106606. _this._shaderCompilationTime.endMonitoring();
  106607. });
  106608. }
  106609. else {
  106610. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106611. this._onBeforeShaderCompilationObserver = null;
  106612. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106613. this._onAfterShaderCompilationObserver = null;
  106614. }
  106615. },
  106616. enumerable: true,
  106617. configurable: true
  106618. });
  106619. EngineInstrumentation.prototype.dispose = function () {
  106620. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106621. this._onBeginFrameObserver = null;
  106622. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106623. this._onEndFrameObserver = null;
  106624. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106625. this._onBeforeShaderCompilationObserver = null;
  106626. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106627. this._onAfterShaderCompilationObserver = null;
  106628. this.engine = null;
  106629. };
  106630. return EngineInstrumentation;
  106631. }());
  106632. BABYLON.EngineInstrumentation = EngineInstrumentation;
  106633. })(BABYLON || (BABYLON = {}));
  106634. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  106635. var BABYLON;
  106636. (function (BABYLON) {
  106637. /**
  106638. * This class can be used to get instrumentation data from a Babylon engine
  106639. */
  106640. var SceneInstrumentation = /** @class */ (function () {
  106641. function SceneInstrumentation(scene) {
  106642. var _this = this;
  106643. this.scene = scene;
  106644. this._captureActiveMeshesEvaluationTime = false;
  106645. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  106646. this._captureRenderTargetsRenderTime = false;
  106647. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  106648. this._captureFrameTime = false;
  106649. this._frameTime = new BABYLON.PerfCounter();
  106650. this._captureRenderTime = false;
  106651. this._renderTime = new BABYLON.PerfCounter();
  106652. this._captureInterFrameTime = false;
  106653. this._interFrameTime = new BABYLON.PerfCounter();
  106654. this._captureParticlesRenderTime = false;
  106655. this._particlesRenderTime = new BABYLON.PerfCounter();
  106656. this._captureSpritesRenderTime = false;
  106657. this._spritesRenderTime = new BABYLON.PerfCounter();
  106658. this._capturePhysicsTime = false;
  106659. this._physicsTime = new BABYLON.PerfCounter();
  106660. this._captureAnimationsTime = false;
  106661. this._animationsTime = new BABYLON.PerfCounter();
  106662. this._captureCameraRenderTime = false;
  106663. this._cameraRenderTime = new BABYLON.PerfCounter();
  106664. // Observers
  106665. this._onBeforeActiveMeshesEvaluationObserver = null;
  106666. this._onAfterActiveMeshesEvaluationObserver = null;
  106667. this._onBeforeRenderTargetsRenderObserver = null;
  106668. this._onAfterRenderTargetsRenderObserver = null;
  106669. this._onAfterRenderObserver = null;
  106670. this._onBeforeDrawPhaseObserver = null;
  106671. this._onAfterDrawPhaseObserver = null;
  106672. this._onBeforeAnimationsObserver = null;
  106673. this._onBeforeParticlesRenderingObserver = null;
  106674. this._onAfterParticlesRenderingObserver = null;
  106675. this._onBeforeSpritesRenderingObserver = null;
  106676. this._onAfterSpritesRenderingObserver = null;
  106677. this._onBeforePhysicsObserver = null;
  106678. this._onAfterPhysicsObserver = null;
  106679. this._onAfterAnimationsObserver = null;
  106680. this._onBeforeCameraRenderObserver = null;
  106681. this._onAfterCameraRenderObserver = null;
  106682. // Before render
  106683. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  106684. if (_this._captureActiveMeshesEvaluationTime) {
  106685. _this._activeMeshesEvaluationTime.fetchNewFrame();
  106686. }
  106687. if (_this._captureRenderTargetsRenderTime) {
  106688. _this._renderTargetsRenderTime.fetchNewFrame();
  106689. }
  106690. if (_this._captureFrameTime) {
  106691. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  106692. _this._frameTime.beginMonitoring();
  106693. }
  106694. if (_this._captureInterFrameTime) {
  106695. _this._interFrameTime.endMonitoring();
  106696. }
  106697. if (_this._captureParticlesRenderTime) {
  106698. _this._particlesRenderTime.fetchNewFrame();
  106699. }
  106700. if (_this._captureSpritesRenderTime) {
  106701. _this._spritesRenderTime.fetchNewFrame();
  106702. }
  106703. if (_this._captureAnimationsTime) {
  106704. _this._animationsTime.beginMonitoring();
  106705. }
  106706. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  106707. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  106708. });
  106709. // After render
  106710. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  106711. if (_this._captureFrameTime) {
  106712. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  106713. _this._frameTime.endMonitoring();
  106714. }
  106715. if (_this._captureRenderTime) {
  106716. _this._renderTime.endMonitoring(false);
  106717. }
  106718. if (_this._captureInterFrameTime) {
  106719. _this._interFrameTime.beginMonitoring();
  106720. }
  106721. });
  106722. }
  106723. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  106724. // Properties
  106725. /**
  106726. * Gets the perf counter used for active meshes evaluation time
  106727. */
  106728. get: function () {
  106729. return this._activeMeshesEvaluationTime;
  106730. },
  106731. enumerable: true,
  106732. configurable: true
  106733. });
  106734. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  106735. /**
  106736. * Gets the active meshes evaluation time capture status
  106737. */
  106738. get: function () {
  106739. return this._captureActiveMeshesEvaluationTime;
  106740. },
  106741. /**
  106742. * Enable or disable the active meshes evaluation time capture
  106743. */
  106744. set: function (value) {
  106745. var _this = this;
  106746. if (value === this._captureActiveMeshesEvaluationTime) {
  106747. return;
  106748. }
  106749. this._captureActiveMeshesEvaluationTime = value;
  106750. if (value) {
  106751. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  106752. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  106753. _this._activeMeshesEvaluationTime.beginMonitoring();
  106754. });
  106755. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  106756. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  106757. _this._activeMeshesEvaluationTime.endMonitoring();
  106758. });
  106759. }
  106760. else {
  106761. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106762. this._onBeforeActiveMeshesEvaluationObserver = null;
  106763. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106764. this._onAfterActiveMeshesEvaluationObserver = null;
  106765. }
  106766. },
  106767. enumerable: true,
  106768. configurable: true
  106769. });
  106770. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  106771. /**
  106772. * Gets the perf counter used for render targets render time
  106773. */
  106774. get: function () {
  106775. return this._renderTargetsRenderTime;
  106776. },
  106777. enumerable: true,
  106778. configurable: true
  106779. });
  106780. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  106781. /**
  106782. * Gets the render targets render time capture status
  106783. */
  106784. get: function () {
  106785. return this._captureRenderTargetsRenderTime;
  106786. },
  106787. /**
  106788. * Enable or disable the render targets render time capture
  106789. */
  106790. set: function (value) {
  106791. var _this = this;
  106792. if (value === this._captureRenderTargetsRenderTime) {
  106793. return;
  106794. }
  106795. this._captureRenderTargetsRenderTime = value;
  106796. if (value) {
  106797. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  106798. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  106799. _this._renderTargetsRenderTime.beginMonitoring();
  106800. });
  106801. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  106802. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  106803. _this._renderTargetsRenderTime.endMonitoring(false);
  106804. });
  106805. }
  106806. else {
  106807. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106808. this._onBeforeRenderTargetsRenderObserver = null;
  106809. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106810. this._onAfterRenderTargetsRenderObserver = null;
  106811. }
  106812. },
  106813. enumerable: true,
  106814. configurable: true
  106815. });
  106816. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  106817. /**
  106818. * Gets the perf counter used for particles render time
  106819. */
  106820. get: function () {
  106821. return this._particlesRenderTime;
  106822. },
  106823. enumerable: true,
  106824. configurable: true
  106825. });
  106826. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  106827. /**
  106828. * Gets the particles render time capture status
  106829. */
  106830. get: function () {
  106831. return this._captureParticlesRenderTime;
  106832. },
  106833. /**
  106834. * Enable or disable the particles render time capture
  106835. */
  106836. set: function (value) {
  106837. var _this = this;
  106838. if (value === this._captureParticlesRenderTime) {
  106839. return;
  106840. }
  106841. this._captureParticlesRenderTime = value;
  106842. if (value) {
  106843. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  106844. BABYLON.Tools.StartPerformanceCounter("Particles");
  106845. _this._particlesRenderTime.beginMonitoring();
  106846. });
  106847. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  106848. BABYLON.Tools.EndPerformanceCounter("Particles");
  106849. _this._particlesRenderTime.endMonitoring(false);
  106850. });
  106851. }
  106852. else {
  106853. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106854. this._onBeforeParticlesRenderingObserver = null;
  106855. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106856. this._onAfterParticlesRenderingObserver = null;
  106857. }
  106858. },
  106859. enumerable: true,
  106860. configurable: true
  106861. });
  106862. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  106863. /**
  106864. * Gets the perf counter used for sprites render time
  106865. */
  106866. get: function () {
  106867. return this._spritesRenderTime;
  106868. },
  106869. enumerable: true,
  106870. configurable: true
  106871. });
  106872. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  106873. /**
  106874. * Gets the sprites render time capture status
  106875. */
  106876. get: function () {
  106877. return this._captureSpritesRenderTime;
  106878. },
  106879. /**
  106880. * Enable or disable the sprites render time capture
  106881. */
  106882. set: function (value) {
  106883. var _this = this;
  106884. if (value === this._captureSpritesRenderTime) {
  106885. return;
  106886. }
  106887. this._captureSpritesRenderTime = value;
  106888. if (!this.scene.spriteManagers) {
  106889. return;
  106890. }
  106891. if (value) {
  106892. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  106893. BABYLON.Tools.StartPerformanceCounter("Sprites");
  106894. _this._spritesRenderTime.beginMonitoring();
  106895. });
  106896. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  106897. BABYLON.Tools.EndPerformanceCounter("Sprites");
  106898. _this._spritesRenderTime.endMonitoring(false);
  106899. });
  106900. }
  106901. else {
  106902. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106903. this._onBeforeSpritesRenderingObserver = null;
  106904. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106905. this._onAfterSpritesRenderingObserver = null;
  106906. }
  106907. },
  106908. enumerable: true,
  106909. configurable: true
  106910. });
  106911. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  106912. /**
  106913. * Gets the perf counter used for physics time
  106914. */
  106915. get: function () {
  106916. return this._physicsTime;
  106917. },
  106918. enumerable: true,
  106919. configurable: true
  106920. });
  106921. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  106922. /**
  106923. * Gets the physics time capture status
  106924. */
  106925. get: function () {
  106926. return this._capturePhysicsTime;
  106927. },
  106928. /**
  106929. * Enable or disable the physics time capture
  106930. */
  106931. set: function (value) {
  106932. var _this = this;
  106933. if (value === this._capturePhysicsTime) {
  106934. return;
  106935. }
  106936. if (!this.scene.onBeforePhysicsObservable) {
  106937. return;
  106938. }
  106939. this._capturePhysicsTime = value;
  106940. if (value) {
  106941. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  106942. BABYLON.Tools.StartPerformanceCounter("Physics");
  106943. _this._physicsTime.beginMonitoring();
  106944. });
  106945. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  106946. BABYLON.Tools.EndPerformanceCounter("Physics");
  106947. _this._physicsTime.endMonitoring();
  106948. });
  106949. }
  106950. else {
  106951. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106952. this._onBeforePhysicsObserver = null;
  106953. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106954. this._onAfterPhysicsObserver = null;
  106955. }
  106956. },
  106957. enumerable: true,
  106958. configurable: true
  106959. });
  106960. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  106961. /**
  106962. * Gets the perf counter used for animations time
  106963. */
  106964. get: function () {
  106965. return this._animationsTime;
  106966. },
  106967. enumerable: true,
  106968. configurable: true
  106969. });
  106970. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  106971. /**
  106972. * Gets the animations time capture status
  106973. */
  106974. get: function () {
  106975. return this._captureAnimationsTime;
  106976. },
  106977. /**
  106978. * Enable or disable the animations time capture
  106979. */
  106980. set: function (value) {
  106981. var _this = this;
  106982. if (value === this._captureAnimationsTime) {
  106983. return;
  106984. }
  106985. this._captureAnimationsTime = value;
  106986. if (value) {
  106987. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  106988. _this._animationsTime.endMonitoring();
  106989. });
  106990. }
  106991. else {
  106992. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106993. this._onAfterAnimationsObserver = null;
  106994. }
  106995. },
  106996. enumerable: true,
  106997. configurable: true
  106998. });
  106999. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  107000. /**
  107001. * Gets the perf counter used for frame time capture
  107002. */
  107003. get: function () {
  107004. return this._frameTime;
  107005. },
  107006. enumerable: true,
  107007. configurable: true
  107008. });
  107009. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  107010. /**
  107011. * Gets the frame time capture status
  107012. */
  107013. get: function () {
  107014. return this._captureFrameTime;
  107015. },
  107016. /**
  107017. * Enable or disable the frame time capture
  107018. */
  107019. set: function (value) {
  107020. this._captureFrameTime = value;
  107021. },
  107022. enumerable: true,
  107023. configurable: true
  107024. });
  107025. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  107026. /**
  107027. * Gets the perf counter used for inter-frames time capture
  107028. */
  107029. get: function () {
  107030. return this._interFrameTime;
  107031. },
  107032. enumerable: true,
  107033. configurable: true
  107034. });
  107035. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  107036. /**
  107037. * Gets the inter-frames time capture status
  107038. */
  107039. get: function () {
  107040. return this._captureInterFrameTime;
  107041. },
  107042. /**
  107043. * Enable or disable the inter-frames time capture
  107044. */
  107045. set: function (value) {
  107046. this._captureInterFrameTime = value;
  107047. },
  107048. enumerable: true,
  107049. configurable: true
  107050. });
  107051. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  107052. /**
  107053. * Gets the perf counter used for render time capture
  107054. */
  107055. get: function () {
  107056. return this._renderTime;
  107057. },
  107058. enumerable: true,
  107059. configurable: true
  107060. });
  107061. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  107062. /**
  107063. * Gets the render time capture status
  107064. */
  107065. get: function () {
  107066. return this._captureRenderTime;
  107067. },
  107068. /**
  107069. * Enable or disable the render time capture
  107070. */
  107071. set: function (value) {
  107072. var _this = this;
  107073. if (value === this._captureRenderTime) {
  107074. return;
  107075. }
  107076. this._captureRenderTime = value;
  107077. if (value) {
  107078. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  107079. _this._renderTime.beginMonitoring();
  107080. BABYLON.Tools.StartPerformanceCounter("Main render");
  107081. });
  107082. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  107083. _this._renderTime.endMonitoring(false);
  107084. BABYLON.Tools.EndPerformanceCounter("Main render");
  107085. });
  107086. }
  107087. else {
  107088. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  107089. this._onBeforeDrawPhaseObserver = null;
  107090. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  107091. this._onAfterDrawPhaseObserver = null;
  107092. }
  107093. },
  107094. enumerable: true,
  107095. configurable: true
  107096. });
  107097. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  107098. /**
  107099. * Gets the perf counter used for camera render time capture
  107100. */
  107101. get: function () {
  107102. return this._cameraRenderTime;
  107103. },
  107104. enumerable: true,
  107105. configurable: true
  107106. });
  107107. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  107108. /**
  107109. * Gets the camera render time capture status
  107110. */
  107111. get: function () {
  107112. return this._captureCameraRenderTime;
  107113. },
  107114. /**
  107115. * Enable or disable the camera render time capture
  107116. */
  107117. set: function (value) {
  107118. var _this = this;
  107119. if (value === this._captureCameraRenderTime) {
  107120. return;
  107121. }
  107122. this._captureCameraRenderTime = value;
  107123. if (value) {
  107124. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  107125. _this._cameraRenderTime.beginMonitoring();
  107126. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  107127. });
  107128. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  107129. _this._cameraRenderTime.endMonitoring(false);
  107130. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  107131. });
  107132. }
  107133. else {
  107134. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  107135. this._onBeforeCameraRenderObserver = null;
  107136. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  107137. this._onAfterCameraRenderObserver = null;
  107138. }
  107139. },
  107140. enumerable: true,
  107141. configurable: true
  107142. });
  107143. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  107144. /**
  107145. * Gets the perf counter used for draw calls
  107146. */
  107147. get: function () {
  107148. return this.scene.getEngine()._drawCalls;
  107149. },
  107150. enumerable: true,
  107151. configurable: true
  107152. });
  107153. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  107154. /**
  107155. * Gets the perf counter used for texture collisions
  107156. */
  107157. get: function () {
  107158. return this.scene.getEngine()._textureCollisions;
  107159. },
  107160. enumerable: true,
  107161. configurable: true
  107162. });
  107163. SceneInstrumentation.prototype.dispose = function () {
  107164. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  107165. this._onAfterRenderObserver = null;
  107166. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  107167. this._onBeforeActiveMeshesEvaluationObserver = null;
  107168. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  107169. this._onAfterActiveMeshesEvaluationObserver = null;
  107170. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  107171. this._onBeforeRenderTargetsRenderObserver = null;
  107172. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  107173. this._onAfterRenderTargetsRenderObserver = null;
  107174. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  107175. this._onBeforeAnimationsObserver = null;
  107176. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  107177. this._onBeforeParticlesRenderingObserver = null;
  107178. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  107179. this._onAfterParticlesRenderingObserver = null;
  107180. if (this._onBeforeSpritesRenderingObserver) {
  107181. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  107182. this._onBeforeSpritesRenderingObserver = null;
  107183. }
  107184. if (this._onAfterSpritesRenderingObserver) {
  107185. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  107186. this._onAfterSpritesRenderingObserver = null;
  107187. }
  107188. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  107189. this._onBeforeDrawPhaseObserver = null;
  107190. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  107191. this._onAfterDrawPhaseObserver = null;
  107192. if (this._onBeforePhysicsObserver) {
  107193. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  107194. this._onBeforePhysicsObserver = null;
  107195. }
  107196. if (this._onAfterPhysicsObserver) {
  107197. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  107198. this._onAfterPhysicsObserver = null;
  107199. }
  107200. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  107201. this._onAfterAnimationsObserver = null;
  107202. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  107203. this._onBeforeCameraRenderObserver = null;
  107204. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  107205. this._onAfterCameraRenderObserver = null;
  107206. this.scene = null;
  107207. };
  107208. return SceneInstrumentation;
  107209. }());
  107210. BABYLON.SceneInstrumentation = SceneInstrumentation;
  107211. })(BABYLON || (BABYLON = {}));
  107212. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  107213. var BABYLON;
  107214. (function (BABYLON) {
  107215. /**
  107216. * @hidden
  107217. **/
  107218. var _TimeToken = /** @class */ (function () {
  107219. function _TimeToken() {
  107220. this._timeElapsedQueryEnded = false;
  107221. }
  107222. return _TimeToken;
  107223. }());
  107224. BABYLON._TimeToken = _TimeToken;
  107225. })(BABYLON || (BABYLON = {}));
  107226. //# sourceMappingURL=babylon.timeToken.js.map
  107227. var BABYLON;
  107228. (function (BABYLON) {
  107229. /**
  107230. * Background material defines definition.
  107231. * @hidden Mainly internal Use
  107232. */
  107233. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  107234. __extends(BackgroundMaterialDefines, _super);
  107235. /**
  107236. * Constructor of the defines.
  107237. */
  107238. function BackgroundMaterialDefines() {
  107239. var _this = _super.call(this) || this;
  107240. /**
  107241. * True if the diffuse texture is in use.
  107242. */
  107243. _this.DIFFUSE = false;
  107244. /**
  107245. * The direct UV channel to use.
  107246. */
  107247. _this.DIFFUSEDIRECTUV = 0;
  107248. /**
  107249. * True if the diffuse texture is in gamma space.
  107250. */
  107251. _this.GAMMADIFFUSE = false;
  107252. /**
  107253. * True if the diffuse texture has opacity in the alpha channel.
  107254. */
  107255. _this.DIFFUSEHASALPHA = false;
  107256. /**
  107257. * True if you want the material to fade to transparent at grazing angle.
  107258. */
  107259. _this.OPACITYFRESNEL = false;
  107260. /**
  107261. * True if an extra blur needs to be added in the reflection.
  107262. */
  107263. _this.REFLECTIONBLUR = false;
  107264. /**
  107265. * True if you want the material to fade to reflection at grazing angle.
  107266. */
  107267. _this.REFLECTIONFRESNEL = false;
  107268. /**
  107269. * True if you want the material to falloff as far as you move away from the scene center.
  107270. */
  107271. _this.REFLECTIONFALLOFF = false;
  107272. /**
  107273. * False if the current Webgl implementation does not support the texture lod extension.
  107274. */
  107275. _this.TEXTURELODSUPPORT = false;
  107276. /**
  107277. * True to ensure the data are premultiplied.
  107278. */
  107279. _this.PREMULTIPLYALPHA = false;
  107280. /**
  107281. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  107282. */
  107283. _this.USERGBCOLOR = false;
  107284. /**
  107285. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  107286. * stays aligned with the desired configuration.
  107287. */
  107288. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  107289. /**
  107290. * True to add noise in order to reduce the banding effect.
  107291. */
  107292. _this.NOISE = false;
  107293. /**
  107294. * is the reflection texture in BGR color scheme?
  107295. * Mainly used to solve a bug in ios10 video tag
  107296. */
  107297. _this.REFLECTIONBGR = false;
  107298. _this.IMAGEPROCESSING = false;
  107299. _this.VIGNETTE = false;
  107300. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  107301. _this.VIGNETTEBLENDMODEOPAQUE = false;
  107302. _this.TONEMAPPING = false;
  107303. _this.TONEMAPPING_ACES = false;
  107304. _this.CONTRAST = false;
  107305. _this.COLORCURVES = false;
  107306. _this.COLORGRADING = false;
  107307. _this.COLORGRADING3D = false;
  107308. _this.SAMPLER3DGREENDEPTH = false;
  107309. _this.SAMPLER3DBGRMAP = false;
  107310. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  107311. _this.EXPOSURE = false;
  107312. // Reflection.
  107313. _this.REFLECTION = false;
  107314. _this.REFLECTIONMAP_3D = false;
  107315. _this.REFLECTIONMAP_SPHERICAL = false;
  107316. _this.REFLECTIONMAP_PLANAR = false;
  107317. _this.REFLECTIONMAP_CUBIC = false;
  107318. _this.REFLECTIONMAP_PROJECTION = false;
  107319. _this.REFLECTIONMAP_SKYBOX = false;
  107320. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107321. _this.REFLECTIONMAP_EXPLICIT = false;
  107322. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107323. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107324. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107325. _this.INVERTCUBICMAP = false;
  107326. _this.REFLECTIONMAP_OPPOSITEZ = false;
  107327. _this.LODINREFLECTIONALPHA = false;
  107328. _this.GAMMAREFLECTION = false;
  107329. _this.RGBDREFLECTION = false;
  107330. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  107331. // Default BJS.
  107332. _this.MAINUV1 = false;
  107333. _this.MAINUV2 = false;
  107334. _this.UV1 = false;
  107335. _this.UV2 = false;
  107336. _this.CLIPPLANE = false;
  107337. _this.CLIPPLANE2 = false;
  107338. _this.CLIPPLANE3 = false;
  107339. _this.CLIPPLANE4 = false;
  107340. _this.POINTSIZE = false;
  107341. _this.FOG = false;
  107342. _this.NORMAL = false;
  107343. _this.NUM_BONE_INFLUENCERS = 0;
  107344. _this.BonesPerMesh = 0;
  107345. _this.INSTANCES = false;
  107346. _this.SHADOWFLOAT = false;
  107347. _this.rebuild();
  107348. return _this;
  107349. }
  107350. return BackgroundMaterialDefines;
  107351. }(BABYLON.MaterialDefines));
  107352. /**
  107353. * Background material used to create an efficient environement around your scene.
  107354. */
  107355. var BackgroundMaterial = /** @class */ (function (_super) {
  107356. __extends(BackgroundMaterial, _super);
  107357. /**
  107358. * Instantiates a Background Material in the given scene
  107359. * @param name The friendly name of the material
  107360. * @param scene The scene to add the material to
  107361. */
  107362. function BackgroundMaterial(name, scene) {
  107363. var _this = _super.call(this, name, scene) || this;
  107364. /**
  107365. * Key light Color (multiply against the environement texture)
  107366. */
  107367. _this.primaryColor = BABYLON.Color3.White();
  107368. _this._primaryColorShadowLevel = 0;
  107369. _this._primaryColorHighlightLevel = 0;
  107370. /**
  107371. * Reflection Texture used in the material.
  107372. * Should be author in a specific way for the best result (refer to the documentation).
  107373. */
  107374. _this.reflectionTexture = null;
  107375. /**
  107376. * Reflection Texture level of blur.
  107377. *
  107378. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  107379. * texture twice.
  107380. */
  107381. _this.reflectionBlur = 0;
  107382. /**
  107383. * Diffuse Texture used in the material.
  107384. * Should be author in a specific way for the best result (refer to the documentation).
  107385. */
  107386. _this.diffuseTexture = null;
  107387. _this._shadowLights = null;
  107388. /**
  107389. * Specify the list of lights casting shadow on the material.
  107390. * All scene shadow lights will be included if null.
  107391. */
  107392. _this.shadowLights = null;
  107393. /**
  107394. * Helps adjusting the shadow to a softer level if required.
  107395. * 0 means black shadows and 1 means no shadows.
  107396. */
  107397. _this.shadowLevel = 0;
  107398. /**
  107399. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  107400. * It is usually zero but might be interesting to modify according to your setup.
  107401. */
  107402. _this.sceneCenter = BABYLON.Vector3.Zero();
  107403. /**
  107404. * This helps specifying that the material is falling off to the sky box at grazing angle.
  107405. * This helps ensuring a nice transition when the camera goes under the ground.
  107406. */
  107407. _this.opacityFresnel = true;
  107408. /**
  107409. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  107410. * This helps adding a mirror texture on the ground.
  107411. */
  107412. _this.reflectionFresnel = false;
  107413. /**
  107414. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  107415. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  107416. */
  107417. _this.reflectionFalloffDistance = 0.0;
  107418. /**
  107419. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  107420. */
  107421. _this.reflectionAmount = 1.0;
  107422. /**
  107423. * This specifies the weight of the reflection at grazing angle.
  107424. */
  107425. _this.reflectionReflectance0 = 0.05;
  107426. /**
  107427. * This specifies the weight of the reflection at a perpendicular point of view.
  107428. */
  107429. _this.reflectionReflectance90 = 0.5;
  107430. /**
  107431. * Helps to directly use the maps channels instead of their level.
  107432. */
  107433. _this.useRGBColor = true;
  107434. /**
  107435. * This helps reducing the banding effect that could occur on the background.
  107436. */
  107437. _this.enableNoise = false;
  107438. _this._fovMultiplier = 1.0;
  107439. /**
  107440. * Enable the FOV adjustment feature controlled by fovMultiplier.
  107441. */
  107442. _this.useEquirectangularFOV = false;
  107443. _this._maxSimultaneousLights = 4;
  107444. /**
  107445. * Number of Simultaneous lights allowed on the material.
  107446. */
  107447. _this.maxSimultaneousLights = 4;
  107448. /**
  107449. * Keep track of the image processing observer to allow dispose and replace.
  107450. */
  107451. _this._imageProcessingObserver = null;
  107452. /**
  107453. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  107454. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  107455. */
  107456. _this.switchToBGR = false;
  107457. // Temp values kept as cache in the material.
  107458. _this._renderTargets = new BABYLON.SmartArray(16);
  107459. _this._reflectionControls = BABYLON.Vector4.Zero();
  107460. _this._white = BABYLON.Color3.White();
  107461. _this._primaryShadowColor = BABYLON.Color3.Black();
  107462. _this._primaryHighlightColor = BABYLON.Color3.Black();
  107463. // Setup the default processing configuration to the scene.
  107464. _this._attachImageProcessingConfiguration(null);
  107465. _this.getRenderTargetTextures = function () {
  107466. _this._renderTargets.reset();
  107467. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  107468. _this._renderTargets.push(_this._diffuseTexture);
  107469. }
  107470. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  107471. _this._renderTargets.push(_this._reflectionTexture);
  107472. }
  107473. return _this._renderTargets;
  107474. };
  107475. return _this;
  107476. }
  107477. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  107478. /**
  107479. * Experimental Internal Use Only.
  107480. *
  107481. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  107482. * This acts as a helper to set the primary color to a more "human friendly" value.
  107483. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  107484. * output color as close as possible from the chosen value.
  107485. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  107486. * part of lighting setup.)
  107487. */
  107488. get: function () {
  107489. return this.__perceptualColor;
  107490. },
  107491. set: function (value) {
  107492. this.__perceptualColor = value;
  107493. this._computePrimaryColorFromPerceptualColor();
  107494. this._markAllSubMeshesAsLightsDirty();
  107495. },
  107496. enumerable: true,
  107497. configurable: true
  107498. });
  107499. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  107500. /**
  107501. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  107502. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  107503. */
  107504. get: function () {
  107505. return this._primaryColorShadowLevel;
  107506. },
  107507. set: function (value) {
  107508. this._primaryColorShadowLevel = value;
  107509. this._computePrimaryColors();
  107510. this._markAllSubMeshesAsLightsDirty();
  107511. },
  107512. enumerable: true,
  107513. configurable: true
  107514. });
  107515. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  107516. /**
  107517. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  107518. * The primary color is used at the level chosen to define what the white area would look.
  107519. */
  107520. get: function () {
  107521. return this._primaryColorHighlightLevel;
  107522. },
  107523. set: function (value) {
  107524. this._primaryColorHighlightLevel = value;
  107525. this._computePrimaryColors();
  107526. this._markAllSubMeshesAsLightsDirty();
  107527. },
  107528. enumerable: true,
  107529. configurable: true
  107530. });
  107531. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  107532. /**
  107533. * Sets the reflection reflectance fresnel values according to the default standard
  107534. * empirically know to work well :-)
  107535. */
  107536. set: function (value) {
  107537. var reflectionWeight = value;
  107538. if (reflectionWeight < 0.5) {
  107539. reflectionWeight = reflectionWeight * 2.0;
  107540. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  107541. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  107542. }
  107543. else {
  107544. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  107545. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  107546. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  107547. }
  107548. },
  107549. enumerable: true,
  107550. configurable: true
  107551. });
  107552. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  107553. /**
  107554. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107555. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  107556. * Recommended to be keep at 1.0 except for special cases.
  107557. */
  107558. get: function () {
  107559. return this._fovMultiplier;
  107560. },
  107561. set: function (value) {
  107562. if (isNaN(value)) {
  107563. value = 1.0;
  107564. }
  107565. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  107566. },
  107567. enumerable: true,
  107568. configurable: true
  107569. });
  107570. /**
  107571. * Attaches a new image processing configuration to the PBR Material.
  107572. * @param configuration (if null the scene configuration will be use)
  107573. */
  107574. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  107575. var _this = this;
  107576. if (configuration === this._imageProcessingConfiguration) {
  107577. return;
  107578. }
  107579. // Detaches observer.
  107580. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107581. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107582. }
  107583. // Pick the scene configuration if needed.
  107584. if (!configuration) {
  107585. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  107586. }
  107587. else {
  107588. this._imageProcessingConfiguration = configuration;
  107589. }
  107590. // Attaches observer.
  107591. if (this._imageProcessingConfiguration) {
  107592. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  107593. _this._computePrimaryColorFromPerceptualColor();
  107594. _this._markAllSubMeshesAsImageProcessingDirty();
  107595. });
  107596. }
  107597. };
  107598. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  107599. /**
  107600. * Gets the image processing configuration used either in this material.
  107601. */
  107602. get: function () {
  107603. return this._imageProcessingConfiguration;
  107604. },
  107605. /**
  107606. * Sets the Default image processing configuration used either in the this material.
  107607. *
  107608. * If sets to null, the scene one is in use.
  107609. */
  107610. set: function (value) {
  107611. this._attachImageProcessingConfiguration(value);
  107612. // Ensure the effect will be rebuilt.
  107613. this._markAllSubMeshesAsTexturesDirty();
  107614. },
  107615. enumerable: true,
  107616. configurable: true
  107617. });
  107618. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  107619. /**
  107620. * Gets wether the color curves effect is enabled.
  107621. */
  107622. get: function () {
  107623. return this.imageProcessingConfiguration.colorCurvesEnabled;
  107624. },
  107625. /**
  107626. * Sets wether the color curves effect is enabled.
  107627. */
  107628. set: function (value) {
  107629. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  107630. },
  107631. enumerable: true,
  107632. configurable: true
  107633. });
  107634. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  107635. /**
  107636. * Gets wether the color grading effect is enabled.
  107637. */
  107638. get: function () {
  107639. return this.imageProcessingConfiguration.colorGradingEnabled;
  107640. },
  107641. /**
  107642. * Gets wether the color grading effect is enabled.
  107643. */
  107644. set: function (value) {
  107645. this.imageProcessingConfiguration.colorGradingEnabled = value;
  107646. },
  107647. enumerable: true,
  107648. configurable: true
  107649. });
  107650. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  107651. /**
  107652. * Gets wether tonemapping is enabled or not.
  107653. */
  107654. get: function () {
  107655. return this._imageProcessingConfiguration.toneMappingEnabled;
  107656. },
  107657. /**
  107658. * Sets wether tonemapping is enabled or not
  107659. */
  107660. set: function (value) {
  107661. this._imageProcessingConfiguration.toneMappingEnabled = value;
  107662. },
  107663. enumerable: true,
  107664. configurable: true
  107665. });
  107666. ;
  107667. ;
  107668. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  107669. /**
  107670. * The camera exposure used on this material.
  107671. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107672. * This corresponds to a photographic exposure.
  107673. */
  107674. get: function () {
  107675. return this._imageProcessingConfiguration.exposure;
  107676. },
  107677. /**
  107678. * The camera exposure used on this material.
  107679. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107680. * This corresponds to a photographic exposure.
  107681. */
  107682. set: function (value) {
  107683. this._imageProcessingConfiguration.exposure = value;
  107684. },
  107685. enumerable: true,
  107686. configurable: true
  107687. });
  107688. ;
  107689. ;
  107690. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  107691. /**
  107692. * Gets The camera contrast used on this material.
  107693. */
  107694. get: function () {
  107695. return this._imageProcessingConfiguration.contrast;
  107696. },
  107697. /**
  107698. * Sets The camera contrast used on this material.
  107699. */
  107700. set: function (value) {
  107701. this._imageProcessingConfiguration.contrast = value;
  107702. },
  107703. enumerable: true,
  107704. configurable: true
  107705. });
  107706. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  107707. /**
  107708. * Gets the Color Grading 2D Lookup Texture.
  107709. */
  107710. get: function () {
  107711. return this._imageProcessingConfiguration.colorGradingTexture;
  107712. },
  107713. /**
  107714. * Sets the Color Grading 2D Lookup Texture.
  107715. */
  107716. set: function (value) {
  107717. this.imageProcessingConfiguration.colorGradingTexture = value;
  107718. },
  107719. enumerable: true,
  107720. configurable: true
  107721. });
  107722. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  107723. /**
  107724. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107725. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107726. * 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;
  107727. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107728. */
  107729. get: function () {
  107730. return this.imageProcessingConfiguration.colorCurves;
  107731. },
  107732. /**
  107733. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107734. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107735. * 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;
  107736. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107737. */
  107738. set: function (value) {
  107739. this.imageProcessingConfiguration.colorCurves = value;
  107740. },
  107741. enumerable: true,
  107742. configurable: true
  107743. });
  107744. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  107745. /**
  107746. * Gets a boolean indicating that current material needs to register RTT
  107747. */
  107748. get: function () {
  107749. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107750. return true;
  107751. }
  107752. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107753. return true;
  107754. }
  107755. return false;
  107756. },
  107757. enumerable: true,
  107758. configurable: true
  107759. });
  107760. /**
  107761. * The entire material has been created in order to prevent overdraw.
  107762. * @returns false
  107763. */
  107764. BackgroundMaterial.prototype.needAlphaTesting = function () {
  107765. return true;
  107766. };
  107767. /**
  107768. * The entire material has been created in order to prevent overdraw.
  107769. * @returns true if blending is enable
  107770. */
  107771. BackgroundMaterial.prototype.needAlphaBlending = function () {
  107772. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  107773. };
  107774. /**
  107775. * Checks wether the material is ready to be rendered for a given mesh.
  107776. * @param mesh The mesh to render
  107777. * @param subMesh The submesh to check against
  107778. * @param useInstances Specify wether or not the material is used with instances
  107779. * @returns true if all the dependencies are ready (Textures, Effects...)
  107780. */
  107781. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  107782. var _this = this;
  107783. if (useInstances === void 0) { useInstances = false; }
  107784. if (subMesh.effect && this.isFrozen) {
  107785. if (this._wasPreviouslyReady) {
  107786. return true;
  107787. }
  107788. }
  107789. if (!subMesh._materialDefines) {
  107790. subMesh._materialDefines = new BackgroundMaterialDefines();
  107791. }
  107792. var scene = this.getScene();
  107793. var defines = subMesh._materialDefines;
  107794. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  107795. if (defines._renderId === scene.getRenderId()) {
  107796. return true;
  107797. }
  107798. }
  107799. var engine = scene.getEngine();
  107800. // Lights
  107801. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  107802. defines._needNormals = true;
  107803. // Textures
  107804. if (defines._areTexturesDirty) {
  107805. defines._needUVs = false;
  107806. if (scene.texturesEnabled) {
  107807. if (scene.getEngine().getCaps().textureLOD) {
  107808. defines.TEXTURELODSUPPORT = true;
  107809. }
  107810. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107811. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  107812. return false;
  107813. }
  107814. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  107815. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  107816. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  107817. defines.OPACITYFRESNEL = this._opacityFresnel;
  107818. }
  107819. else {
  107820. defines.DIFFUSE = false;
  107821. defines.DIFFUSEHASALPHA = false;
  107822. defines.GAMMADIFFUSE = false;
  107823. defines.OPACITYFRESNEL = false;
  107824. }
  107825. var reflectionTexture = this._reflectionTexture;
  107826. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107827. if (!reflectionTexture.isReadyOrNotBlocking()) {
  107828. return false;
  107829. }
  107830. defines.REFLECTION = true;
  107831. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  107832. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  107833. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  107834. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  107835. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  107836. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  107837. defines.REFLECTIONBGR = this.switchToBGR;
  107838. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  107839. defines.INVERTCUBICMAP = true;
  107840. }
  107841. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  107842. switch (reflectionTexture.coordinatesMode) {
  107843. case BABYLON.Texture.EXPLICIT_MODE:
  107844. defines.REFLECTIONMAP_EXPLICIT = true;
  107845. break;
  107846. case BABYLON.Texture.PLANAR_MODE:
  107847. defines.REFLECTIONMAP_PLANAR = true;
  107848. break;
  107849. case BABYLON.Texture.PROJECTION_MODE:
  107850. defines.REFLECTIONMAP_PROJECTION = true;
  107851. break;
  107852. case BABYLON.Texture.SKYBOX_MODE:
  107853. defines.REFLECTIONMAP_SKYBOX = true;
  107854. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  107855. break;
  107856. case BABYLON.Texture.SPHERICAL_MODE:
  107857. defines.REFLECTIONMAP_SPHERICAL = true;
  107858. break;
  107859. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  107860. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  107861. break;
  107862. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  107863. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  107864. break;
  107865. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  107866. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  107867. break;
  107868. case BABYLON.Texture.CUBIC_MODE:
  107869. case BABYLON.Texture.INVCUBIC_MODE:
  107870. default:
  107871. defines.REFLECTIONMAP_CUBIC = true;
  107872. break;
  107873. }
  107874. if (this.reflectionFresnel) {
  107875. defines.REFLECTIONFRESNEL = true;
  107876. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  107877. this._reflectionControls.x = this.reflectionAmount;
  107878. this._reflectionControls.y = this.reflectionReflectance0;
  107879. this._reflectionControls.z = this.reflectionReflectance90;
  107880. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  107881. }
  107882. else {
  107883. defines.REFLECTIONFRESNEL = false;
  107884. defines.REFLECTIONFALLOFF = false;
  107885. }
  107886. }
  107887. else {
  107888. defines.REFLECTION = false;
  107889. defines.REFLECTIONFRESNEL = false;
  107890. defines.REFLECTIONFALLOFF = false;
  107891. defines.REFLECTIONBLUR = false;
  107892. defines.REFLECTIONMAP_3D = false;
  107893. defines.REFLECTIONMAP_SPHERICAL = false;
  107894. defines.REFLECTIONMAP_PLANAR = false;
  107895. defines.REFLECTIONMAP_CUBIC = false;
  107896. defines.REFLECTIONMAP_PROJECTION = false;
  107897. defines.REFLECTIONMAP_SKYBOX = false;
  107898. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107899. defines.REFLECTIONMAP_EXPLICIT = false;
  107900. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107901. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107902. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107903. defines.INVERTCUBICMAP = false;
  107904. defines.REFLECTIONMAP_OPPOSITEZ = false;
  107905. defines.LODINREFLECTIONALPHA = false;
  107906. defines.GAMMAREFLECTION = false;
  107907. defines.RGBDREFLECTION = false;
  107908. }
  107909. }
  107910. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  107911. defines.USERGBCOLOR = this._useRGBColor;
  107912. defines.NOISE = this._enableNoise;
  107913. }
  107914. if (defines._areLightsDirty) {
  107915. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  107916. }
  107917. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  107918. if (!this._imageProcessingConfiguration.isReady()) {
  107919. return false;
  107920. }
  107921. this._imageProcessingConfiguration.prepareDefines(defines);
  107922. }
  107923. // Misc.
  107924. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  107925. // Values that need to be evaluated on every frame
  107926. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  107927. // Attribs
  107928. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  107929. if (mesh) {
  107930. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  107931. mesh.createNormals(true);
  107932. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  107933. }
  107934. }
  107935. }
  107936. // Get correct effect
  107937. if (defines.isDirty) {
  107938. defines.markAsProcessed();
  107939. scene.resetCachedMaterial();
  107940. // Fallbacks
  107941. var fallbacks = new BABYLON.EffectFallbacks();
  107942. if (defines.FOG) {
  107943. fallbacks.addFallback(0, "FOG");
  107944. }
  107945. if (defines.POINTSIZE) {
  107946. fallbacks.addFallback(1, "POINTSIZE");
  107947. }
  107948. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  107949. if (defines.NUM_BONE_INFLUENCERS > 0) {
  107950. fallbacks.addCPUSkinningFallback(0, mesh);
  107951. }
  107952. //Attributes
  107953. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107954. if (defines.NORMAL) {
  107955. attribs.push(BABYLON.VertexBuffer.NormalKind);
  107956. }
  107957. if (defines.UV1) {
  107958. attribs.push(BABYLON.VertexBuffer.UVKind);
  107959. }
  107960. if (defines.UV2) {
  107961. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107962. }
  107963. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  107964. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  107965. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  107966. "vFogInfos", "vFogColor", "pointSize",
  107967. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  107968. "vPrimaryColor", "vPrimaryColorShadow",
  107969. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  107970. "shadowLevel", "alpha",
  107971. "vBackgroundCenter", "vReflectionControl",
  107972. "vDiffuseInfos", "diffuseMatrix",
  107973. ];
  107974. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  107975. var uniformBuffers = ["Material", "Scene"];
  107976. if (BABYLON.ImageProcessingConfiguration) {
  107977. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  107978. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  107979. }
  107980. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  107981. uniformsNames: uniforms,
  107982. uniformBuffersNames: uniformBuffers,
  107983. samplers: samplers,
  107984. defines: defines,
  107985. maxSimultaneousLights: this._maxSimultaneousLights
  107986. });
  107987. var onCompiled = function (effect) {
  107988. if (_this.onCompiled) {
  107989. _this.onCompiled(effect);
  107990. }
  107991. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  107992. };
  107993. var join = defines.toString();
  107994. subMesh.setEffect(scene.getEngine().createEffect("background", {
  107995. attributes: attribs,
  107996. uniformsNames: uniforms,
  107997. uniformBuffersNames: uniformBuffers,
  107998. samplers: samplers,
  107999. defines: join,
  108000. fallbacks: fallbacks,
  108001. onCompiled: onCompiled,
  108002. onError: this.onError,
  108003. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  108004. }, engine), defines);
  108005. this.buildUniformLayout();
  108006. }
  108007. if (!subMesh.effect || !subMesh.effect.isReady()) {
  108008. return false;
  108009. }
  108010. defines._renderId = scene.getRenderId();
  108011. this._wasPreviouslyReady = true;
  108012. return true;
  108013. };
  108014. /**
  108015. * Compute the primary color according to the chosen perceptual color.
  108016. */
  108017. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  108018. if (!this.__perceptualColor) {
  108019. return;
  108020. }
  108021. this._primaryColor.copyFrom(this.__perceptualColor);
  108022. // Revert gamma space.
  108023. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  108024. // Revert image processing configuration.
  108025. if (this._imageProcessingConfiguration) {
  108026. // Revert Exposure.
  108027. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  108028. }
  108029. this._computePrimaryColors();
  108030. };
  108031. /**
  108032. * Compute the highlights and shadow colors according to their chosen levels.
  108033. */
  108034. BackgroundMaterial.prototype._computePrimaryColors = function () {
  108035. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  108036. return;
  108037. }
  108038. // Find the highlight color based on the configuration.
  108039. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  108040. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  108041. // Find the shadow color based on the configuration.
  108042. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  108043. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  108044. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  108045. };
  108046. /**
  108047. * Build the uniform buffer used in the material.
  108048. */
  108049. BackgroundMaterial.prototype.buildUniformLayout = function () {
  108050. // Order is important !
  108051. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  108052. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  108053. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  108054. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  108055. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  108056. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  108057. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  108058. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  108059. this._uniformBuffer.addUniform("pointSize", 1);
  108060. this._uniformBuffer.addUniform("shadowLevel", 1);
  108061. this._uniformBuffer.addUniform("alpha", 1);
  108062. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  108063. this._uniformBuffer.addUniform("vReflectionControl", 4);
  108064. this._uniformBuffer.create();
  108065. };
  108066. /**
  108067. * Unbind the material.
  108068. */
  108069. BackgroundMaterial.prototype.unbind = function () {
  108070. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  108071. this._uniformBuffer.setTexture("diffuseSampler", null);
  108072. }
  108073. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  108074. this._uniformBuffer.setTexture("reflectionSampler", null);
  108075. }
  108076. _super.prototype.unbind.call(this);
  108077. };
  108078. /**
  108079. * Bind only the world matrix to the material.
  108080. * @param world The world matrix to bind.
  108081. */
  108082. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  108083. this._activeEffect.setMatrix("world", world);
  108084. };
  108085. /**
  108086. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  108087. * @param world The world matrix to bind.
  108088. * @param subMesh The submesh to bind for.
  108089. */
  108090. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  108091. var scene = this.getScene();
  108092. var defines = subMesh._materialDefines;
  108093. if (!defines) {
  108094. return;
  108095. }
  108096. var effect = subMesh.effect;
  108097. if (!effect) {
  108098. return;
  108099. }
  108100. this._activeEffect = effect;
  108101. // Matrices
  108102. this.bindOnlyWorldMatrix(world);
  108103. // Bones
  108104. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  108105. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  108106. if (mustRebind) {
  108107. this._uniformBuffer.bindToEffect(effect, "Material");
  108108. this.bindViewProjection(effect);
  108109. var reflectionTexture = this._reflectionTexture;
  108110. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  108111. // Texture uniforms
  108112. if (scene.texturesEnabled) {
  108113. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108114. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  108115. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  108116. }
  108117. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108118. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  108119. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  108120. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  108121. }
  108122. }
  108123. if (this.shadowLevel > 0) {
  108124. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  108125. }
  108126. this._uniformBuffer.updateFloat("alpha", this.alpha);
  108127. // Point size
  108128. if (this.pointsCloud) {
  108129. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  108130. }
  108131. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  108132. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  108133. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  108134. }
  108135. else {
  108136. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  108137. }
  108138. }
  108139. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  108140. // Textures
  108141. if (scene.texturesEnabled) {
  108142. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108143. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  108144. }
  108145. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108146. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  108147. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  108148. }
  108149. else if (!defines.REFLECTIONBLUR) {
  108150. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  108151. }
  108152. else {
  108153. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  108154. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  108155. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  108156. }
  108157. if (defines.REFLECTIONFRESNEL) {
  108158. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  108159. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  108160. }
  108161. }
  108162. }
  108163. // Clip plane
  108164. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  108165. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  108166. }
  108167. if (mustRebind || !this.isFrozen) {
  108168. if (scene.lightsEnabled) {
  108169. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  108170. }
  108171. // View
  108172. this.bindView(effect);
  108173. // Fog
  108174. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  108175. // image processing
  108176. if (this._imageProcessingConfiguration) {
  108177. this._imageProcessingConfiguration.bind(this._activeEffect);
  108178. }
  108179. }
  108180. this._uniformBuffer.update();
  108181. this._afterBind(mesh, this._activeEffect);
  108182. };
  108183. /**
  108184. * Dispose the material.
  108185. * @param forceDisposeEffect Force disposal of the associated effect.
  108186. * @param forceDisposeTextures Force disposal of the associated textures.
  108187. */
  108188. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  108189. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  108190. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  108191. if (forceDisposeTextures) {
  108192. if (this.diffuseTexture) {
  108193. this.diffuseTexture.dispose();
  108194. }
  108195. if (this.reflectionTexture) {
  108196. this.reflectionTexture.dispose();
  108197. }
  108198. }
  108199. this._renderTargets.dispose();
  108200. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  108201. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  108202. }
  108203. _super.prototype.dispose.call(this, forceDisposeEffect);
  108204. };
  108205. /**
  108206. * Clones the material.
  108207. * @param name The cloned name.
  108208. * @returns The cloned material.
  108209. */
  108210. BackgroundMaterial.prototype.clone = function (name) {
  108211. var _this = this;
  108212. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  108213. };
  108214. /**
  108215. * Serializes the current material to its JSON representation.
  108216. * @returns The JSON representation.
  108217. */
  108218. BackgroundMaterial.prototype.serialize = function () {
  108219. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108220. serializationObject.customType = "BABYLON.BackgroundMaterial";
  108221. return serializationObject;
  108222. };
  108223. /**
  108224. * Gets the class name of the material
  108225. * @returns "BackgroundMaterial"
  108226. */
  108227. BackgroundMaterial.prototype.getClassName = function () {
  108228. return "BackgroundMaterial";
  108229. };
  108230. /**
  108231. * Parse a JSON input to create back a background material.
  108232. * @param source The JSON data to parse
  108233. * @param scene The scene to create the parsed material in
  108234. * @param rootUrl The root url of the assets the material depends upon
  108235. * @returns the instantiated BackgroundMaterial.
  108236. */
  108237. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  108238. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  108239. };
  108240. /**
  108241. * Standard reflectance value at parallel view angle.
  108242. */
  108243. BackgroundMaterial.StandardReflectance0 = 0.05;
  108244. /**
  108245. * Standard reflectance value at grazing angle.
  108246. */
  108247. BackgroundMaterial.StandardReflectance90 = 0.5;
  108248. __decorate([
  108249. BABYLON.serializeAsColor3()
  108250. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  108251. __decorate([
  108252. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  108253. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  108254. __decorate([
  108255. BABYLON.serializeAsColor3()
  108256. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  108257. __decorate([
  108258. BABYLON.serialize()
  108259. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  108260. __decorate([
  108261. BABYLON.serialize()
  108262. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  108263. __decorate([
  108264. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  108265. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  108266. __decorate([
  108267. BABYLON.serializeAsTexture()
  108268. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  108269. __decorate([
  108270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108271. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  108272. __decorate([
  108273. BABYLON.serialize()
  108274. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  108275. __decorate([
  108276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108277. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  108278. __decorate([
  108279. BABYLON.serializeAsTexture()
  108280. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  108281. __decorate([
  108282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108283. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  108284. __decorate([
  108285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108286. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  108287. __decorate([
  108288. BABYLON.serialize()
  108289. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  108290. __decorate([
  108291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108292. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  108293. __decorate([
  108294. BABYLON.serializeAsVector3()
  108295. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  108296. __decorate([
  108297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108298. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  108299. __decorate([
  108300. BABYLON.serialize()
  108301. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  108302. __decorate([
  108303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108304. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  108305. __decorate([
  108306. BABYLON.serialize()
  108307. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  108308. __decorate([
  108309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108310. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  108311. __decorate([
  108312. BABYLON.serialize()
  108313. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  108314. __decorate([
  108315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108316. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  108317. __decorate([
  108318. BABYLON.serialize()
  108319. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  108320. __decorate([
  108321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108322. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  108323. __decorate([
  108324. BABYLON.serialize()
  108325. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  108326. __decorate([
  108327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108328. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  108329. __decorate([
  108330. BABYLON.serialize()
  108331. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  108332. __decorate([
  108333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108334. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  108335. __decorate([
  108336. BABYLON.serialize()
  108337. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  108338. __decorate([
  108339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108340. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  108341. __decorate([
  108342. BABYLON.serialize()
  108343. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  108344. __decorate([
  108345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108346. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  108347. __decorate([
  108348. BABYLON.serialize()
  108349. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  108350. __decorate([
  108351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108352. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  108353. __decorate([
  108354. BABYLON.serializeAsImageProcessingConfiguration()
  108355. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  108356. return BackgroundMaterial;
  108357. }(BABYLON.PushMaterial));
  108358. BABYLON.BackgroundMaterial = BackgroundMaterial;
  108359. })(BABYLON || (BABYLON = {}));
  108360. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  108361. var __assign = (this && this.__assign) || function () {
  108362. __assign = Object.assign || function(t) {
  108363. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108364. s = arguments[i];
  108365. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108366. t[p] = s[p];
  108367. }
  108368. return t;
  108369. };
  108370. return __assign.apply(this, arguments);
  108371. };
  108372. var BABYLON;
  108373. (function (BABYLON) {
  108374. /**
  108375. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  108376. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  108377. * It also helps with the default setup of your imageProcessing configuration.
  108378. */
  108379. var EnvironmentHelper = /** @class */ (function () {
  108380. /**
  108381. * constructor
  108382. * @param options
  108383. * @param scene The scene to add the material to
  108384. */
  108385. function EnvironmentHelper(options, scene) {
  108386. var _this = this;
  108387. this._errorHandler = function (message, exception) {
  108388. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  108389. };
  108390. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  108391. this._scene = scene;
  108392. this.onErrorObservable = new BABYLON.Observable();
  108393. this._setupBackground();
  108394. this._setupImageProcessing();
  108395. }
  108396. /**
  108397. * Creates the default options for the helper.
  108398. */
  108399. EnvironmentHelper._getDefaultOptions = function () {
  108400. return {
  108401. createGround: true,
  108402. groundSize: 15,
  108403. groundTexture: this._groundTextureCDNUrl,
  108404. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  108405. groundOpacity: 0.9,
  108406. enableGroundShadow: true,
  108407. groundShadowLevel: 0.5,
  108408. enableGroundMirror: false,
  108409. groundMirrorSizeRatio: 0.3,
  108410. groundMirrorBlurKernel: 64,
  108411. groundMirrorAmount: 1,
  108412. groundMirrorFresnelWeight: 1,
  108413. groundMirrorFallOffDistance: 0,
  108414. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  108415. groundYBias: 0.00001,
  108416. createSkybox: true,
  108417. skyboxSize: 20,
  108418. skyboxTexture: this._skyboxTextureCDNUrl,
  108419. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  108420. backgroundYRotation: 0,
  108421. sizeAuto: true,
  108422. rootPosition: BABYLON.Vector3.Zero(),
  108423. setupImageProcessing: true,
  108424. environmentTexture: this._environmentTextureCDNUrl,
  108425. cameraExposure: 0.8,
  108426. cameraContrast: 1.2,
  108427. toneMappingEnabled: true,
  108428. };
  108429. };
  108430. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  108431. /**
  108432. * Gets the root mesh created by the helper.
  108433. */
  108434. get: function () {
  108435. return this._rootMesh;
  108436. },
  108437. enumerable: true,
  108438. configurable: true
  108439. });
  108440. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  108441. /**
  108442. * Gets the skybox created by the helper.
  108443. */
  108444. get: function () {
  108445. return this._skybox;
  108446. },
  108447. enumerable: true,
  108448. configurable: true
  108449. });
  108450. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  108451. /**
  108452. * Gets the skybox texture created by the helper.
  108453. */
  108454. get: function () {
  108455. return this._skyboxTexture;
  108456. },
  108457. enumerable: true,
  108458. configurable: true
  108459. });
  108460. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  108461. /**
  108462. * Gets the skybox material created by the helper.
  108463. */
  108464. get: function () {
  108465. return this._skyboxMaterial;
  108466. },
  108467. enumerable: true,
  108468. configurable: true
  108469. });
  108470. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  108471. /**
  108472. * Gets the ground mesh created by the helper.
  108473. */
  108474. get: function () {
  108475. return this._ground;
  108476. },
  108477. enumerable: true,
  108478. configurable: true
  108479. });
  108480. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  108481. /**
  108482. * Gets the ground texture created by the helper.
  108483. */
  108484. get: function () {
  108485. return this._groundTexture;
  108486. },
  108487. enumerable: true,
  108488. configurable: true
  108489. });
  108490. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  108491. /**
  108492. * Gets the ground mirror created by the helper.
  108493. */
  108494. get: function () {
  108495. return this._groundMirror;
  108496. },
  108497. enumerable: true,
  108498. configurable: true
  108499. });
  108500. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  108501. /**
  108502. * Gets the ground mirror render list to helps pushing the meshes
  108503. * you wish in the ground reflection.
  108504. */
  108505. get: function () {
  108506. if (this._groundMirror) {
  108507. return this._groundMirror.renderList;
  108508. }
  108509. return null;
  108510. },
  108511. enumerable: true,
  108512. configurable: true
  108513. });
  108514. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  108515. /**
  108516. * Gets the ground material created by the helper.
  108517. */
  108518. get: function () {
  108519. return this._groundMaterial;
  108520. },
  108521. enumerable: true,
  108522. configurable: true
  108523. });
  108524. /**
  108525. * Updates the background according to the new options
  108526. * @param options
  108527. */
  108528. EnvironmentHelper.prototype.updateOptions = function (options) {
  108529. var newOptions = __assign({}, this._options, options);
  108530. if (this._ground && !newOptions.createGround) {
  108531. this._ground.dispose();
  108532. this._ground = null;
  108533. }
  108534. if (this._groundMaterial && !newOptions.createGround) {
  108535. this._groundMaterial.dispose();
  108536. this._groundMaterial = null;
  108537. }
  108538. if (this._groundTexture) {
  108539. if (this._options.groundTexture != newOptions.groundTexture) {
  108540. this._groundTexture.dispose();
  108541. this._groundTexture = null;
  108542. }
  108543. }
  108544. if (this._skybox && !newOptions.createSkybox) {
  108545. this._skybox.dispose();
  108546. this._skybox = null;
  108547. }
  108548. if (this._skyboxMaterial && !newOptions.createSkybox) {
  108549. this._skyboxMaterial.dispose();
  108550. this._skyboxMaterial = null;
  108551. }
  108552. if (this._skyboxTexture) {
  108553. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  108554. this._skyboxTexture.dispose();
  108555. this._skyboxTexture = null;
  108556. }
  108557. }
  108558. if (this._groundMirror && !newOptions.enableGroundMirror) {
  108559. this._groundMirror.dispose();
  108560. this._groundMirror = null;
  108561. }
  108562. if (this._scene.environmentTexture) {
  108563. if (this._options.environmentTexture != newOptions.environmentTexture) {
  108564. this._scene.environmentTexture.dispose();
  108565. }
  108566. }
  108567. this._options = newOptions;
  108568. this._setupBackground();
  108569. this._setupImageProcessing();
  108570. };
  108571. /**
  108572. * Sets the primary color of all the available elements.
  108573. * @param color the main color to affect to the ground and the background
  108574. */
  108575. EnvironmentHelper.prototype.setMainColor = function (color) {
  108576. if (this.groundMaterial) {
  108577. this.groundMaterial.primaryColor = color;
  108578. }
  108579. if (this.skyboxMaterial) {
  108580. this.skyboxMaterial.primaryColor = color;
  108581. }
  108582. if (this.groundMirror) {
  108583. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  108584. }
  108585. };
  108586. /**
  108587. * Setup the image processing according to the specified options.
  108588. */
  108589. EnvironmentHelper.prototype._setupImageProcessing = function () {
  108590. if (this._options.setupImageProcessing) {
  108591. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  108592. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  108593. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  108594. this._setupEnvironmentTexture();
  108595. }
  108596. };
  108597. /**
  108598. * Setup the environment texture according to the specified options.
  108599. */
  108600. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  108601. if (this._scene.environmentTexture) {
  108602. return;
  108603. }
  108604. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  108605. this._scene.environmentTexture = this._options.environmentTexture;
  108606. return;
  108607. }
  108608. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  108609. this._scene.environmentTexture = environmentTexture;
  108610. };
  108611. /**
  108612. * Setup the background according to the specified options.
  108613. */
  108614. EnvironmentHelper.prototype._setupBackground = function () {
  108615. if (!this._rootMesh) {
  108616. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  108617. }
  108618. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  108619. var sceneSize = this._getSceneSize();
  108620. if (this._options.createGround) {
  108621. this._setupGround(sceneSize);
  108622. this._setupGroundMaterial();
  108623. this._setupGroundDiffuseTexture();
  108624. if (this._options.enableGroundMirror) {
  108625. this._setupGroundMirrorTexture(sceneSize);
  108626. }
  108627. this._setupMirrorInGroundMaterial();
  108628. }
  108629. if (this._options.createSkybox) {
  108630. this._setupSkybox(sceneSize);
  108631. this._setupSkyboxMaterial();
  108632. this._setupSkyboxReflectionTexture();
  108633. }
  108634. this._rootMesh.position.x = sceneSize.rootPosition.x;
  108635. this._rootMesh.position.z = sceneSize.rootPosition.z;
  108636. this._rootMesh.position.y = sceneSize.rootPosition.y;
  108637. };
  108638. /**
  108639. * Get the scene sizes according to the setup.
  108640. */
  108641. EnvironmentHelper.prototype._getSceneSize = function () {
  108642. var _this = this;
  108643. var groundSize = this._options.groundSize;
  108644. var skyboxSize = this._options.skyboxSize;
  108645. var rootPosition = this._options.rootPosition;
  108646. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  108647. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108648. }
  108649. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  108650. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  108651. });
  108652. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108653. if (this._options.sizeAuto) {
  108654. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  108655. this._scene.activeCamera.upperRadiusLimit) {
  108656. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  108657. skyboxSize = groundSize;
  108658. }
  108659. var sceneDiagonalLenght = sceneDiagonal.length();
  108660. if (sceneDiagonalLenght > groundSize) {
  108661. groundSize = sceneDiagonalLenght * 2;
  108662. skyboxSize = groundSize;
  108663. }
  108664. // 10 % bigger.
  108665. groundSize *= 1.1;
  108666. skyboxSize *= 1.5;
  108667. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  108668. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  108669. }
  108670. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108671. };
  108672. /**
  108673. * Setup the ground according to the specified options.
  108674. */
  108675. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  108676. var _this = this;
  108677. if (!this._ground || this._ground.isDisposed()) {
  108678. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  108679. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  108680. this._ground.parent = this._rootMesh;
  108681. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  108682. }
  108683. this._ground.receiveShadows = this._options.enableGroundShadow;
  108684. };
  108685. /**
  108686. * Setup the ground material according to the specified options.
  108687. */
  108688. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  108689. if (!this._groundMaterial) {
  108690. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  108691. }
  108692. this._groundMaterial.alpha = this._options.groundOpacity;
  108693. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  108694. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  108695. this._groundMaterial.primaryColor = this._options.groundColor;
  108696. this._groundMaterial.useRGBColor = false;
  108697. this._groundMaterial.enableNoise = true;
  108698. if (this._ground) {
  108699. this._ground.material = this._groundMaterial;
  108700. }
  108701. };
  108702. /**
  108703. * Setup the ground diffuse texture according to the specified options.
  108704. */
  108705. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  108706. if (!this._groundMaterial) {
  108707. return;
  108708. }
  108709. if (this._groundTexture) {
  108710. return;
  108711. }
  108712. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  108713. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  108714. return;
  108715. }
  108716. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108717. diffuseTexture.gammaSpace = false;
  108718. diffuseTexture.hasAlpha = true;
  108719. this._groundMaterial.diffuseTexture = diffuseTexture;
  108720. };
  108721. /**
  108722. * Setup the ground mirror texture according to the specified options.
  108723. */
  108724. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  108725. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108726. if (!this._groundMirror) {
  108727. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  108728. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  108729. this._groundMirror.anisotropicFilteringLevel = 1;
  108730. this._groundMirror.wrapU = wrapping;
  108731. this._groundMirror.wrapV = wrapping;
  108732. this._groundMirror.gammaSpace = false;
  108733. if (this._groundMirror.renderList) {
  108734. for (var i = 0; i < this._scene.meshes.length; i++) {
  108735. var mesh = this._scene.meshes[i];
  108736. if (mesh !== this._ground &&
  108737. mesh !== this._skybox &&
  108738. mesh !== this._rootMesh) {
  108739. this._groundMirror.renderList.push(mesh);
  108740. }
  108741. }
  108742. }
  108743. }
  108744. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  108745. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  108746. };
  108747. /**
  108748. * Setup the ground to receive the mirror texture.
  108749. */
  108750. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  108751. if (this._groundMaterial) {
  108752. this._groundMaterial.reflectionTexture = this._groundMirror;
  108753. this._groundMaterial.reflectionFresnel = true;
  108754. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  108755. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  108756. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  108757. }
  108758. };
  108759. /**
  108760. * Setup the skybox according to the specified options.
  108761. */
  108762. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  108763. var _this = this;
  108764. if (!this._skybox || this._skybox.isDisposed()) {
  108765. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  108766. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  108767. }
  108768. this._skybox.parent = this._rootMesh;
  108769. };
  108770. /**
  108771. * Setup the skybox material according to the specified options.
  108772. */
  108773. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  108774. if (!this._skybox) {
  108775. return;
  108776. }
  108777. if (!this._skyboxMaterial) {
  108778. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  108779. }
  108780. this._skyboxMaterial.useRGBColor = false;
  108781. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  108782. this._skyboxMaterial.enableNoise = true;
  108783. this._skybox.material = this._skyboxMaterial;
  108784. };
  108785. /**
  108786. * Setup the skybox reflection texture according to the specified options.
  108787. */
  108788. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  108789. if (!this._skyboxMaterial) {
  108790. return;
  108791. }
  108792. if (this._skyboxTexture) {
  108793. return;
  108794. }
  108795. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  108796. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  108797. return;
  108798. }
  108799. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108800. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  108801. this._skyboxTexture.gammaSpace = false;
  108802. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  108803. };
  108804. /**
  108805. * Dispose all the elements created by the Helper.
  108806. */
  108807. EnvironmentHelper.prototype.dispose = function () {
  108808. if (this._groundMaterial) {
  108809. this._groundMaterial.dispose(true, true);
  108810. }
  108811. if (this._skyboxMaterial) {
  108812. this._skyboxMaterial.dispose(true, true);
  108813. }
  108814. this._rootMesh.dispose(false);
  108815. };
  108816. /**
  108817. * Default ground texture URL.
  108818. */
  108819. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  108820. /**
  108821. * Default skybox texture URL.
  108822. */
  108823. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  108824. /**
  108825. * Default environment texture URL.
  108826. */
  108827. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  108828. return EnvironmentHelper;
  108829. }());
  108830. BABYLON.EnvironmentHelper = EnvironmentHelper;
  108831. })(BABYLON || (BABYLON = {}));
  108832. //# sourceMappingURL=babylon.environmentHelper.js.map
  108833. var BABYLON;
  108834. (function (BABYLON) {
  108835. /** Internal class used to store shapes for emitters */
  108836. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  108837. function ParticleSystemSetEmitterCreationOptions() {
  108838. }
  108839. return ParticleSystemSetEmitterCreationOptions;
  108840. }());
  108841. /**
  108842. * Represents a set of particle systems working together to create a specific effect
  108843. */
  108844. var ParticleSystemSet = /** @class */ (function () {
  108845. function ParticleSystemSet() {
  108846. /**
  108847. * Gets the particle system list
  108848. */
  108849. this.systems = new Array();
  108850. }
  108851. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  108852. /**
  108853. * Gets the emitter node used with this set
  108854. */
  108855. get: function () {
  108856. return this._emitterNode;
  108857. },
  108858. enumerable: true,
  108859. configurable: true
  108860. });
  108861. /**
  108862. * Creates a new emitter mesh as a sphere
  108863. * @param options defines the options used to create the sphere
  108864. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  108865. * @param scene defines the hosting scene
  108866. */
  108867. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  108868. if (this._emitterNode) {
  108869. this._emitterNode.dispose();
  108870. }
  108871. this._emitterCreationOptions = {
  108872. kind: "Sphere",
  108873. options: options,
  108874. renderingGroupId: renderingGroupId
  108875. };
  108876. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  108877. emitterMesh.renderingGroupId = renderingGroupId;
  108878. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  108879. material.emissiveColor = options.color;
  108880. emitterMesh.material = material;
  108881. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108882. var system = _a[_i];
  108883. system.emitter = emitterMesh;
  108884. }
  108885. this._emitterNode = emitterMesh;
  108886. };
  108887. /**
  108888. * Starts all particle systems of the set
  108889. * @param emitter defines an optional mesh to use as emitter for the particle systems
  108890. */
  108891. ParticleSystemSet.prototype.start = function (emitter) {
  108892. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108893. var system = _a[_i];
  108894. if (emitter) {
  108895. system.emitter = emitter;
  108896. }
  108897. system.start();
  108898. }
  108899. };
  108900. /**
  108901. * Release all associated resources
  108902. */
  108903. ParticleSystemSet.prototype.dispose = function () {
  108904. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108905. var system = _a[_i];
  108906. system.dispose();
  108907. }
  108908. this.systems = [];
  108909. if (this._emitterNode) {
  108910. this._emitterNode.dispose();
  108911. this._emitterNode = null;
  108912. }
  108913. };
  108914. /**
  108915. * Serialize the set into a JSON compatible object
  108916. * @returns a JSON compatible representation of the set
  108917. */
  108918. ParticleSystemSet.prototype.serialize = function () {
  108919. var result = {};
  108920. result.systems = [];
  108921. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108922. var system = _a[_i];
  108923. result.systems.push(system.serialize());
  108924. }
  108925. if (this._emitterNode) {
  108926. result.emitter = this._emitterCreationOptions;
  108927. }
  108928. return result;
  108929. };
  108930. /**
  108931. * Parse a new ParticleSystemSet from a serialized source
  108932. * @param data defines a JSON compatible representation of the set
  108933. * @param scene defines the hosting scene
  108934. * @param gpu defines if we want GPU particles or CPU particles
  108935. * @returns a new ParticleSystemSet
  108936. */
  108937. ParticleSystemSet.Parse = function (data, scene, gpu) {
  108938. if (gpu === void 0) { gpu = false; }
  108939. var result = new ParticleSystemSet();
  108940. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  108941. scene = scene || BABYLON.Engine.LastCreatedScene;
  108942. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  108943. var system = _a[_i];
  108944. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  108945. }
  108946. if (data.emitter) {
  108947. var options = data.emitter.options;
  108948. switch (data.emitter.kind) {
  108949. case "Sphere":
  108950. result.setEmitterAsSphere({
  108951. diameter: options.diameter,
  108952. segments: options.segments,
  108953. color: BABYLON.Color3.FromArray(options.color)
  108954. }, data.emitter.renderingGroupId, scene);
  108955. break;
  108956. }
  108957. }
  108958. return result;
  108959. };
  108960. return ParticleSystemSet;
  108961. }());
  108962. BABYLON.ParticleSystemSet = ParticleSystemSet;
  108963. })(BABYLON || (BABYLON = {}));
  108964. //# sourceMappingURL=babylon.particleSystemSet.js.map
  108965. var BABYLON;
  108966. (function (BABYLON) {
  108967. /**
  108968. * This class is made for on one-liner static method to help creating particle system set.
  108969. */
  108970. var ParticleHelper = /** @class */ (function () {
  108971. function ParticleHelper() {
  108972. }
  108973. /**
  108974. * Create a default particle system that you can tweak
  108975. * @param emitter defines the emitter to use
  108976. * @param capacity defines the system capacity (default is 500 particles)
  108977. * @param scene defines the hosting scene
  108978. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  108979. * @returns the new Particle system
  108980. */
  108981. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  108982. if (capacity === void 0) { capacity = 500; }
  108983. if (useGPU === void 0) { useGPU = false; }
  108984. var system;
  108985. if (useGPU) {
  108986. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  108987. }
  108988. else {
  108989. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  108990. }
  108991. system.emitter = emitter;
  108992. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  108993. system.createConeEmitter(0.1, Math.PI / 4);
  108994. // Particle color
  108995. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108996. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108997. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  108998. // Particle Size
  108999. system.minSize = 0.1;
  109000. system.maxSize = 0.1;
  109001. // Emission speed
  109002. system.minEmitPower = 2;
  109003. system.maxEmitPower = 2;
  109004. // Update speed
  109005. system.updateSpeed = 1 / 60;
  109006. system.emitRate = 30;
  109007. return system;
  109008. };
  109009. /**
  109010. * This is the main static method (one-liner) of this helper to create different particle systems
  109011. * @param type This string represents the type to the particle system to create
  109012. * @param scene The scene where the particle system should live
  109013. * @param gpu If the system will use gpu
  109014. * @returns the ParticleSystemSet created
  109015. */
  109016. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  109017. if (gpu === void 0) { gpu = false; }
  109018. if (!scene) {
  109019. scene = BABYLON.Engine.LastCreatedScene;
  109020. ;
  109021. }
  109022. var token = {};
  109023. scene._addPendingData(token);
  109024. return new Promise(function (resolve, reject) {
  109025. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  109026. scene._removePendingData(token);
  109027. return reject("Particle system with GPU is not supported.");
  109028. }
  109029. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  109030. scene._removePendingData(token);
  109031. var newData = JSON.parse(data.toString());
  109032. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  109033. }, undefined, undefined, undefined, function (req, exception) {
  109034. scene._removePendingData(token);
  109035. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  109036. });
  109037. });
  109038. };
  109039. /**
  109040. * Static function used to export a particle system to a ParticleSystemSet variable.
  109041. * Please note that the emitter shape is not exported
  109042. * @param system defines the particle systems to export
  109043. */
  109044. ParticleHelper.ExportSet = function (systems) {
  109045. var set = new BABYLON.ParticleSystemSet();
  109046. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  109047. var system = systems_1[_i];
  109048. set.systems.push(system);
  109049. }
  109050. return set;
  109051. };
  109052. /**
  109053. * Gets or sets base Assets URL
  109054. */
  109055. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  109056. return ParticleHelper;
  109057. }());
  109058. BABYLON.ParticleHelper = ParticleHelper;
  109059. })(BABYLON || (BABYLON = {}));
  109060. //# sourceMappingURL=babylon.particleHelper.js.map
  109061. var BABYLON;
  109062. (function (BABYLON) {
  109063. /**
  109064. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  109065. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  109066. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  109067. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  109068. */
  109069. var VideoDome = /** @class */ (function (_super) {
  109070. __extends(VideoDome, _super);
  109071. /**
  109072. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  109073. * @param name Element's name, child elements will append suffixes for their own names.
  109074. * @param urlsOrVideo defines the url(s) or the video element to use
  109075. * @param options An object containing optional or exposed sub element properties
  109076. */
  109077. function VideoDome(name, urlsOrVideo, options, scene) {
  109078. var _this = _super.call(this, name, scene) || this;
  109079. _this._useDirectMapping = false;
  109080. // set defaults and manage values
  109081. name = name || "videoDome";
  109082. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  109083. options.clickToPlay = Boolean(options.clickToPlay);
  109084. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  109085. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  109086. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  109087. if (options.useDirectMapping === undefined) {
  109088. _this._useDirectMapping = true;
  109089. }
  109090. else {
  109091. _this._useDirectMapping = options.useDirectMapping;
  109092. }
  109093. _this._setReady(false);
  109094. // create
  109095. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  109096. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  109097. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  109098. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  109099. texture.onLoadObservable.addOnce(function () {
  109100. _this._setReady(true);
  109101. });
  109102. // configure material
  109103. material.useEquirectangularFOV = true;
  109104. material.fovMultiplier = 1.0;
  109105. material.opacityFresnel = false;
  109106. if (_this._useDirectMapping) {
  109107. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109108. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109109. material.diffuseTexture = texture;
  109110. }
  109111. else {
  109112. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  109113. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109114. material.reflectionTexture = texture;
  109115. }
  109116. // configure mesh
  109117. _this._mesh.material = material;
  109118. _this._mesh.parent = _this;
  109119. // optional configuration
  109120. if (options.clickToPlay) {
  109121. scene.onPointerUp = function () {
  109122. _this._videoTexture.video.play();
  109123. };
  109124. }
  109125. return _this;
  109126. }
  109127. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  109128. /**
  109129. * Gets the video texture being displayed on the sphere
  109130. */
  109131. get: function () {
  109132. return this._videoTexture;
  109133. },
  109134. enumerable: true,
  109135. configurable: true
  109136. });
  109137. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  109138. /**
  109139. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109140. * Also see the options.resolution property.
  109141. */
  109142. get: function () {
  109143. return this._material.fovMultiplier;
  109144. },
  109145. set: function (value) {
  109146. this._material.fovMultiplier = value;
  109147. },
  109148. enumerable: true,
  109149. configurable: true
  109150. });
  109151. /**
  109152. * Releases resources associated with this node.
  109153. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  109154. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  109155. */
  109156. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  109157. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  109158. this._videoTexture.dispose();
  109159. this._mesh.dispose();
  109160. this._material.dispose();
  109161. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  109162. };
  109163. return VideoDome;
  109164. }(BABYLON.TransformNode));
  109165. BABYLON.VideoDome = VideoDome;
  109166. })(BABYLON || (BABYLON = {}));
  109167. //# sourceMappingURL=babylon.videoDome.js.map
  109168. var BABYLON;
  109169. (function (BABYLON) {
  109170. /**
  109171. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  109172. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  109173. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  109174. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  109175. */
  109176. var PhotoDome = /** @class */ (function (_super) {
  109177. __extends(PhotoDome, _super);
  109178. /**
  109179. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  109180. * @param name Element's name, child elements will append suffixes for their own names.
  109181. * @param urlsOfPhoto defines the url of the photo to display
  109182. * @param options defines an object containing optional or exposed sub element properties
  109183. * @param onError defines a callback called when an error occured while loading the texture
  109184. */
  109185. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  109186. if (onError === void 0) { onError = null; }
  109187. var _this = _super.call(this, name, scene) || this;
  109188. _this._useDirectMapping = false;
  109189. /**
  109190. * Observable raised when an error occured while loading the 360 image
  109191. */
  109192. _this.onLoadErrorObservable = new BABYLON.Observable();
  109193. // set defaults and manage values
  109194. name = name || "photoDome";
  109195. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  109196. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  109197. if (options.useDirectMapping === undefined) {
  109198. _this._useDirectMapping = true;
  109199. }
  109200. else {
  109201. _this._useDirectMapping = options.useDirectMapping;
  109202. }
  109203. _this._setReady(false);
  109204. // create
  109205. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  109206. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  109207. // configure material
  109208. material.opacityFresnel = false;
  109209. material.useEquirectangularFOV = true;
  109210. material.fovMultiplier = 1.0;
  109211. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  109212. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  109213. if (onError) {
  109214. onError(message, exception);
  109215. }
  109216. });
  109217. _this.photoTexture.onLoadObservable.addOnce(function () {
  109218. _this._setReady(true);
  109219. });
  109220. // configure mesh
  109221. _this._mesh.material = material;
  109222. _this._mesh.parent = _this;
  109223. return _this;
  109224. }
  109225. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  109226. /**
  109227. * Gets or sets the texture being displayed on the sphere
  109228. */
  109229. get: function () {
  109230. return this._photoTexture;
  109231. },
  109232. set: function (value) {
  109233. if (this._photoTexture === value) {
  109234. return;
  109235. }
  109236. this._photoTexture = value;
  109237. if (this._useDirectMapping) {
  109238. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109239. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109240. this._material.diffuseTexture = this._photoTexture;
  109241. }
  109242. else {
  109243. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  109244. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109245. this._material.reflectionTexture = this._photoTexture;
  109246. }
  109247. },
  109248. enumerable: true,
  109249. configurable: true
  109250. });
  109251. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  109252. /**
  109253. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109254. * Also see the options.resolution property.
  109255. */
  109256. get: function () {
  109257. return this._material.fovMultiplier;
  109258. },
  109259. set: function (value) {
  109260. this._material.fovMultiplier = value;
  109261. },
  109262. enumerable: true,
  109263. configurable: true
  109264. });
  109265. /**
  109266. * Releases resources associated with this node.
  109267. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  109268. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  109269. */
  109270. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  109271. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  109272. this._photoTexture.dispose();
  109273. this._mesh.dispose();
  109274. this._material.dispose();
  109275. this.onLoadErrorObservable.clear();
  109276. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  109277. };
  109278. return PhotoDome;
  109279. }(BABYLON.TransformNode));
  109280. BABYLON.PhotoDome = PhotoDome;
  109281. })(BABYLON || (BABYLON = {}));
  109282. //# sourceMappingURL=babylon.photoDome.js.map
  109283. var BABYLON;
  109284. (function (BABYLON) {
  109285. BABYLON.Engine.prototype.createQuery = function () {
  109286. return this._gl.createQuery();
  109287. };
  109288. BABYLON.Engine.prototype.deleteQuery = function (query) {
  109289. this._gl.deleteQuery(query);
  109290. return this;
  109291. };
  109292. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  109293. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  109294. };
  109295. BABYLON.Engine.prototype.getQueryResult = function (query) {
  109296. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  109297. };
  109298. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  109299. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  109300. this._gl.beginQuery(glAlgorithm, query);
  109301. return this;
  109302. };
  109303. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  109304. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  109305. this._gl.endQuery(glAlgorithm);
  109306. return this;
  109307. };
  109308. BABYLON.Engine.prototype._createTimeQuery = function () {
  109309. var timerQuery = this.getCaps().timerQuery;
  109310. if (timerQuery.createQueryEXT) {
  109311. return timerQuery.createQueryEXT();
  109312. }
  109313. return this.createQuery();
  109314. };
  109315. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  109316. var timerQuery = this.getCaps().timerQuery;
  109317. if (timerQuery.deleteQueryEXT) {
  109318. timerQuery.deleteQueryEXT(query);
  109319. return;
  109320. }
  109321. this.deleteQuery(query);
  109322. };
  109323. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  109324. var timerQuery = this.getCaps().timerQuery;
  109325. if (timerQuery.getQueryObjectEXT) {
  109326. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  109327. }
  109328. return this.getQueryResult(query);
  109329. };
  109330. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  109331. var timerQuery = this.getCaps().timerQuery;
  109332. if (timerQuery.getQueryObjectEXT) {
  109333. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  109334. }
  109335. return this.isQueryResultAvailable(query);
  109336. };
  109337. BABYLON.Engine.prototype.startTimeQuery = function () {
  109338. var caps = this.getCaps();
  109339. var timerQuery = caps.timerQuery;
  109340. if (!timerQuery) {
  109341. return null;
  109342. }
  109343. var token = new BABYLON._TimeToken();
  109344. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  109345. if (caps.canUseTimestampForTimerQuery) {
  109346. token._startTimeQuery = this._createTimeQuery();
  109347. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  109348. }
  109349. else {
  109350. if (this._currentNonTimestampToken) {
  109351. return this._currentNonTimestampToken;
  109352. }
  109353. token._timeElapsedQuery = this._createTimeQuery();
  109354. if (timerQuery.beginQueryEXT) {
  109355. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  109356. }
  109357. else {
  109358. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  109359. }
  109360. this._currentNonTimestampToken = token;
  109361. }
  109362. return token;
  109363. };
  109364. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  109365. var caps = this.getCaps();
  109366. var timerQuery = caps.timerQuery;
  109367. if (!timerQuery || !token) {
  109368. return -1;
  109369. }
  109370. if (caps.canUseTimestampForTimerQuery) {
  109371. if (!token._startTimeQuery) {
  109372. return -1;
  109373. }
  109374. if (!token._endTimeQuery) {
  109375. token._endTimeQuery = this._createTimeQuery();
  109376. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  109377. }
  109378. }
  109379. else if (!token._timeElapsedQueryEnded) {
  109380. if (!token._timeElapsedQuery) {
  109381. return -1;
  109382. }
  109383. if (timerQuery.endQueryEXT) {
  109384. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  109385. }
  109386. else {
  109387. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  109388. }
  109389. token._timeElapsedQueryEnded = true;
  109390. }
  109391. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  109392. var available = false;
  109393. if (token._endTimeQuery) {
  109394. available = this._getTimeQueryAvailability(token._endTimeQuery);
  109395. }
  109396. else if (token._timeElapsedQuery) {
  109397. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  109398. }
  109399. if (available && !disjoint) {
  109400. var result = 0;
  109401. if (caps.canUseTimestampForTimerQuery) {
  109402. if (!token._startTimeQuery || !token._endTimeQuery) {
  109403. return -1;
  109404. }
  109405. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  109406. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  109407. result = timeEnd - timeStart;
  109408. this._deleteTimeQuery(token._startTimeQuery);
  109409. this._deleteTimeQuery(token._endTimeQuery);
  109410. token._startTimeQuery = null;
  109411. token._endTimeQuery = null;
  109412. }
  109413. else {
  109414. if (!token._timeElapsedQuery) {
  109415. return -1;
  109416. }
  109417. result = this._getTimeQueryResult(token._timeElapsedQuery);
  109418. this._deleteTimeQuery(token._timeElapsedQuery);
  109419. token._timeElapsedQuery = null;
  109420. token._timeElapsedQueryEnded = false;
  109421. this._currentNonTimestampToken = null;
  109422. }
  109423. return result;
  109424. }
  109425. return -1;
  109426. };
  109427. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  109428. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  109429. };
  109430. // We also need to update AbstractMesh as there is a portion of the code there
  109431. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  109432. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  109433. this._isOccluded = false;
  109434. return;
  109435. }
  109436. var engine = this.getEngine();
  109437. if (engine.webGLVersion < 2) {
  109438. this._isOccluded = false;
  109439. return;
  109440. }
  109441. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  109442. this._isOccluded = false;
  109443. return;
  109444. }
  109445. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  109446. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  109447. if (isOcclusionQueryAvailable) {
  109448. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  109449. this._isOcclusionQueryInProgress = false;
  109450. this._occlusionInternalRetryCounter = 0;
  109451. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  109452. }
  109453. else {
  109454. this._occlusionInternalRetryCounter++;
  109455. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  109456. this._isOcclusionQueryInProgress = false;
  109457. this._occlusionInternalRetryCounter = 0;
  109458. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  109459. // if strict continue the last state of the object.
  109460. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  109461. }
  109462. else {
  109463. return;
  109464. }
  109465. }
  109466. }
  109467. var scene = this.getScene();
  109468. if (scene.getBoundingBoxRenderer) {
  109469. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  109470. if (!this._occlusionQuery) {
  109471. this._occlusionQuery = engine.createQuery();
  109472. }
  109473. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  109474. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  109475. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  109476. this._isOcclusionQueryInProgress = true;
  109477. }
  109478. };
  109479. })(BABYLON || (BABYLON = {}));
  109480. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  109481. var BABYLON;
  109482. (function (BABYLON) {
  109483. /**
  109484. * Class used to generate noise procedural textures
  109485. */
  109486. var NoiseProceduralTexture = /** @class */ (function (_super) {
  109487. __extends(NoiseProceduralTexture, _super);
  109488. /**
  109489. * Creates a new NoiseProceduralTexture
  109490. * @param name defines the name fo the texture
  109491. * @param size defines the size of the texture (default is 256)
  109492. * @param scene defines the hosting scene
  109493. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  109494. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  109495. */
  109496. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  109497. if (size === void 0) { size = 256; }
  109498. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  109499. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  109500. _this._time = 0;
  109501. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  109502. _this.brightness = 0.2;
  109503. /** Defines the number of octaves to process */
  109504. _this.octaves = 3;
  109505. /** Defines the level of persistence (0.8 by default) */
  109506. _this.persistence = 0.8;
  109507. /** Gets or sets animation speed factor (default is 1) */
  109508. _this.animationSpeedFactor = 1;
  109509. _this._updateShaderUniforms();
  109510. return _this;
  109511. }
  109512. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  109513. var scene = this.getScene();
  109514. if (!scene) {
  109515. return;
  109516. }
  109517. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  109518. this.setFloat("brightness", this.brightness);
  109519. this.setFloat("persistence", this.persistence);
  109520. this.setFloat("timeScale", this._time);
  109521. };
  109522. NoiseProceduralTexture.prototype._getDefines = function () {
  109523. return "#define OCTAVES " + (this.octaves | 0);
  109524. };
  109525. /** Generate the current state of the procedural texture */
  109526. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  109527. this._updateShaderUniforms();
  109528. _super.prototype.render.call(this, useCameraPostProcess);
  109529. };
  109530. /**
  109531. * Serializes this noise procedural texture
  109532. * @returns a serialized noise procedural texture object
  109533. */
  109534. NoiseProceduralTexture.prototype.serialize = function () {
  109535. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  109536. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  109537. return serializationObject;
  109538. };
  109539. /**
  109540. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  109541. * @param parsedTexture defines parsed texture data
  109542. * @param scene defines the current scene
  109543. * @param rootUrl defines the root URL containing noise procedural texture information
  109544. * @returns a parsed NoiseProceduralTexture
  109545. */
  109546. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  109547. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  109548. return texture;
  109549. };
  109550. return NoiseProceduralTexture;
  109551. }(BABYLON.ProceduralTexture));
  109552. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  109553. })(BABYLON || (BABYLON = {}));
  109554. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  109555. var __assign = (this && this.__assign) || function () {
  109556. __assign = Object.assign || function(t) {
  109557. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109558. s = arguments[i];
  109559. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109560. t[p] = s[p];
  109561. }
  109562. return t;
  109563. };
  109564. return __assign.apply(this, arguments);
  109565. };
  109566. var BABYLON;
  109567. (function (BABYLON) {
  109568. /**
  109569. * This can helps recording videos from BabylonJS.
  109570. * This is based on the available WebRTC functionalities of the browser.
  109571. *
  109572. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  109573. */
  109574. var VideoRecorder = /** @class */ (function () {
  109575. /**
  109576. * Create a new VideoCapture object which can help converting what you see in Babylon to
  109577. * a video file.
  109578. * @param engine Defines the BabylonJS Engine you wish to record
  109579. * @param options Defines options that can be used to customized the capture
  109580. */
  109581. function VideoRecorder(engine, options) {
  109582. if (options === void 0) { options = null; }
  109583. if (!VideoRecorder.IsSupported(engine)) {
  109584. throw "Your browser does not support recording so far.";
  109585. }
  109586. var canvas = engine.getRenderingCanvas();
  109587. if (!canvas) {
  109588. throw "The babylon engine must have a canvas to be recorded";
  109589. }
  109590. this._canvas = canvas;
  109591. this._canvas.isRecording = false;
  109592. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  109593. var stream = this._canvas.captureStream(this._options.fps);
  109594. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  109595. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  109596. this._mediaRecorder.onerror = this._handleError.bind(this);
  109597. this._mediaRecorder.onstop = this._handleStop.bind(this);
  109598. }
  109599. /**
  109600. * Returns wehther or not the VideoRecorder is available in your browser.
  109601. * @param engine Defines the Babylon Engine to check the support for
  109602. * @returns true if supported otherwise false
  109603. */
  109604. VideoRecorder.IsSupported = function (engine) {
  109605. var canvas = engine.getRenderingCanvas();
  109606. return (!!canvas && typeof canvas.captureStream === "function");
  109607. };
  109608. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  109609. /**
  109610. * True wether a recording is already in progress.
  109611. */
  109612. get: function () {
  109613. return !!this._canvas && this._canvas.isRecording;
  109614. },
  109615. enumerable: true,
  109616. configurable: true
  109617. });
  109618. /**
  109619. * Stops the current recording before the default capture timeout passed in the startRecording
  109620. * functions.
  109621. */
  109622. VideoRecorder.prototype.stopRecording = function () {
  109623. if (!this._canvas || !this._mediaRecorder) {
  109624. return;
  109625. }
  109626. if (!this.isRecording) {
  109627. return;
  109628. }
  109629. this._canvas.isRecording = false;
  109630. this._mediaRecorder.stop();
  109631. };
  109632. /**
  109633. * Starts recording the canvas for a max duration specified in parameters.
  109634. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  109635. * @param maxDuration Defines the maximum recording time in seconds.
  109636. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  109637. * @return a promise callback at the end of the recording with the video data in Blob.
  109638. */
  109639. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  109640. var _this = this;
  109641. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  109642. if (maxDuration === void 0) { maxDuration = 7; }
  109643. if (!this._canvas || !this._mediaRecorder) {
  109644. throw "Recorder has already been disposed";
  109645. }
  109646. if (this.isRecording) {
  109647. throw "Recording already in progress";
  109648. }
  109649. if (maxDuration > 0) {
  109650. setTimeout(function () {
  109651. _this.stopRecording();
  109652. }, maxDuration * 1000);
  109653. }
  109654. this._fileName = fileName;
  109655. this._recordedChunks = [];
  109656. this._resolve = null;
  109657. this._reject = null;
  109658. this._canvas.isRecording = true;
  109659. this._mediaRecorder.start(this._options.recordChunckSize);
  109660. return new Promise(function (resolve, reject) {
  109661. _this._resolve = resolve;
  109662. _this._reject = reject;
  109663. });
  109664. };
  109665. /**
  109666. * Releases internal resources used during the recording.
  109667. */
  109668. VideoRecorder.prototype.dispose = function () {
  109669. this._canvas = null;
  109670. this._mediaRecorder = null;
  109671. this._recordedChunks = [];
  109672. this._fileName = null;
  109673. this._resolve = null;
  109674. this._reject = null;
  109675. };
  109676. VideoRecorder.prototype._handleDataAvailable = function (event) {
  109677. if (event.data.size > 0) {
  109678. this._recordedChunks.push(event.data);
  109679. }
  109680. };
  109681. VideoRecorder.prototype._handleError = function (event) {
  109682. this.stopRecording();
  109683. if (this._reject) {
  109684. this._reject(event.error);
  109685. }
  109686. else {
  109687. throw new event.error;
  109688. }
  109689. };
  109690. VideoRecorder.prototype._handleStop = function () {
  109691. this.stopRecording();
  109692. var superBuffer = new Blob(this._recordedChunks);
  109693. if (this._resolve) {
  109694. this._resolve(superBuffer);
  109695. }
  109696. window.URL.createObjectURL(superBuffer);
  109697. if (this._fileName) {
  109698. BABYLON.Tools.Download(superBuffer, this._fileName);
  109699. }
  109700. };
  109701. VideoRecorder._defaultOptions = {
  109702. mimeType: "video/webm",
  109703. fps: 25,
  109704. recordChunckSize: 3000
  109705. };
  109706. return VideoRecorder;
  109707. }());
  109708. BABYLON.VideoRecorder = VideoRecorder;
  109709. })(BABYLON || (BABYLON = {}));
  109710. //# sourceMappingURL=babylon.videoRecorder.js.map
  109711. var BABYLON;
  109712. (function (BABYLON) {
  109713. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  109714. if (replace === void 0) { replace = false; }
  109715. // Dispose existing light in replace mode.
  109716. if (replace) {
  109717. if (this.lights) {
  109718. for (var i = 0; i < this.lights.length; i++) {
  109719. this.lights[i].dispose();
  109720. }
  109721. }
  109722. }
  109723. // Light
  109724. if (this.lights.length === 0) {
  109725. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  109726. }
  109727. };
  109728. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  109729. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109730. if (replace === void 0) { replace = false; }
  109731. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109732. // Dispose existing camera in replace mode.
  109733. if (replace) {
  109734. if (this.activeCamera) {
  109735. this.activeCamera.dispose();
  109736. this.activeCamera = null;
  109737. }
  109738. }
  109739. // Camera
  109740. if (!this.activeCamera) {
  109741. var worldExtends = this.getWorldExtends();
  109742. var worldSize = worldExtends.max.subtract(worldExtends.min);
  109743. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  109744. var camera;
  109745. var radius = worldSize.length() * 1.5;
  109746. // empty scene scenario!
  109747. if (!isFinite(radius)) {
  109748. radius = 1;
  109749. worldCenter.copyFromFloats(0, 0, 0);
  109750. }
  109751. if (createArcRotateCamera) {
  109752. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  109753. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  109754. arcRotateCamera.wheelPrecision = 100 / radius;
  109755. camera = arcRotateCamera;
  109756. }
  109757. else {
  109758. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  109759. freeCamera.setTarget(worldCenter);
  109760. camera = freeCamera;
  109761. }
  109762. camera.minZ = radius * 0.01;
  109763. camera.maxZ = radius * 1000;
  109764. camera.speed = radius * 0.2;
  109765. this.activeCamera = camera;
  109766. var canvas = this.getEngine().getRenderingCanvas();
  109767. if (attachCameraControls && canvas) {
  109768. camera.attachControl(canvas);
  109769. }
  109770. }
  109771. };
  109772. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  109773. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109774. if (replace === void 0) { replace = false; }
  109775. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109776. this.createDefaultLight(replace);
  109777. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  109778. };
  109779. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  109780. if (pbr === void 0) { pbr = false; }
  109781. if (scale === void 0) { scale = 1000; }
  109782. if (blur === void 0) { blur = 0; }
  109783. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  109784. if (!environmentTexture) {
  109785. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  109786. return null;
  109787. }
  109788. if (setGlobalEnvTexture) {
  109789. if (environmentTexture) {
  109790. this.environmentTexture = environmentTexture;
  109791. }
  109792. }
  109793. // Skybox
  109794. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  109795. if (pbr) {
  109796. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  109797. hdrSkyboxMaterial.backFaceCulling = false;
  109798. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  109799. if (hdrSkyboxMaterial.reflectionTexture) {
  109800. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109801. }
  109802. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  109803. hdrSkyboxMaterial.disableLighting = true;
  109804. hdrSkyboxMaterial.twoSidedLighting = true;
  109805. hdrSkybox.infiniteDistance = true;
  109806. hdrSkybox.material = hdrSkyboxMaterial;
  109807. }
  109808. else {
  109809. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  109810. skyboxMaterial.backFaceCulling = false;
  109811. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  109812. if (skyboxMaterial.reflectionTexture) {
  109813. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109814. }
  109815. skyboxMaterial.disableLighting = true;
  109816. hdrSkybox.infiniteDistance = true;
  109817. hdrSkybox.material = skyboxMaterial;
  109818. }
  109819. return hdrSkybox;
  109820. };
  109821. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  109822. if (BABYLON.EnvironmentHelper) {
  109823. return new BABYLON.EnvironmentHelper(options, this);
  109824. }
  109825. return null;
  109826. };
  109827. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  109828. if (webVROptions === void 0) { webVROptions = {}; }
  109829. return new BABYLON.VRExperienceHelper(this, webVROptions);
  109830. };
  109831. })(BABYLON || (BABYLON = {}));
  109832. //# sourceMappingURL=babylon.sceneHelpers.js.map
  109833. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  109834. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  109835. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  109836. globalObject["BABYLON"] = BABYLON;
  109837. //backwards compatibility
  109838. if(typeof earcut !== 'undefined') {
  109839. globalObject["Earcut"] = {
  109840. earcut: earcut
  109841. };
  109842. }
  109843. return BABYLON;
  109844. });